clarity-js 0.7.65 → 0.7.67

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/README.md +26 -26
  2. package/build/clarity.extended.js +1 -1
  3. package/build/clarity.insight.js +1 -1
  4. package/build/clarity.js +5410 -5355
  5. package/build/clarity.min.js +1 -1
  6. package/build/clarity.module.js +5410 -5355
  7. package/build/clarity.performance.js +1 -1
  8. package/package.json +70 -70
  9. package/rollup.config.ts +98 -98
  10. package/src/clarity.ts +60 -60
  11. package/src/core/api.ts +8 -8
  12. package/src/core/config.ts +32 -32
  13. package/src/core/copy.ts +3 -3
  14. package/src/core/event.ts +26 -26
  15. package/src/core/hash.ts +19 -19
  16. package/src/core/history.ts +73 -73
  17. package/src/core/index.ts +83 -83
  18. package/src/core/measure.ts +19 -19
  19. package/src/core/report.ts +28 -28
  20. package/src/core/scrub.ts +196 -196
  21. package/src/core/task.ts +180 -180
  22. package/src/core/time.ts +19 -19
  23. package/src/core/timeout.ts +10 -10
  24. package/src/core/version.ts +2 -2
  25. package/src/data/baseline.ts +123 -92
  26. package/src/data/compress.ts +31 -31
  27. package/src/data/consent.ts +20 -20
  28. package/src/data/custom.ts +23 -23
  29. package/src/data/dimension.ts +53 -53
  30. package/src/data/encode.ts +134 -127
  31. package/src/data/envelope.ts +53 -53
  32. package/src/data/extract.ts +204 -204
  33. package/src/data/index.ts +46 -46
  34. package/src/data/limit.ts +44 -44
  35. package/src/data/metadata.ts +356 -356
  36. package/src/data/metric.ts +51 -51
  37. package/src/data/ping.ts +36 -36
  38. package/src/data/signal.ts +30 -30
  39. package/src/data/summary.ts +34 -34
  40. package/src/data/token.ts +39 -39
  41. package/src/data/upgrade.ts +37 -37
  42. package/src/data/upload.ts +283 -283
  43. package/src/data/variable.ts +83 -83
  44. package/src/diagnostic/encode.ts +40 -40
  45. package/src/diagnostic/fraud.ts +36 -36
  46. package/src/diagnostic/index.ts +15 -15
  47. package/src/diagnostic/internal.ts +28 -28
  48. package/src/diagnostic/script.ts +37 -37
  49. package/src/global.ts +6 -6
  50. package/src/index.ts +9 -9
  51. package/src/insight/blank.ts +14 -14
  52. package/src/insight/encode.ts +60 -60
  53. package/src/insight/snapshot.ts +114 -114
  54. package/src/interaction/change.ts +40 -40
  55. package/src/interaction/click.ts +156 -156
  56. package/src/interaction/clipboard.ts +34 -34
  57. package/src/interaction/encode.ts +191 -191
  58. package/src/interaction/index.ts +59 -59
  59. package/src/interaction/input.ts +59 -59
  60. package/src/interaction/pointer.ts +139 -139
  61. package/src/interaction/resize.ts +47 -47
  62. package/src/interaction/scroll.ts +124 -124
  63. package/src/interaction/selection.ts +68 -68
  64. package/src/interaction/submit.ts +32 -32
  65. package/src/interaction/timeline.ts +65 -65
  66. package/src/interaction/unload.ts +28 -28
  67. package/src/interaction/visibility.ts +26 -26
  68. package/src/layout/animation.ts +133 -133
  69. package/src/layout/discover.ts +31 -31
  70. package/src/layout/document.ts +48 -48
  71. package/src/layout/dom.ts +414 -414
  72. package/src/layout/encode.ts +145 -145
  73. package/src/layout/index.ts +41 -41
  74. package/src/layout/mutation.ts +340 -340
  75. package/src/layout/node.ts +264 -264
  76. package/src/layout/offset.ts +19 -19
  77. package/src/layout/region.ts +153 -153
  78. package/src/layout/schema.ts +63 -63
  79. package/src/layout/selector.ts +82 -82
  80. package/src/layout/style.ts +149 -149
  81. package/src/layout/target.ts +32 -32
  82. package/src/layout/traverse.ts +27 -27
  83. package/src/performance/blank.ts +7 -7
  84. package/src/performance/encode.ts +31 -31
  85. package/src/performance/index.ts +14 -14
  86. package/src/performance/interaction.ts +125 -125
  87. package/src/performance/navigation.ts +31 -31
  88. package/src/performance/observer.ts +108 -108
  89. package/src/queue.ts +33 -33
  90. package/test/core.test.ts +139 -139
  91. package/test/helper.ts +162 -162
  92. package/test/html/core.html +27 -27
  93. package/test/tsconfig.test.json +5 -5
  94. package/tsconfig.json +21 -21
  95. package/tslint.json +32 -32
  96. package/types/core.d.ts +151 -151
  97. package/types/data.d.ts +504 -497
  98. package/types/diagnostic.d.ts +24 -24
  99. package/types/index.d.ts +39 -39
  100. package/types/interaction.d.ts +157 -157
  101. package/types/layout.d.ts +273 -273
  102. package/types/performance.d.ts +64 -64
@@ -1,340 +1,340 @@
1
- import { Priority, Task, Timer } from "@clarity-types/core";
2
- import { Code, Event, Metric, Severity } from "@clarity-types/data";
3
- import { Constant, MutationHistory, MutationRecordWithTime, MutationQueue, Setting, Source } from "@clarity-types/layout";
4
- import { FunctionNames } from "@clarity-types/performance";
5
- import api from "@src/core/api";
6
- import * as core from "@src/core";
7
- import { bind } from "@src/core/event";
8
- import measure from "@src/core/measure";
9
- import * as task from "@src/core/task";
10
- import { time } from "@src/core/time";
11
- import { clearTimeout, setTimeout } from "@src/core/timeout";
12
- import { id } from "@src/data/metadata";
13
- import * as summary from "@src/data/summary";
14
- import * as internal from "@src/diagnostic/internal";
15
- import * as doc from "@src/layout/document";
16
- import * as dom from "@src/layout/dom";
17
- import * as metric from "@src/data/metric";
18
- import encode from "@src/layout/encode";
19
- import * as region from "@src/layout/region";
20
- import traverse from "@src/layout/traverse";
21
- import processNode from "./node";
22
- import config from "@src/core/config";
23
-
24
- let observers: MutationObserver[] = [];
25
- let mutations: MutationQueue[] = [];
26
- let throttledMutations: { [key: number]: MutationRecordWithTime } = {};
27
- let insertRule: (rule: string, index?: number) => number = null;
28
- let deleteRule: (index?: number) => void = null;
29
- let attachShadow: (init: ShadowRootInit) => ShadowRoot = null;
30
- let mediaInsertRule: (rule: string, index?: number) => number = null;
31
- let mediaDeleteRule: (index?: number) => void = null;
32
- let queue: Node[] = [];
33
- let timeout: number = null;
34
- let throttleDelay: number = null;
35
- let activePeriod = null;
36
- let history: MutationHistory = {};
37
- let criticalPeriod = null;
38
-
39
- export function start(): void {
40
- observers = [];
41
- queue = [];
42
- timeout = null;
43
- activePeriod = 0;
44
- history = {};
45
- criticalPeriod = 0;
46
-
47
- // Some popular open source libraries, like styled-components, optimize performance
48
- // by injecting CSS using insertRule API vs. appending text node. A side effect of
49
- // using javascript API is that it doesn't trigger DOM mutation and therefore we
50
- // need to override the insertRule API and listen for changes manually.
51
- if (insertRule === null) {
52
- insertRule = CSSStyleSheet.prototype.insertRule;
53
- CSSStyleSheet.prototype.insertRule = function(): number {
54
- if (core.active()) { schedule(this.ownerNode); }
55
- return insertRule.apply(this, arguments);
56
- };
57
- }
58
-
59
- if ("CSSMediaRule" in window && mediaInsertRule === null) {
60
- mediaInsertRule = CSSMediaRule.prototype.insertRule;
61
- CSSMediaRule.prototype.insertRule = function(): number {
62
- if (core.active()) { schedule(this.parentStyleSheet.ownerNode); }
63
- return mediaInsertRule.apply(this, arguments);
64
- };
65
- }
66
-
67
- if (deleteRule === null) {
68
- deleteRule = CSSStyleSheet.prototype.deleteRule;
69
- CSSStyleSheet.prototype.deleteRule = function(): void {
70
- if (core.active()) { schedule(this.ownerNode); }
71
- return deleteRule.apply(this, arguments);
72
- };
73
- }
74
-
75
- if ("CSSMediaRule" in window && mediaDeleteRule === null) {
76
- mediaDeleteRule = CSSMediaRule.prototype.deleteRule;
77
- CSSMediaRule.prototype.deleteRule = function(): void {
78
- if (core.active()) { schedule(this.parentStyleSheet.ownerNode); }
79
- return mediaDeleteRule.apply(this, arguments);
80
- };
81
- }
82
-
83
- // Add a hook to attachShadow API calls
84
- // In case we are unable to add a hook and browser throws an exception,
85
- // reset attachShadow variable and resume processing like before
86
- if (attachShadow === null) {
87
- attachShadow = Element.prototype.attachShadow;
88
- try {
89
- Element.prototype.attachShadow = function (): ShadowRoot {
90
- if (core.active()) { return schedule(attachShadow.apply(this, arguments)) as ShadowRoot; }
91
- else { return attachShadow.apply(this, arguments)}
92
- }
93
- } catch { attachShadow = null; }
94
- }
95
- }
96
- start.dn = FunctionNames.MutationStart;
97
-
98
- export function observe(node: Node): void {
99
- // Create a new observer for every time a new DOM tree (e.g. root document or shadowdom root) is discovered on the page
100
- // In the case of shadow dom, any mutations that happen within the shadow dom are not bubbled up to the host document
101
- // For this reason, we need to wire up mutations every time we see a new shadow dom.
102
- // Also, wrap it inside a try / catch. In certain browsers (e.g. legacy Edge), observer on shadow dom can throw errors
103
- try {
104
- let m = api(Constant.MutationObserver);
105
- let observer = m in window ? new window[m](measure(handle) as MutationCallback) : null;
106
- if (observer) {
107
- observer.observe(node, { attributes: true, childList: true, characterData: true, subtree: true });
108
- observers.push(observer);
109
- }
110
- } catch (e) { internal.log(Code.MutationObserver, Severity.Info, e ? e.name : null); }
111
- }
112
-
113
- export function monitor(frame: HTMLIFrameElement): void {
114
- // Bind to iframe's onload event so we get notified anytime there's an update to iframe content.
115
- // This includes cases where iframe location is updated without explicitly updating src attribute
116
- // E.g. iframe.contentWindow.location.href = "new-location";
117
- if (dom.has(frame) === false) {
118
- bind(frame, Constant.LoadEvent, generate.bind(this, frame, Constant.ChildList), true);
119
- }
120
- }
121
-
122
- export function stop(): void {
123
- for (let observer of observers) { if (observer) { observer.disconnect(); } }
124
- observers = [];
125
- history = {};
126
- mutations = [];
127
- throttledMutations = [];
128
- queue = [];
129
- activePeriod = 0;
130
- timeout = null;
131
- criticalPeriod = 0;
132
- }
133
-
134
- export function active(): void {
135
- activePeriod = time() + Setting.MutationActivePeriod;
136
- criticalPeriod = time() + config.criticalMs;
137
- }
138
-
139
- function handle(m: MutationRecord[]): void {
140
- // Queue up mutation records for asynchronous processing
141
- let now = time();
142
- summary.track(Event.Mutation, now);
143
- mutations.push({ time: now, mutations: m});
144
- task.schedule(process, Priority.High).then((): void => {
145
- setTimeout(doc.compute)
146
- measure(region.compute)();
147
- });
148
- }
149
- handle.dn = FunctionNames.MutationHandle;
150
-
151
- async function processMutation(timer: Timer, mutation: MutationRecord, instance: number, timestamp: number): Promise<void> {
152
- let state = task.state(timer);
153
- if (state === Task.Wait) { state = await task.suspend(timer); }
154
- if (state === Task.Stop) { return; }
155
- let target = mutation.target;
156
- let type = config.throttleDom ? track(mutation, timer, instance, timestamp) : mutation.type;
157
- if (type && target && target.ownerDocument) { dom.parse(target.ownerDocument); }
158
- if (type && target && target.nodeType == Node.DOCUMENT_FRAGMENT_NODE && (target as ShadowRoot).host) { dom.parse(target as ShadowRoot); }
159
- switch (type) {
160
- case Constant.Attributes:
161
- processNode(target, Source.Attributes, timestamp);
162
- break;
163
- case Constant.CharacterData:
164
- processNode(target, Source.CharacterData, timestamp);
165
- break;
166
- case Constant.ChildList:
167
- processNodeList(mutation.addedNodes, Source.ChildListAdd, timer, timestamp);
168
- processNodeList(mutation.removedNodes, Source.ChildListRemove, timer, timestamp);
169
- break;
170
- case Constant.Throttle:
171
- default:
172
- break;
173
- }
174
- }
175
- async function process(): Promise<void> {
176
- let timer: Timer = { id: id(), cost: Metric.LayoutCost };
177
- task.start(timer);
178
- while (mutations.length > 0) {
179
- let record = mutations.shift();
180
- let instance = time();
181
- for (let mutation of record.mutations) {
182
- processMutation(timer, mutation, instance, record.time)
183
- }
184
- await encode(Event.Mutation, timer, record.time);
185
- }
186
-
187
- let processedMutations = false;
188
- for (var key of Object.keys(throttledMutations)) {
189
- let throttledMutationToProcess: MutationRecordWithTime = throttledMutations[key];
190
- delete throttledMutations[key];
191
- processMutation(timer, throttledMutationToProcess.mutation, time(), throttledMutationToProcess.timestamp);
192
- processedMutations = true;
193
- }
194
-
195
- if (Object.keys(throttledMutations).length > 0) {
196
- processThrottledMutations();
197
- }
198
-
199
- // ensure we encode the previously throttled mutations once we have finished them
200
- if (Object.keys(throttledMutations).length === 0 && processedMutations) {
201
- await encode(Event.Mutation, timer, time());
202
- }
203
-
204
- cleanHistory();
205
-
206
- task.stop(timer);
207
- }
208
-
209
- function cleanHistory(): void {
210
- let now = time();
211
- if (Object.keys(history).length > Setting.MaxMutationHistoryCount) {
212
- history = {};
213
- metric.count(Metric.HistoryClear);
214
- }
215
-
216
- for (let key of Object.keys(history)) {
217
- let h = history[key];
218
- if (now > h[1] + Setting.MaxMutationHistoryTime) {
219
- delete history[key];
220
- }
221
- }
222
- }
223
-
224
- function track(m: MutationRecord, timer: Timer, instance: number, timestamp: number): string {
225
- let value = m.target ? dom.get(m.target.parentNode) : null;
226
- // Check if the parent is already discovered and that the parent is not the document root
227
- if (value && value.data.tag !== Constant.HTML) {
228
- // calculate inactive period based on the timestamp of the mutation not when the mutation is processed
229
- let inactive = timestamp > activePeriod;
230
- // Calculate critical period based on when mutation is processed
231
- const critical = instance < criticalPeriod;
232
- let target = dom.get(m.target);
233
- let element = target && target.selector ? target.selector.join() : m.target.nodeName;
234
- let parent = value.selector ? value.selector.join() : Constant.Empty;
235
- // Check if its a low priority (e.g., ads related) element mutation happening during critical period
236
- // If the discard list is empty, we discard all mutations during critical period
237
- const lowPriMutation =
238
- config.throttleMutations && critical &&
239
- (config.discard.length === 0 || config.discard.some((key) => element.includes(key)));
240
- // We use selector, instead of id, to determine the key (signature for the mutation) because in some cases
241
- // repeated mutations can cause elements to be destroyed and then recreated as new DOM nodes
242
- // In those cases, IDs will change however the selector (which is relative to DOM xPath) remains the same
243
- let key = [parent, element, m.attributeName, names(m.addedNodes), names(m.removedNodes)].join();
244
- // Initialize an entry if it doesn't already exist
245
- history[key] = key in history ? history[key] : [0, instance];
246
- let h = history[key];
247
- // Lookup any pending nodes queued up for removal, and process them now if we suspended a mutation before
248
- if (inactive === false && h[0] >= Setting.MutationSuspendThreshold) { processNodeList(h[2], Source.ChildListRemove, timer, timestamp); }
249
-
250
- // Update the counter, do not reset counter if its critical period
251
- h[0] = inactive || lowPriMutation ? (h[1] === instance ? h[0] : h[0] + 1) : 1;
252
- h[1] = instance;
253
- // Return updated mutation type based on,
254
- // 1. if we have already hit the threshold or not
255
- // 2. if its a low priority mutation happening during critical time period
256
- if (h[0] >= Setting.MutationSuspendThreshold || lowPriMutation) {
257
- // Store a reference to removedNodes so we can process them later
258
- // when we resume mutations again on user interactions
259
- h[2] = m.removedNodes;
260
- if (instance > timestamp + Setting.MutationActivePeriod) {
261
- return m.type;
262
- }
263
- if (!config.dropMutations) {
264
- // we only store the most recent mutation for a given key if it is being throttled
265
- throttledMutations[key] = {mutation: m, timestamp};
266
- }
267
- return Constant.Throttle;
268
- }
269
- }
270
- return m.type;
271
- }
272
-
273
- function names(nodes: NodeList): string {
274
- let output: string[] = [];
275
- for (let i = 0; nodes && i < nodes.length; i++) { output.push(nodes[i].nodeName); }
276
- return output.join();
277
- }
278
-
279
- async function processNodeList(list: NodeList, source: Source, timer: Timer, timestamp: number): Promise<void> {
280
- let length = list ? list.length : 0;
281
- for (let i = 0; i < length; i++) {
282
- const node = list[i];
283
- if (source === Source.ChildListAdd) {
284
- traverse(node, timer, source, timestamp);
285
- } else {
286
- let state = task.state(timer);
287
- if (state === Task.Wait) { state = await task.suspend(timer); }
288
- if (state === Task.Stop) { break; }
289
- processNode(node, source, timestamp);
290
- }
291
- }
292
- }
293
-
294
- function processThrottledMutations(): void {
295
- if (throttleDelay) {
296
- clearTimeout(throttleDelay);
297
- }
298
- throttleDelay = setTimeout(() => { task.schedule(process, Priority.High) }, Setting.LookAhead);
299
- }
300
-
301
- export function schedule(node: Node): Node {
302
- // Only schedule manual trigger for this node if it's not already in the queue
303
- if (queue.indexOf(node) < 0) { queue.push(node); }
304
-
305
- // Cancel any previous trigger before scheduling a new one.
306
- // It's common for a webpage to call multiple synchronous "insertRule" / "deleteRule" calls.
307
- // And in those cases we do not wish to monitor changes multiple times for the same node.
308
- if (timeout) { clearTimeout(timeout); }
309
- timeout = setTimeout(() => { trigger() }, Setting.LookAhead);
310
-
311
- return node;
312
- }
313
-
314
- function trigger(): void {
315
- for (let node of queue) {
316
- // Generate a mutation for this node only if it still exists
317
- if (node) {
318
- let shadowRoot = node.nodeType === Node.DOCUMENT_FRAGMENT_NODE;
319
- // Skip re-processing shadowRoot if it was already discovered
320
- if (shadowRoot && dom.has(node)) { continue; }
321
- generate(node, shadowRoot ? Constant.ChildList : Constant.CharacterData);
322
- }
323
- }
324
- queue = [];
325
- }
326
-
327
- function generate(target: Node, type: MutationRecordType): void {
328
- measure(handle)([{
329
- addedNodes: [target],
330
- attributeName: null,
331
- attributeNamespace: null,
332
- nextSibling: null,
333
- oldValue: null,
334
- previousSibling: null,
335
- removedNodes: [],
336
- target,
337
- type
338
- }]);
339
- }
340
- generate.dn = FunctionNames.MutationGenerate;
1
+ import { Priority, Task, Timer } from "@clarity-types/core";
2
+ import { Code, Event, Metric, Severity } from "@clarity-types/data";
3
+ import { Constant, MutationHistory, MutationRecordWithTime, MutationQueue, Setting, Source } from "@clarity-types/layout";
4
+ import { FunctionNames } from "@clarity-types/performance";
5
+ import api from "@src/core/api";
6
+ import * as core from "@src/core";
7
+ import { bind } from "@src/core/event";
8
+ import measure from "@src/core/measure";
9
+ import * as task from "@src/core/task";
10
+ import { time } from "@src/core/time";
11
+ import { clearTimeout, setTimeout } from "@src/core/timeout";
12
+ import { id } from "@src/data/metadata";
13
+ import * as summary from "@src/data/summary";
14
+ import * as internal from "@src/diagnostic/internal";
15
+ import * as doc from "@src/layout/document";
16
+ import * as dom from "@src/layout/dom";
17
+ import * as metric from "@src/data/metric";
18
+ import encode from "@src/layout/encode";
19
+ import * as region from "@src/layout/region";
20
+ import traverse from "@src/layout/traverse";
21
+ import processNode from "./node";
22
+ import config from "@src/core/config";
23
+
24
+ let observers: MutationObserver[] = [];
25
+ let mutations: MutationQueue[] = [];
26
+ let throttledMutations: { [key: number]: MutationRecordWithTime } = {};
27
+ let insertRule: (rule: string, index?: number) => number = null;
28
+ let deleteRule: (index?: number) => void = null;
29
+ let attachShadow: (init: ShadowRootInit) => ShadowRoot = null;
30
+ let mediaInsertRule: (rule: string, index?: number) => number = null;
31
+ let mediaDeleteRule: (index?: number) => void = null;
32
+ let queue: Node[] = [];
33
+ let timeout: number = null;
34
+ let throttleDelay: number = null;
35
+ let activePeriod = null;
36
+ let history: MutationHistory = {};
37
+ let criticalPeriod = null;
38
+
39
+ export function start(): void {
40
+ start.dn = FunctionNames.MutationStart;
41
+ observers = [];
42
+ queue = [];
43
+ timeout = null;
44
+ activePeriod = 0;
45
+ history = {};
46
+ criticalPeriod = 0;
47
+
48
+ // Some popular open source libraries, like styled-components, optimize performance
49
+ // by injecting CSS using insertRule API vs. appending text node. A side effect of
50
+ // using javascript API is that it doesn't trigger DOM mutation and therefore we
51
+ // need to override the insertRule API and listen for changes manually.
52
+ if (insertRule === null) {
53
+ insertRule = CSSStyleSheet.prototype.insertRule;
54
+ CSSStyleSheet.prototype.insertRule = function(): number {
55
+ if (core.active()) { schedule(this.ownerNode); }
56
+ return insertRule.apply(this, arguments);
57
+ };
58
+ }
59
+
60
+ if ("CSSMediaRule" in window && mediaInsertRule === null) {
61
+ mediaInsertRule = CSSMediaRule.prototype.insertRule;
62
+ CSSMediaRule.prototype.insertRule = function(): number {
63
+ if (core.active()) { schedule(this.parentStyleSheet.ownerNode); }
64
+ return mediaInsertRule.apply(this, arguments);
65
+ };
66
+ }
67
+
68
+ if (deleteRule === null) {
69
+ deleteRule = CSSStyleSheet.prototype.deleteRule;
70
+ CSSStyleSheet.prototype.deleteRule = function(): void {
71
+ if (core.active()) { schedule(this.ownerNode); }
72
+ return deleteRule.apply(this, arguments);
73
+ };
74
+ }
75
+
76
+ if ("CSSMediaRule" in window && mediaDeleteRule === null) {
77
+ mediaDeleteRule = CSSMediaRule.prototype.deleteRule;
78
+ CSSMediaRule.prototype.deleteRule = function(): void {
79
+ if (core.active()) { schedule(this.parentStyleSheet.ownerNode); }
80
+ return mediaDeleteRule.apply(this, arguments);
81
+ };
82
+ }
83
+
84
+ // Add a hook to attachShadow API calls
85
+ // In case we are unable to add a hook and browser throws an exception,
86
+ // reset attachShadow variable and resume processing like before
87
+ if (attachShadow === null) {
88
+ attachShadow = Element.prototype.attachShadow;
89
+ try {
90
+ Element.prototype.attachShadow = function (): ShadowRoot {
91
+ if (core.active()) { return schedule(attachShadow.apply(this, arguments)) as ShadowRoot; }
92
+ else { return attachShadow.apply(this, arguments)}
93
+ }
94
+ } catch { attachShadow = null; }
95
+ }
96
+ }
97
+
98
+ export function observe(node: Node): void {
99
+ // Create a new observer for every time a new DOM tree (e.g. root document or shadowdom root) is discovered on the page
100
+ // In the case of shadow dom, any mutations that happen within the shadow dom are not bubbled up to the host document
101
+ // For this reason, we need to wire up mutations every time we see a new shadow dom.
102
+ // Also, wrap it inside a try / catch. In certain browsers (e.g. legacy Edge), observer on shadow dom can throw errors
103
+ try {
104
+ let m = api(Constant.MutationObserver);
105
+ let observer = m in window ? new window[m](measure(handle) as MutationCallback) : null;
106
+ if (observer) {
107
+ observer.observe(node, { attributes: true, childList: true, characterData: true, subtree: true });
108
+ observers.push(observer);
109
+ }
110
+ } catch (e) { internal.log(Code.MutationObserver, Severity.Info, e ? e.name : null); }
111
+ }
112
+
113
+ export function monitor(frame: HTMLIFrameElement): void {
114
+ // Bind to iframe's onload event so we get notified anytime there's an update to iframe content.
115
+ // This includes cases where iframe location is updated without explicitly updating src attribute
116
+ // E.g. iframe.contentWindow.location.href = "new-location";
117
+ if (dom.has(frame) === false) {
118
+ bind(frame, Constant.LoadEvent, generate.bind(this, frame, Constant.ChildList), true);
119
+ }
120
+ }
121
+
122
+ export function stop(): void {
123
+ for (let observer of observers) { if (observer) { observer.disconnect(); } }
124
+ observers = [];
125
+ history = {};
126
+ mutations = [];
127
+ throttledMutations = [];
128
+ queue = [];
129
+ activePeriod = 0;
130
+ timeout = null;
131
+ criticalPeriod = 0;
132
+ }
133
+
134
+ export function active(): void {
135
+ activePeriod = time() + Setting.MutationActivePeriod;
136
+ criticalPeriod = time() + config.criticalMs;
137
+ }
138
+
139
+ function handle(m: MutationRecord[]): void {
140
+ handle.dn = FunctionNames.MutationHandle;
141
+ // Queue up mutation records for asynchronous processing
142
+ let now = time();
143
+ summary.track(Event.Mutation, now);
144
+ mutations.push({ time: now, mutations: m});
145
+ task.schedule(process, Priority.High).then((): void => {
146
+ setTimeout(doc.compute)
147
+ measure(region.compute)();
148
+ });
149
+ }
150
+
151
+ async function processMutation(timer: Timer, mutation: MutationRecord, instance: number, timestamp: number): Promise<void> {
152
+ let state = task.state(timer);
153
+ if (state === Task.Wait) { state = await task.suspend(timer); }
154
+ if (state === Task.Stop) { return; }
155
+ let target = mutation.target;
156
+ let type = config.throttleDom ? track(mutation, timer, instance, timestamp) : mutation.type;
157
+ if (type && target && target.ownerDocument) { dom.parse(target.ownerDocument); }
158
+ if (type && target && target.nodeType == Node.DOCUMENT_FRAGMENT_NODE && (target as ShadowRoot).host) { dom.parse(target as ShadowRoot); }
159
+ switch (type) {
160
+ case Constant.Attributes:
161
+ processNode(target, Source.Attributes, timestamp);
162
+ break;
163
+ case Constant.CharacterData:
164
+ processNode(target, Source.CharacterData, timestamp);
165
+ break;
166
+ case Constant.ChildList:
167
+ processNodeList(mutation.addedNodes, Source.ChildListAdd, timer, timestamp);
168
+ processNodeList(mutation.removedNodes, Source.ChildListRemove, timer, timestamp);
169
+ break;
170
+ case Constant.Throttle:
171
+ default:
172
+ break;
173
+ }
174
+ }
175
+ async function process(): Promise<void> {
176
+ let timer: Timer = { id: id(), cost: Metric.LayoutCost };
177
+ task.start(timer);
178
+ while (mutations.length > 0) {
179
+ let record = mutations.shift();
180
+ let instance = time();
181
+ for (let mutation of record.mutations) {
182
+ await processMutation(timer, mutation, instance, record.time)
183
+ }
184
+ await encode(Event.Mutation, timer, record.time);
185
+ }
186
+
187
+ let processedMutations = false;
188
+ for (var key of Object.keys(throttledMutations)) {
189
+ let throttledMutationToProcess: MutationRecordWithTime = throttledMutations[key];
190
+ delete throttledMutations[key];
191
+ await processMutation(timer, throttledMutationToProcess.mutation, time(), throttledMutationToProcess.timestamp);
192
+ processedMutations = true;
193
+ }
194
+
195
+ if (Object.keys(throttledMutations).length > 0) {
196
+ processThrottledMutations();
197
+ }
198
+
199
+ // ensure we encode the previously throttled mutations once we have finished them
200
+ if (Object.keys(throttledMutations).length === 0 && processedMutations) {
201
+ await encode(Event.Mutation, timer, time());
202
+ }
203
+
204
+ cleanHistory();
205
+
206
+ task.stop(timer);
207
+ }
208
+
209
+ function cleanHistory(): void {
210
+ let now = time();
211
+ if (Object.keys(history).length > Setting.MaxMutationHistoryCount) {
212
+ history = {};
213
+ metric.count(Metric.HistoryClear);
214
+ }
215
+
216
+ for (let key of Object.keys(history)) {
217
+ let h = history[key];
218
+ if (now > h[1] + Setting.MaxMutationHistoryTime) {
219
+ delete history[key];
220
+ }
221
+ }
222
+ }
223
+
224
+ function track(m: MutationRecord, timer: Timer, instance: number, timestamp: number): string {
225
+ let value = m.target ? dom.get(m.target.parentNode) : null;
226
+ // Check if the parent is already discovered and that the parent is not the document root
227
+ if (value && value.data.tag !== Constant.HTML) {
228
+ // calculate inactive period based on the timestamp of the mutation not when the mutation is processed
229
+ let inactive = timestamp > activePeriod;
230
+ // Calculate critical period based on when mutation is processed
231
+ const critical = instance < criticalPeriod;
232
+ let target = dom.get(m.target);
233
+ let element = target && target.selector ? target.selector.join() : m.target.nodeName;
234
+ let parent = value.selector ? value.selector.join() : Constant.Empty;
235
+ // Check if its a low priority (e.g., ads related) element mutation happening during critical period
236
+ // If the discard list is empty, we discard all mutations during critical period
237
+ const lowPriMutation =
238
+ config.throttleMutations && critical &&
239
+ (config.discard.length === 0 || config.discard.some((key) => element.includes(key)));
240
+ // We use selector, instead of id, to determine the key (signature for the mutation) because in some cases
241
+ // repeated mutations can cause elements to be destroyed and then recreated as new DOM nodes
242
+ // In those cases, IDs will change however the selector (which is relative to DOM xPath) remains the same
243
+ let key = [parent, element, m.attributeName, names(m.addedNodes), names(m.removedNodes)].join();
244
+ // Initialize an entry if it doesn't already exist
245
+ history[key] = key in history ? history[key] : [0, instance];
246
+ let h = history[key];
247
+ // Lookup any pending nodes queued up for removal, and process them now if we suspended a mutation before
248
+ if (inactive === false && h[0] >= Setting.MutationSuspendThreshold) { processNodeList(h[2], Source.ChildListRemove, timer, timestamp); }
249
+
250
+ // Update the counter, do not reset counter if its critical period
251
+ h[0] = inactive || lowPriMutation ? (h[1] === instance ? h[0] : h[0] + 1) : 1;
252
+ h[1] = instance;
253
+ // Return updated mutation type based on,
254
+ // 1. if we have already hit the threshold or not
255
+ // 2. if its a low priority mutation happening during critical time period
256
+ if (h[0] >= Setting.MutationSuspendThreshold || lowPriMutation) {
257
+ // Store a reference to removedNodes so we can process them later
258
+ // when we resume mutations again on user interactions
259
+ h[2] = m.removedNodes;
260
+ if (instance > timestamp + Setting.MutationActivePeriod) {
261
+ return m.type;
262
+ }
263
+ if (!config.dropMutations) {
264
+ // we only store the most recent mutation for a given key if it is being throttled
265
+ throttledMutations[key] = {mutation: m, timestamp};
266
+ }
267
+ return Constant.Throttle;
268
+ }
269
+ }
270
+ return m.type;
271
+ }
272
+
273
+ function names(nodes: NodeList): string {
274
+ let output: string[] = [];
275
+ for (let i = 0; nodes && i < nodes.length; i++) { output.push(nodes[i].nodeName); }
276
+ return output.join();
277
+ }
278
+
279
+ async function processNodeList(list: NodeList, source: Source, timer: Timer, timestamp: number): Promise<void> {
280
+ let length = list ? list.length : 0;
281
+ for (let i = 0; i < length; i++) {
282
+ const node = list[i];
283
+ if (source === Source.ChildListAdd) {
284
+ traverse(node, timer, source, timestamp);
285
+ } else {
286
+ let state = task.state(timer);
287
+ if (state === Task.Wait) { state = await task.suspend(timer); }
288
+ if (state === Task.Stop) { break; }
289
+ processNode(node, source, timestamp);
290
+ }
291
+ }
292
+ }
293
+
294
+ function processThrottledMutations(): void {
295
+ if (throttleDelay) {
296
+ clearTimeout(throttleDelay);
297
+ }
298
+ throttleDelay = setTimeout(() => { task.schedule(process, Priority.High) }, Setting.LookAhead);
299
+ }
300
+
301
+ export function schedule(node: Node): Node {
302
+ // Only schedule manual trigger for this node if it's not already in the queue
303
+ if (queue.indexOf(node) < 0) { queue.push(node); }
304
+
305
+ // Cancel any previous trigger before scheduling a new one.
306
+ // It's common for a webpage to call multiple synchronous "insertRule" / "deleteRule" calls.
307
+ // And in those cases we do not wish to monitor changes multiple times for the same node.
308
+ if (timeout) { clearTimeout(timeout); }
309
+ timeout = setTimeout(() => { trigger() }, Setting.LookAhead);
310
+
311
+ return node;
312
+ }
313
+
314
+ function trigger(): void {
315
+ for (let node of queue) {
316
+ // Generate a mutation for this node only if it still exists
317
+ if (node) {
318
+ let shadowRoot = node.nodeType === Node.DOCUMENT_FRAGMENT_NODE;
319
+ // Skip re-processing shadowRoot if it was already discovered
320
+ if (shadowRoot && dom.has(node)) { continue; }
321
+ generate(node, shadowRoot ? Constant.ChildList : Constant.CharacterData);
322
+ }
323
+ }
324
+ queue = [];
325
+ }
326
+
327
+ function generate(target: Node, type: MutationRecordType): void {
328
+ generate.dn = FunctionNames.MutationGenerate;
329
+ measure(handle)([{
330
+ addedNodes: [target],
331
+ attributeName: null,
332
+ attributeNamespace: null,
333
+ nextSibling: null,
334
+ oldValue: null,
335
+ previousSibling: null,
336
+ removedNodes: [],
337
+ target,
338
+ type
339
+ }]);
340
+ }