@cloudcare/browser-rum 2.1.5 → 2.2.0

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 (135) hide show
  1. package/README.md +1 -2
  2. package/bundle/dataflux-rum.js +1 -1
  3. package/cjs/boot/buildEnv.js +1 -1
  4. package/cjs/boot/rum.js +57 -48
  5. package/cjs/boot/rumPublicApi.js +169 -134
  6. package/cjs/domain/assembly.js +58 -44
  7. package/cjs/domain/configuration.js +67 -0
  8. package/cjs/domain/contexts/internalContext.js +45 -0
  9. package/cjs/domain/contexts/urlContexts.js +68 -0
  10. package/cjs/domain/contexts/viewContexts.js +43 -0
  11. package/cjs/domain/domMutationCollection.js +44 -31
  12. package/cjs/domain/{rumEventsCollection/view/trackLocationChanges.js → locationChangeObservable.js} +25 -25
  13. package/cjs/domain/performanceCollection.js +55 -24
  14. package/cjs/domain/requestCollection.js +117 -0
  15. package/cjs/domain/rumEventsCollection/actions/actionCollection.js +22 -4
  16. package/cjs/domain/rumEventsCollection/actions/clickChain.js +82 -0
  17. package/cjs/domain/rumEventsCollection/actions/computeFrustration.js +78 -0
  18. package/cjs/domain/rumEventsCollection/actions/getActionNameFromElement.js +60 -47
  19. package/cjs/domain/rumEventsCollection/actions/getSelectorsFromElement.js +163 -0
  20. package/cjs/domain/rumEventsCollection/actions/listenActionEvents.js +74 -0
  21. package/cjs/domain/rumEventsCollection/actions/trackClickActions.js +263 -0
  22. package/cjs/domain/rumEventsCollection/error/errorCollection.js +33 -53
  23. package/cjs/domain/rumEventsCollection/error/trackConsoleError.js +26 -0
  24. package/cjs/domain/rumEventsCollection/error/trackReportError.js +26 -0
  25. package/cjs/domain/rumEventsCollection/longTask/longTaskCollection.js +46 -17
  26. package/cjs/domain/rumEventsCollection/resource/resourceCollection.js +49 -9
  27. package/cjs/domain/rumEventsCollection/view/trackFirstHidden.js +7 -5
  28. package/cjs/domain/rumEventsCollection/view/trackInitialViewTimings.js +61 -24
  29. package/cjs/domain/rumEventsCollection/view/trackViewMetrics.js +91 -51
  30. package/cjs/domain/rumEventsCollection/view/trackViews.js +119 -86
  31. package/cjs/domain/rumEventsCollection/view/viewCollection.js +41 -31
  32. package/cjs/domain/rumSessionManager.js +95 -0
  33. package/cjs/domain/tracing/tracer.js +9 -10
  34. package/cjs/domain/trackEventCounts.js +9 -6
  35. package/cjs/domain/usr/index.js +30 -0
  36. package/cjs/domain/waitPageActivityEnd.js +163 -0
  37. package/cjs/transport/startRumBatch.js +38 -0
  38. package/esm/boot/buildEnv.js +1 -1
  39. package/esm/boot/rum.js +55 -48
  40. package/esm/boot/rumPublicApi.js +167 -135
  41. package/esm/domain/assembly.js +58 -44
  42. package/esm/domain/configuration.js +53 -0
  43. package/esm/domain/contexts/internalContext.js +38 -0
  44. package/esm/domain/contexts/urlContexts.js +58 -0
  45. package/esm/domain/contexts/viewContexts.js +32 -0
  46. package/esm/domain/domMutationCollection.js +43 -33
  47. package/esm/domain/{rumEventsCollection/view/trackLocationChanges.js → locationChangeObservable.js} +26 -24
  48. package/esm/domain/performanceCollection.js +56 -26
  49. package/esm/domain/requestCollection.js +102 -0
  50. package/esm/domain/rumEventsCollection/actions/actionCollection.js +23 -5
  51. package/esm/domain/rumEventsCollection/actions/clickChain.js +69 -0
  52. package/esm/domain/rumEventsCollection/actions/computeFrustration.js +64 -0
  53. package/esm/domain/rumEventsCollection/actions/getActionNameFromElement.js +60 -47
  54. package/esm/domain/rumEventsCollection/actions/getSelectorsFromElement.js +139 -0
  55. package/esm/domain/rumEventsCollection/actions/listenActionEvents.js +66 -0
  56. package/esm/domain/rumEventsCollection/actions/trackClickActions.js +244 -0
  57. package/esm/domain/rumEventsCollection/error/errorCollection.js +32 -54
  58. package/esm/domain/rumEventsCollection/error/trackConsoleError.js +18 -0
  59. package/esm/domain/rumEventsCollection/error/trackReportError.js +18 -0
  60. package/esm/domain/rumEventsCollection/longTask/longTaskCollection.js +30 -18
  61. package/esm/domain/rumEventsCollection/resource/resourceCollection.js +31 -9
  62. package/esm/domain/rumEventsCollection/view/trackFirstHidden.js +8 -6
  63. package/esm/domain/rumEventsCollection/view/trackInitialViewTimings.js +43 -26
  64. package/esm/domain/rumEventsCollection/view/trackViewMetrics.js +75 -51
  65. package/esm/domain/rumEventsCollection/view/trackViews.js +120 -85
  66. package/esm/domain/rumEventsCollection/view/viewCollection.js +42 -32
  67. package/esm/domain/rumSessionManager.js +80 -0
  68. package/esm/domain/tracing/skywalkingTracer.js +1 -1
  69. package/esm/domain/tracing/tracer.js +8 -9
  70. package/esm/domain/trackEventCounts.js +9 -6
  71. package/esm/domain/usr/index.js +17 -0
  72. package/esm/domain/waitPageActivityEnd.js +147 -0
  73. package/esm/transport/startRumBatch.js +30 -0
  74. package/package.json +3 -3
  75. package/src/boot/rum.js +79 -59
  76. package/src/boot/rumPublicApi.js +165 -171
  77. package/src/domain/.DS_Store +0 -0
  78. package/src/domain/assembly.js +77 -54
  79. package/src/domain/configuration.js +69 -0
  80. package/src/domain/contexts/internalContext.js +39 -0
  81. package/src/domain/contexts/urlContexts.js +76 -0
  82. package/src/domain/contexts/viewContexts.js +37 -0
  83. package/src/domain/domMutationCollection.js +48 -32
  84. package/src/domain/{rumEventsCollection/view/trackLocationChanges.js → locationChangeObservable.js} +28 -28
  85. package/src/domain/performanceCollection.js +62 -45
  86. package/src/domain/requestCollection.js +103 -0
  87. package/src/domain/rumEventsCollection/actions/actionCollection.js +34 -11
  88. package/src/domain/rumEventsCollection/actions/clickChain.js +90 -0
  89. package/src/domain/rumEventsCollection/actions/computeFrustration.js +84 -0
  90. package/src/domain/rumEventsCollection/actions/getActionNameFromElement.js +73 -62
  91. package/src/domain/rumEventsCollection/actions/getSelectorsFromElement.js +157 -0
  92. package/src/domain/rumEventsCollection/actions/listenActionEvents.js +85 -0
  93. package/src/domain/rumEventsCollection/actions/trackClickActions.js +326 -0
  94. package/src/domain/rumEventsCollection/error/errorCollection.js +53 -69
  95. package/src/domain/rumEventsCollection/error/trackConsoleError.js +21 -0
  96. package/src/domain/rumEventsCollection/error/trackReportError.js +22 -0
  97. package/src/domain/rumEventsCollection/longTask/longTaskCollection.js +29 -18
  98. package/src/domain/rumEventsCollection/resource/resourceCollection.js +39 -23
  99. package/src/domain/rumEventsCollection/view/trackFirstHidden.js +9 -6
  100. package/src/domain/rumEventsCollection/view/trackInitialViewTimings.js +63 -42
  101. package/src/domain/rumEventsCollection/view/trackViewMetrics.js +80 -61
  102. package/src/domain/rumEventsCollection/view/trackViews.js +171 -134
  103. package/src/domain/rumEventsCollection/view/viewCollection.js +69 -49
  104. package/src/domain/rumSessionManager.js +90 -0
  105. package/src/domain/tracing/jaegerTracer.js +5 -5
  106. package/src/domain/tracing/skywalkingTracer.js +3 -3
  107. package/src/domain/tracing/tracer.js +50 -38
  108. package/src/domain/tracing/w3cTraceParentTracer.js +5 -5
  109. package/src/domain/tracing/zipkinMultiTracer.js +5 -5
  110. package/src/domain/tracing/zipkinSingleTracer.js +5 -5
  111. package/src/domain/trackEventCounts.js +10 -6
  112. package/src/domain/usr/index.js +16 -0
  113. package/src/domain/waitPageActivityEnd.js +192 -0
  114. package/src/transport/startRumBatch.js +48 -0
  115. package/cjs/domain/internalContext.js +0 -34
  116. package/cjs/domain/parentContexts.js +0 -143
  117. package/cjs/domain/requestCollections.js +0 -131
  118. package/cjs/domain/rumEventsCollection/actions/trackActions.js +0 -114
  119. package/cjs/domain/rumSession.js +0 -82
  120. package/cjs/domain/trackPageActivities.js +0 -166
  121. package/cjs/transport/batch.js +0 -81
  122. package/esm/domain/internalContext.js +0 -27
  123. package/esm/domain/parentContexts.js +0 -130
  124. package/esm/domain/requestCollections.js +0 -118
  125. package/esm/domain/rumEventsCollection/actions/trackActions.js +0 -103
  126. package/esm/domain/rumSession.js +0 -70
  127. package/esm/domain/trackPageActivities.js +0 -149
  128. package/esm/transport/batch.js +0 -74
  129. package/src/domain/internalContext.js +0 -28
  130. package/src/domain/parentContexts.js +0 -171
  131. package/src/domain/requestCollections.js +0 -118
  132. package/src/domain/rumEventsCollection/actions/trackActions.js +0 -113
  133. package/src/domain/rumSession.js +0 -92
  134. package/src/domain/trackPageActivities.js +0 -170
  135. package/src/transport/batch.js +0 -85
@@ -0,0 +1,102 @@
1
+ import { RequestType, initFetchObservable, initXhrObservable, LifeCycleEventType } from '@cloudcare/browser-core';
2
+ import { isAllowedRequestUrl } from './rumEventsCollection/resource/resourceUtils';
3
+ import { startTracer } from './tracing/tracer';
4
+ var nextRequestIndex = 1;
5
+ export function startRequestCollection(lifeCycle, configuration, sessionManager) {
6
+ var tracer = startTracer(configuration, sessionManager);
7
+ trackXhr(lifeCycle, configuration, tracer);
8
+ trackFetch(lifeCycle, configuration, tracer);
9
+ }
10
+ export function trackXhr(lifeCycle, configuration, tracer) {
11
+ var subscription = initXhrObservable().subscribe(function (rawContext) {
12
+ var context = rawContext;
13
+
14
+ if (!isAllowedRequestUrl(configuration, context.url)) {
15
+ return;
16
+ }
17
+
18
+ switch (context.state) {
19
+ case 'start':
20
+ tracer.traceXhr(context, context.xhr);
21
+ context.requestIndex = getNextRequestIndex();
22
+ lifeCycle.notify(LifeCycleEventType.REQUEST_STARTED, {
23
+ requestIndex: context.requestIndex,
24
+ url: context.url
25
+ });
26
+ break;
27
+
28
+ case 'complete':
29
+ tracer.clearTracingIfNeeded(context);
30
+ lifeCycle.notify(LifeCycleEventType.REQUEST_COMPLETED, {
31
+ duration: context.duration,
32
+ method: context.method,
33
+ requestIndex: context.requestIndex,
34
+ spanId: context.spanId,
35
+ startClocks: context.startClocks,
36
+ status: context.status,
37
+ traceId: context.traceId,
38
+ traceSampled: context.traceSampled,
39
+ type: RequestType.XHR,
40
+ url: context.url,
41
+ xhr: context.xhr
42
+ });
43
+ break;
44
+ }
45
+ });
46
+ return {
47
+ stop: function stop() {
48
+ return subscription.unsubscribe();
49
+ }
50
+ };
51
+ }
52
+ export function trackFetch(lifeCycle, configuration, tracer) {
53
+ var subscription = initFetchObservable().subscribe(function (rawContext) {
54
+ var context = rawContext;
55
+
56
+ if (!isAllowedRequestUrl(configuration, context.url)) {
57
+ return;
58
+ }
59
+
60
+ switch (context.state) {
61
+ case 'start':
62
+ tracer.traceFetch(context);
63
+ context.requestIndex = getNextRequestIndex();
64
+ lifeCycle.notify(LifeCycleEventType.REQUEST_STARTED, {
65
+ requestIndex: context.requestIndex,
66
+ url: context.url
67
+ });
68
+ break;
69
+
70
+ case 'complete':
71
+ tracer.clearTracingIfNeeded(context);
72
+ lifeCycle.notify(LifeCycleEventType.REQUEST_COMPLETED, {
73
+ duration: context.duration,
74
+ method: context.method,
75
+ requestIndex: context.requestIndex,
76
+ responseType: context.responseType,
77
+ spanId: context.spanId,
78
+ startClocks: context.startClocks,
79
+ status: context.status,
80
+ traceId: context.traceId,
81
+ traceSampled: context.traceSampled,
82
+ type: RequestType.FETCH,
83
+ url: context.url,
84
+ response: context.response,
85
+ init: context.init,
86
+ input: context.input
87
+ });
88
+ break;
89
+ }
90
+ });
91
+ return {
92
+ stop: function stop() {
93
+ return subscription.unsubscribe();
94
+ }
95
+ };
96
+ }
97
+
98
+ function getNextRequestIndex() {
99
+ var result = nextRequestIndex;
100
+ nextRequestIndex += 1;
101
+ return result;
102
+ }
@@ -1,15 +1,19 @@
1
- import { toServerDuration, extend, extend2Lev, preferredTimeStamp, ActionType, RumEventType, LifeCycleEventType } from '@cloudcare/browser-core';
2
- import { trackActions } from './trackActions';
3
- export function startActionCollection(lifeCycle, configuration) {
1
+ import { toServerDuration, extend, extend2Lev, ActionType, RumEventType, LifeCycleEventType, UUID, noop } from '@cloudcare/browser-core';
2
+ import { trackClickActions } from './trackClickActions';
3
+ export function startActionCollection(lifeCycle, domMutationObservable, configuration) {
4
4
  lifeCycle.subscribe(LifeCycleEventType.AUTO_ACTION_COMPLETED, function (action) {
5
5
  lifeCycle.notify(LifeCycleEventType.RAW_RUM_EVENT_COLLECTED, processAction(action));
6
6
  });
7
+ var actionContexts = {
8
+ findActionId: noop
9
+ };
7
10
 
8
11
  if (configuration.trackInteractions) {
9
- trackActions(lifeCycle);
12
+ actionContexts = trackClickActions(lifeCycle, domMutationObservable, configuration).actionContexts;
10
13
  }
11
14
 
12
15
  return {
16
+ actionContexts: actionContexts,
13
17
  addAction: function addAction(action, savedCommonContext) {
14
18
  lifeCycle.notify(LifeCycleEventType.RAW_RUM_EVENT_COLLECTED, extend({
15
19
  savedCommonContext: savedCommonContext
@@ -26,12 +30,21 @@ function processAction(action) {
26
30
  },
27
31
  id: action.id,
28
32
  loadingTime: toServerDuration(action.duration),
33
+ frustration: {
34
+ type: action.frustrationTypes
35
+ },
29
36
  long_task: {
30
37
  count: action.counts.longTaskCount
31
38
  },
32
39
  resource: {
33
40
  count: action.counts.resourceCount
34
41
  }
42
+ },
43
+ _dd: {
44
+ action: {
45
+ target: action.target,
46
+ position: action.position
47
+ }
35
48
  }
36
49
  } : {
37
50
  action: {
@@ -41,6 +54,7 @@ function processAction(action) {
41
54
  var customerContext = !isAutoAction(action) ? action.context : undefined;
42
55
  var actionEvent = extend2Lev({
43
56
  action: {
57
+ id: UUID(),
44
58
  target: {
45
59
  name: action.name
46
60
  },
@@ -52,7 +66,11 @@ function processAction(action) {
52
66
  return {
53
67
  customerContext: customerContext,
54
68
  rawRumEvent: actionEvent,
55
- startTime: action.startClocks.relative
69
+ startTime: action.startClocks.relative,
70
+ domainContext: isAutoAction(action) ? {
71
+ event: action.event,
72
+ events: action.events
73
+ } : {}
56
74
  };
57
75
  }
58
76
 
@@ -0,0 +1,69 @@
1
+ import { ONE_SECOND, every } from '@cloudcare/browser-core';
2
+ export var MAX_DURATION_BETWEEN_CLICKS = ONE_SECOND;
3
+ export var MAX_DISTANCE_BETWEEN_CLICKS = 100;
4
+ var ClickChainStatus = {
5
+ WaitingForMoreClicks: 'WaitingForMoreClicks',
6
+ WaitingForClicksToStop: 'WaitingForClicksToStop',
7
+ Finalized: 'Finalized'
8
+ };
9
+ export function createClickChain(firstClick, onFinalize) {
10
+ var bufferedClicks = [];
11
+ var status = ClickChainStatus.WaitingForMoreClicks;
12
+ var maxDurationBetweenClicksTimeout;
13
+ appendClick(firstClick);
14
+
15
+ function appendClick(click) {
16
+ click.stopObservable.subscribe(tryFinalize);
17
+ bufferedClicks.push(click);
18
+ clearTimeout(maxDurationBetweenClicksTimeout);
19
+ maxDurationBetweenClicksTimeout = setTimeout(dontAcceptMoreClick, MAX_DURATION_BETWEEN_CLICKS);
20
+ }
21
+
22
+ function tryFinalize() {
23
+ if (status === ClickChainStatus.WaitingForClicksToStop && every(bufferedClicks, function (click) {
24
+ return click.isStopped();
25
+ })) {
26
+ status = ClickChainStatus.Finalized;
27
+ onFinalize(bufferedClicks);
28
+ }
29
+ }
30
+
31
+ function dontAcceptMoreClick() {
32
+ clearTimeout(maxDurationBetweenClicksTimeout);
33
+
34
+ if (status === ClickChainStatus.WaitingForMoreClicks) {
35
+ status = ClickChainStatus.WaitingForClicksToStop;
36
+ tryFinalize();
37
+ }
38
+ }
39
+
40
+ return {
41
+ tryAppend: function tryAppend(click) {
42
+ if (status !== ClickChainStatus.WaitingForMoreClicks) {
43
+ return false;
44
+ }
45
+
46
+ if (bufferedClicks.length > 0 && !areEventsSimilar(bufferedClicks[bufferedClicks.length - 1].event, click.event)) {
47
+ dontAcceptMoreClick();
48
+ return false;
49
+ }
50
+
51
+ appendClick(click);
52
+ return true;
53
+ },
54
+ stop: function stop() {
55
+ dontAcceptMoreClick();
56
+ }
57
+ };
58
+ }
59
+ /**
60
+ * Checks whether two events are similar by comparing their target, position and timestamp
61
+ */
62
+
63
+ function areEventsSimilar(first, second) {
64
+ return first.target === second.target && mouseEventDistance(first, second) <= MAX_DISTANCE_BETWEEN_CLICKS && first.timeStamp - second.timeStamp <= MAX_DURATION_BETWEEN_CLICKS;
65
+ }
66
+
67
+ function mouseEventDistance(origin, other) {
68
+ return Math.sqrt(Math.pow(origin.clientX - other.clientX, 2) + Math.pow(origin.clientY - other.clientY, 2));
69
+ }
@@ -0,0 +1,64 @@
1
+ import { elementMatches, ONE_SECOND, FrustrationType, some, each } from '@cloudcare/browser-core';
2
+ var MIN_CLICKS_PER_SECOND_TO_CONSIDER_RAGE = 3;
3
+ export function computeFrustration(clicks, rageClick) {
4
+ if (isRage(clicks)) {
5
+ rageClick.addFrustration(FrustrationType.RAGE_CLICK);
6
+
7
+ if (clicks.some(isDead)) {
8
+ rageClick.addFrustration(FrustrationType.DEAD_CLICK);
9
+ }
10
+
11
+ if (rageClick.hasError) {
12
+ rageClick.addFrustration(FrustrationType.ERROR_CLICK);
13
+ }
14
+
15
+ return {
16
+ isRage: true
17
+ };
18
+ }
19
+
20
+ var hasSelectionChanged = some(clicks, function (click) {
21
+ return click.getUserActivity().selection;
22
+ });
23
+ each(clicks, function (click) {
24
+ if (click.hasError) {
25
+ click.addFrustration(FrustrationType.ERROR_CLICK);
26
+ }
27
+
28
+ if (isDead(click) && // Avoid considering clicks part of a double-click or triple-click selections as dead clicks
29
+ !hasSelectionChanged) {
30
+ click.addFrustration(FrustrationType.DEAD_CLICK);
31
+ }
32
+ });
33
+ return {
34
+ isRage: false
35
+ };
36
+ }
37
+ export function isRage(clicks) {
38
+ if (some(clicks, function (click) {
39
+ return click.getUserActivity().selection;
40
+ })) {
41
+ return false;
42
+ }
43
+
44
+ for (var i = 0; i < clicks.length - (MIN_CLICKS_PER_SECOND_TO_CONSIDER_RAGE - 1); i += 1) {
45
+ if (clicks[i + MIN_CLICKS_PER_SECOND_TO_CONSIDER_RAGE - 1].event.timeStamp - clicks[i].event.timeStamp <= ONE_SECOND) {
46
+ return true;
47
+ }
48
+ }
49
+
50
+ return false;
51
+ }
52
+ var DEAD_CLICK_EXCLUDE_SELECTOR = // inputs that don't trigger a meaningful event like "input" when clicked, including textual
53
+ // inputs (using a negative selector is shorter here)
54
+ 'input:not([type="checkbox"]):not([type="radio"]):not([type="button"]):not([type="submit"]):not([type="reset"]):not([type="range"]),' + 'textarea,' + 'select,' + // canvas, as there is no good way to detect activity occurring on them
55
+ 'canvas,' + // links that are interactive (have an href attribute) or any of their descendants, as they can
56
+ // open a new tab or navigate to a hash without triggering a meaningful event
57
+ 'a[href],' + 'a[href] *';
58
+ export function isDead(click) {
59
+ if (click.hasPageActivity || click.getUserActivity().input) {
60
+ return false;
61
+ }
62
+
63
+ return !elementMatches(click.event.target, DEAD_CLICK_EXCLUDE_SELECTOR);
64
+ }
@@ -1,32 +1,28 @@
1
- import { map, filter, safeTruncate } from '@cloudcare/browser-core';
2
- export function getActionNameFromElement(element) {
1
+ import { safeTruncate, isIE, find, map, filter } from '@cloudcare/browser-core';
2
+ var DEFAULT_PROGRAMMATIC_ATTRIBUTE = 'data-guance-action-name';
3
+ export function getActionNameFromElement(element, userProgrammaticAttribute) {
3
4
  // Proceed to get the action name in two steps:
4
5
  // * first, get the name programmatically, explicitly defined by the user.
5
6
  // * then, use strategies that are known to return good results. Those strategies will be used on
6
7
  // the element and a few parents, but it's likely that they won't succeed at all.
7
8
  // * if no name is found this way, use strategies returning less accurate names as a fallback.
8
9
  // Those are much likely to succeed.
9
- return getActionNameFromElementProgrammatically(element) || getActionNameFromElementForStrategies(element, priorityStrategies) || getActionNameFromElementForStrategies(element, fallbackStrategies) || '';
10
+ return getActionNameFromElementProgrammatically(element, DEFAULT_PROGRAMMATIC_ATTRIBUTE) || userProgrammaticAttribute && getActionNameFromElementProgrammatically(element, userProgrammaticAttribute) || getActionNameFromElementForStrategies(element, userProgrammaticAttribute, priorityStrategies) || getActionNameFromElementForStrategies(element, userProgrammaticAttribute, fallbackStrategies) || '';
10
11
  }
11
- /**
12
- * Get the action name from the attribute 'data-dd-action-name' on the element or any of its parent.
13
- */
14
-
15
- var PROGRAMMATIC_ATTRIBUTE = 'data-df-action-name';
16
12
 
17
- function getActionNameFromElementProgrammatically(targetElement) {
13
+ function getActionNameFromElementProgrammatically(targetElement, programmaticAttribute) {
18
14
  var elementWithAttribute; // We don't use getActionNameFromElementForStrategies here, because we want to consider all parents,
19
15
  // without limit. It is up to the user to declare a relevant naming strategy.
20
16
  // If available, use element.closest() to match get the attribute from the element or any of its
21
17
  // parent. Else fallback to a more traditional implementation.
22
18
 
23
19
  if (supportsElementClosest()) {
24
- elementWithAttribute = targetElement.closest('[' + PROGRAMMATIC_ATTRIBUTE + ']');
20
+ elementWithAttribute = targetElement.closest('[' + programmaticAttribute + ']');
25
21
  } else {
26
22
  var element = targetElement;
27
23
 
28
24
  while (element) {
29
- if (element.hasAttribute(PROGRAMMATIC_ATTRIBUTE)) {
25
+ if (element.hasAttribute(programmaticAttribute)) {
30
26
  elementWithAttribute = element;
31
27
  break;
32
28
  }
@@ -39,21 +35,23 @@ function getActionNameFromElementProgrammatically(targetElement) {
39
35
  return;
40
36
  }
41
37
 
42
- var name = elementWithAttribute.getAttribute(PROGRAMMATIC_ATTRIBUTE);
38
+ var name = elementWithAttribute.getAttribute(programmaticAttribute);
43
39
  return truncate(normalizeWhitespace(name.trim()));
44
40
  }
45
41
 
46
42
  var priorityStrategies = [// associated LABEL text
47
- function (element) {
43
+ function (element, userProgrammaticAttribute) {
48
44
  // IE does not support element.labels, so we fallback to a CSS selector based on the element id
49
45
  // instead
50
46
  if (supportsLabelProperty()) {
51
47
  if ('labels' in element && element.labels && element.labels.length > 0) {
52
- return getTextualContent(element.labels[0]);
48
+ return getTextualContent(element.labels[0], userProgrammaticAttribute);
53
49
  }
54
50
  } else if (element.id) {
55
- var label = element.ownerDocument && element.ownerDocument.querySelector('label[for="' + element.id.replace('"', '\\"') + '"]');
56
- return label && getTextualContent(label);
51
+ var label = element.ownerDocument && find(element.ownerDocument.querySelectorAll('label'), function (label) {
52
+ return label.htmlFor === element.id;
53
+ });
54
+ return label && getTextualContent(label, userProgrammaticAttribute);
57
55
  }
58
56
  }, // INPUT button (and associated) value
59
57
  function (element) {
@@ -66,14 +64,14 @@ function (element) {
66
64
  }
67
65
  }
68
66
  }, // BUTTON, LABEL or button-like element text
69
- function (element) {
67
+ function (element, userProgrammaticAttribute) {
70
68
  if (element.nodeName === 'BUTTON' || element.nodeName === 'LABEL' || element.getAttribute('role') === 'button') {
71
- return getTextualContent(element);
69
+ return getTextualContent(element, userProgrammaticAttribute);
72
70
  }
73
71
  }, function (element) {
74
72
  return element.getAttribute('aria-label');
75
73
  }, // associated element text designated by the aria-labelledby attribute
76
- function (element) {
74
+ function (element, userProgrammaticAttribute) {
77
75
  var labelledByAttribute = element.getAttribute('aria-labelledby');
78
76
 
79
77
  if (labelledByAttribute) {
@@ -103,8 +101,8 @@ function (element) {
103
101
  return getTextualContent(element.options[0]);
104
102
  }
105
103
  }];
106
- var fallbackStrategies = [function (element) {
107
- return getTextualContent(element);
104
+ var fallbackStrategies = [function (element, userProgrammaticAttribute) {
105
+ return getTextualContent(element, userProgrammaticAttribute);
108
106
  }];
109
107
  /**
110
108
  * Iterates over the target element and its parent, using the strategies list to get an action name.
@@ -113,13 +111,13 @@ var fallbackStrategies = [function (element) {
113
111
 
114
112
  var MAX_PARENTS_TO_CONSIDER = 10;
115
113
 
116
- function getActionNameFromElementForStrategies(targetElement, strategies) {
114
+ function getActionNameFromElementForStrategies(targetElement, userProgrammaticAttribute, strategies) {
117
115
  var element = targetElement;
118
116
  var recursionCounter = 0;
119
117
 
120
118
  while (recursionCounter <= MAX_PARENTS_TO_CONSIDER && element && element.nodeName !== 'BODY' && element.nodeName !== 'HTML' && element.nodeName !== 'HEAD') {
121
119
  for (var strategy of strategies) {
122
- var name = strategy(element);
120
+ var name = strategy(element, userProgrammaticAttribute);
123
121
 
124
122
  if (typeof name === 'string') {
125
123
  var trimmedName = name.trim();
@@ -155,7 +153,7 @@ function getElementById(refElement, id) {
155
153
  return refElement.ownerDocument ? refElement.ownerDocument.getElementById(id) : null;
156
154
  }
157
155
 
158
- function getTextualContent(element) {
156
+ function getTextualContent(element, userProgrammaticAttribute) {
159
157
  if (element.isContentEditable) {
160
158
  return;
161
159
  }
@@ -163,18 +161,33 @@ function getTextualContent(element) {
163
161
  if ('innerText' in element) {
164
162
  var text = element.innerText;
165
163
 
164
+ var removeTextFromElements = function removeTextFromElements(query) {
165
+ var list = element.querySelectorAll(query);
166
+
167
+ for (var index = 0; index < list.length; index += 1) {
168
+ var _element = list[index];
169
+
170
+ if ('innerText' in _element) {
171
+ var textToReplace = _element.innerText;
172
+
173
+ if (textToReplace && textToReplace.trim().length > 0) {
174
+ text = text.replace(textToReplace, '');
175
+ }
176
+ }
177
+ }
178
+ };
179
+
166
180
  if (!supportsInnerTextScriptAndStyleRemoval()) {
167
181
  // remove the inner text of SCRIPT and STYLES from the result. This is a bit dirty, but should
168
182
  // be relatively fast and work in most cases.
169
- var elementsTextToRemove = element.querySelectorAll('script, style'); // eslint-disable-next-line @typescript-eslint/prefer-for-of
183
+ removeTextFromElements('script, style');
184
+ } // remove the text of elements with programmatic attribute value
170
185
 
171
- for (var i = 0; i < elementsTextToRemove.length; i += 1) {
172
- var innerText = elementsTextToRemove[i].innerText;
173
186
 
174
- if (innerText.trim().length > 0) {
175
- text = text.replace(innerText, '');
176
- }
177
- }
187
+ removeTextFromElements('[' + DEFAULT_PROGRAMMATIC_ATTRIBUTE + ']');
188
+
189
+ if (userProgrammaticAttribute) {
190
+ removeTextFromElements('[' + userProgrammaticAttribute + ']');
178
191
  }
179
192
 
180
193
  return text;
@@ -183,26 +196,26 @@ function getTextualContent(element) {
183
196
  return element.textContent;
184
197
  }
185
198
  /**
186
- * Returns true if element.innerText excludes the text from inline SCRIPT and STYLE element. This
187
- * should be the case everywhere except on some version of Internet Explorer.
188
- * See http://perfectionkills.com/the-poor-misunderstood-innerText/#diff-with-textContent
199
+ * Returns true if element.innerText excludes the text from inline SCRIPT and STYLE element. This
200
+ * should be the case everywhere except on Internet Explorer 10 and 11 (see [1])
201
+ *
202
+ * The innerText property relies on what is actually rendered to compute its output, so to check if
203
+ * it actually excludes SCRIPT and STYLE content, a solution would be to create a style element, set
204
+ * its content to '*', inject it in the document body, and check if the style element innerText
205
+ * property returns '*'. Using a new `document` instance won't work as it is not rendered.
206
+ *
207
+ * This solution requires specific CSP rules (see [2]) to be set by the customer. We want to avoid
208
+ * this, so instead we rely on browser detection. In case of false negative, the impact should be
209
+ * low, since we rely on this result to remove the SCRIPT and STYLE innerText (which will be empty)
210
+ * from a parent element innerText.
211
+ *
212
+ * [1]: https://web.archive.org/web/20210602165716/http://perfectionkills.com/the-poor-misunderstood-innerText/#diff-with-textContent
213
+ * [2]: https://github.com/DataDog/browser-sdk/issues/1084
189
214
  */
190
215
 
191
216
 
192
- var supportsInnerTextScriptAndStyleRemovalResult;
193
-
194
217
  function supportsInnerTextScriptAndStyleRemoval() {
195
- if (supportsInnerTextScriptAndStyleRemovalResult === undefined) {
196
- var style = document.createElement('style');
197
- style.textContent = '*';
198
- var div = document.createElement('div');
199
- div.appendChild(style);
200
- document.body.appendChild(div);
201
- supportsInnerTextScriptAndStyleRemovalResult = div.innerText === '';
202
- document.body.removeChild(div);
203
- }
204
-
205
- return supportsInnerTextScriptAndStyleRemovalResult;
218
+ return !isIE();
206
219
  }
207
220
  /**
208
221
  * Returns true if the browser supports the element.labels property. This should be the case
@@ -0,0 +1,139 @@
1
+ import { arrayFrom, cssEscape, elementMatches, map } from '@cloudcare/browser-core';
2
+ /**
3
+ * Stable attributes are attributes that are commonly used to identify parts of a UI (ex:
4
+ * component). Those attribute values should not be generated randomly (hardcoded most of the time)
5
+ * and stay the same across deploys. They are not necessarily unique across the document.
6
+ */
7
+
8
+ var STABLE_ATTRIBUTES = ['data-guance-action-name', // Common test attributes (list provided by google recorder)
9
+ 'data-testid', 'data-test', 'data-qa', 'data-cy', 'data-test-id', 'data-qa-id', 'data-testing', // FullStory decorator attributes:
10
+ 'data-component', 'data-element', 'data-source-file'];
11
+ export function getSelectorsFromElement(element, actionNameAttribute) {
12
+ var attributeSelectors = getStableAttributeSelectors();
13
+
14
+ if (actionNameAttribute) {
15
+ attributeSelectors = [function (element) {
16
+ return getAttributeSelector(actionNameAttribute, element);
17
+ }].concat(attributeSelectors);
18
+ }
19
+
20
+ return {
21
+ selector: getSelectorFromElement(element, [getIDSelector], [getClassSelector]),
22
+ selector_with_stable_attributes: getSelectorFromElement(element, attributeSelectors.concat(getIDSelector), attributeSelectors.concat(getClassSelector)),
23
+ selector_without_classes: getSelectorFromElement(element, attributeSelectors.concat(getIDSelector), attributeSelectors)
24
+ };
25
+ }
26
+
27
+ function getSelectorFromElement(targetElement, globallyUniqueSelectorStrategies, uniqueAmongChildrenSelectorStrategies) {
28
+ var targetElementSelector = [];
29
+ var element = targetElement;
30
+
31
+ while (element && element.nodeName !== 'HTML') {
32
+ var globallyUniqueSelector = findSelector(element, globallyUniqueSelectorStrategies, isSelectorUniqueGlobally);
33
+
34
+ if (globallyUniqueSelector) {
35
+ targetElementSelector.unshift(globallyUniqueSelector);
36
+ break;
37
+ }
38
+
39
+ var uniqueSelectorAmongChildren = findSelector(element, uniqueAmongChildrenSelectorStrategies, isSelectorUniqueAmongChildren);
40
+
41
+ if (uniqueSelectorAmongChildren) {
42
+ targetElementSelector.unshift(uniqueSelectorAmongChildren);
43
+ } else {
44
+ targetElementSelector.unshift(getPositionSelector(element));
45
+ }
46
+
47
+ element = element.parentElement;
48
+ }
49
+
50
+ return targetElementSelector.join('>');
51
+ }
52
+
53
+ function getIDSelector(element) {
54
+ if (element.id) {
55
+ return '#' + cssEscape(element.id);
56
+ }
57
+ }
58
+
59
+ function getClassSelector(element) {
60
+ if (element.classList.length > 0) {
61
+ var orderedClassList = arrayFrom(element.classList).sort();
62
+ return element.tagName + map(orderedClassList, function (className) {
63
+ return '.' + cssEscape(className);
64
+ }).join('');
65
+ }
66
+ }
67
+
68
+ var stableAttributeSelectorsCache;
69
+
70
+ function getStableAttributeSelectors() {
71
+ if (!stableAttributeSelectorsCache) {
72
+ stableAttributeSelectorsCache = map(STABLE_ATTRIBUTES, function (attribute) {
73
+ return function (element) {
74
+ return getAttributeSelector(attribute, element);
75
+ };
76
+ });
77
+ }
78
+
79
+ return stableAttributeSelectorsCache;
80
+ }
81
+
82
+ function getAttributeSelector(attributeName, element) {
83
+ if (element.hasAttribute(attributeName)) {
84
+ return element.tagName + '[' + attributeName + '="' + cssEscape(element.getAttribute(attributeName)) + '"]';
85
+ }
86
+ }
87
+
88
+ function getPositionSelector(element) {
89
+ var parent = element.parentElement;
90
+ var sibling = parent.firstElementChild;
91
+ var currentIndex = 0;
92
+ var elementIndex;
93
+
94
+ while (sibling) {
95
+ if (sibling.tagName === element.tagName) {
96
+ currentIndex += 1;
97
+
98
+ if (sibling === element) {
99
+ elementIndex = currentIndex;
100
+ }
101
+
102
+ if (elementIndex !== undefined && currentIndex > 1) {
103
+ // Performance improvement: avoid iterating over all children, stop as soon as we are sure
104
+ // the element is not alone
105
+ break;
106
+ }
107
+ }
108
+
109
+ sibling = sibling.nextElementSibling;
110
+ }
111
+
112
+ return currentIndex === 1 ? element.tagName : element.tagName + ':nth-of-type(' + elementIndex + ')';
113
+ }
114
+
115
+ function findSelector(element, selectorGetters, predicate) {
116
+ for (var selectorGetter of selectorGetters) {
117
+ var selector = selectorGetter(element);
118
+
119
+ if (selector && predicate(element, selector)) {
120
+ return selector;
121
+ }
122
+ }
123
+ }
124
+
125
+ function isSelectorUniqueGlobally(element, selector) {
126
+ return element.ownerDocument.body.querySelectorAll(selector).length === 1;
127
+ }
128
+
129
+ function isSelectorUniqueAmongChildren(element, selector) {
130
+ for (var i = 0; i < element.parentElement.children.length; i++) {
131
+ var sibling = element.parentElement.children[i];
132
+
133
+ if (sibling !== element && elementMatches(sibling, selector)) {
134
+ return false;
135
+ }
136
+ }
137
+
138
+ return true;
139
+ }