@opentelemetry/browser-instrumentation 0.1.0 → 0.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -1,2 +1,3 @@
1
+ import { NavigationTimingInstrumentationConfig } from "./types.js";
1
2
  import { NavigationTimingInstrumentation } from "./instrumentation.js";
2
- export { NavigationTimingInstrumentation };
3
+ export { NavigationTimingInstrumentation, type NavigationTimingInstrumentationConfig };
@@ -7,9 +7,9 @@ import { InstrumentationBase } from "@opentelemetry/instrumentation";
7
7
  */
8
8
  declare class NavigationTimingInstrumentation extends InstrumentationBase<NavigationTimingInstrumentationConfig> {
9
9
  private _lastEntry?;
10
- private _didEmit;
11
10
  private _completeDelayTimeoutId?;
12
11
  private _retryCount;
12
+ private _didEmit;
13
13
  private _isEnabled;
14
14
  private _onLoad;
15
15
  private _onPageHide;
@@ -1,3 +1,4 @@
1
+ import { version } from "../package.js";
1
2
  import { ATTR_NAVIGATION_CONNECT_END, ATTR_NAVIGATION_CONNECT_START, ATTR_NAVIGATION_DECODED_BODY_SIZE, ATTR_NAVIGATION_DOMAIN_LOOKUP_END, ATTR_NAVIGATION_DOMAIN_LOOKUP_START, ATTR_NAVIGATION_DOM_COMPLETE, ATTR_NAVIGATION_DOM_CONTENT_LOADED_EVENT_END, ATTR_NAVIGATION_DOM_CONTENT_LOADED_EVENT_START, ATTR_NAVIGATION_DOM_INTERACTIVE, ATTR_NAVIGATION_DURATION, ATTR_NAVIGATION_ENCODED_BODY_SIZE, ATTR_NAVIGATION_FETCH_START, ATTR_NAVIGATION_LOAD_EVENT_END, ATTR_NAVIGATION_LOAD_EVENT_START, ATTR_NAVIGATION_REDIRECT_COUNT, ATTR_NAVIGATION_REQUEST_START, ATTR_NAVIGATION_RESPONSE_END, ATTR_NAVIGATION_RESPONSE_START, ATTR_NAVIGATION_SECURE_CONNECTION_START, ATTR_NAVIGATION_TRANSFER_SIZE, ATTR_NAVIGATION_TYPE, ATTR_NAVIGATION_UNLOAD_EVENT_END, ATTR_NAVIGATION_UNLOAD_EVENT_START, ATTR_NAVIGATION_URL, NAVIGATION_TIMING_EVENT_NAME } from "./semconv.js";
2
3
  import { SeverityNumber } from "@opentelemetry/api-logs";
3
4
  import { InstrumentationBase } from "@opentelemetry/instrumentation";
@@ -9,18 +10,11 @@ const MAX_RETRIES = 5;
9
10
  */
10
11
  var NavigationTimingInstrumentation = class extends InstrumentationBase {
11
12
  _lastEntry;
12
- _didEmit = false;
13
13
  _completeDelayTimeoutId;
14
14
  _retryCount = 0;
15
- _isEnabled = false;
16
- _onLoad = () => {
17
- this._tryEmitOrSchedule();
18
- };
19
- _onPageHide = () => {
20
- this._handleUnload();
21
- };
15
+ _didEmit = false;
22
16
  constructor(config = {}) {
23
- super("@opentelemetry/instrumentation-navigation-timing", "0.1.0", config);
17
+ super("@opentelemetry/browser-instrumentation/navigation-timing", version, config);
24
18
  }
25
19
  init() {
26
20
  return [];
@@ -28,6 +22,8 @@ var NavigationTimingInstrumentation = class extends InstrumentationBase {
28
22
  enable() {
29
23
  if (this._isEnabled) return;
30
24
  this._isEnabled = true;
25
+ this._onLoad = () => this._tryEmitOrSchedule();
26
+ this._onPageHide = () => this._handleUnload();
31
27
  this._tryEmitOrSchedule();
32
28
  if (this._didEmit) return;
33
29
  window.addEventListener("pagehide", this._onPageHide);
@@ -70,24 +66,32 @@ var NavigationTimingInstrumentation = class extends InstrumentationBase {
70
66
  window.addEventListener("load", this._onLoad, { once: true });
71
67
  return;
72
68
  }
73
- if (this._completeDelayTimeoutId !== void 0 || this._retryCount > MAX_RETRIES) return;
74
- else {
75
- const delay = this._calculateBackoffDelay();
76
- this._retryCount++;
77
- this._completeDelayTimeoutId = window.setTimeout(() => {
78
- this._completeDelayTimeoutId = void 0;
79
- this._tryEmitOrSchedule();
80
- }, delay);
69
+ if (this._completeDelayTimeoutId !== void 0) return;
70
+ if (this._retryCount > MAX_RETRIES) {
71
+ if (this._lastEntry) {
72
+ this._diag.warn("Navigation timing: retries exhausted, emitting incomplete entry");
73
+ this._emitAndCleanup(this._lastEntry);
74
+ } else {
75
+ this._diag.warn("Navigation timing: retries exhausted with no entry available");
76
+ this._unsubscribeAll();
77
+ }
78
+ return;
81
79
  }
80
+ const delay = this._calculateBackoffDelay();
81
+ this._retryCount++;
82
+ this._completeDelayTimeoutId = window.setTimeout(() => {
83
+ this._completeDelayTimeoutId = void 0;
84
+ this._tryEmitOrSchedule();
85
+ }, delay);
82
86
  }
83
87
  _handleUnload() {
84
88
  if (this._didEmit) return;
85
89
  const entry = this._getLatestNavigationEntry() ?? this._lastEntry;
86
- if (!entry) {
90
+ if (entry) this._emitAndCleanup(entry);
91
+ else {
92
+ this._diag.warn("Navigation timing: no entry available at unload");
87
93
  this._unsubscribeAll();
88
- return;
89
94
  }
90
- this._emitAndCleanup(entry);
91
95
  }
92
96
  _emitAndCleanup(entry) {
93
97
  if (this._didEmit) return;
@@ -134,8 +138,8 @@ var NavigationTimingInstrumentation = class extends InstrumentationBase {
134
138
  clearTimeout(this._completeDelayTimeoutId);
135
139
  this._completeDelayTimeoutId = void 0;
136
140
  }
137
- window.removeEventListener("load", this._onLoad);
138
- window.removeEventListener("pagehide", this._onPageHide);
141
+ if (this._onLoad) window.removeEventListener("load", this._onLoad);
142
+ if (this._onPageHide) window.removeEventListener("pagehide", this._onPageHide);
139
143
  }
140
144
  };
141
145
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.js","names":[],"sources":["../../src/navigation-timing/instrumentation.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { SeverityNumber } from '@opentelemetry/api-logs';\nimport { InstrumentationBase } from '@opentelemetry/instrumentation';\nimport {\n ATTR_NAVIGATION_CONNECT_END,\n ATTR_NAVIGATION_CONNECT_START,\n ATTR_NAVIGATION_DECODED_BODY_SIZE,\n ATTR_NAVIGATION_DOM_COMPLETE,\n ATTR_NAVIGATION_DOM_CONTENT_LOADED_EVENT_END,\n ATTR_NAVIGATION_DOM_CONTENT_LOADED_EVENT_START,\n ATTR_NAVIGATION_DOM_INTERACTIVE,\n ATTR_NAVIGATION_DOMAIN_LOOKUP_END,\n ATTR_NAVIGATION_DOMAIN_LOOKUP_START,\n ATTR_NAVIGATION_DURATION,\n ATTR_NAVIGATION_ENCODED_BODY_SIZE,\n ATTR_NAVIGATION_FETCH_START,\n ATTR_NAVIGATION_LOAD_EVENT_END,\n ATTR_NAVIGATION_LOAD_EVENT_START,\n ATTR_NAVIGATION_REDIRECT_COUNT,\n ATTR_NAVIGATION_REQUEST_START,\n ATTR_NAVIGATION_RESPONSE_END,\n ATTR_NAVIGATION_RESPONSE_START,\n ATTR_NAVIGATION_SECURE_CONNECTION_START,\n ATTR_NAVIGATION_TRANSFER_SIZE,\n ATTR_NAVIGATION_TYPE,\n ATTR_NAVIGATION_UNLOAD_EVENT_END,\n ATTR_NAVIGATION_UNLOAD_EVENT_START,\n ATTR_NAVIGATION_URL,\n NAVIGATION_TIMING_EVENT_NAME,\n} from './semconv.ts';\nimport type { NavigationTimingInstrumentationConfig } from './types.ts';\n\nconst BASE_DELAY_MS = 50;\nconst MAX_RETRIES = 5;\n\n/**\n * This class automatically instruments navigation timing within the browser.\n */\nexport class NavigationTimingInstrumentation extends InstrumentationBase<NavigationTimingInstrumentationConfig> {\n private _lastEntry?: PerformanceNavigationTiming;\n private _didEmit = false;\n private _completeDelayTimeoutId?: number;\n private _retryCount = 0;\n private _isEnabled = false;\n\n private _onLoad = () => {\n this._tryEmitOrSchedule();\n };\n\n private _onPageHide = () => {\n this._handleUnload();\n };\n\n constructor(config: NavigationTimingInstrumentationConfig = {}) {\n super('@opentelemetry/instrumentation-navigation-timing', '0.1.0', config);\n }\n\n protected override init() {\n return [];\n }\n\n override enable(): void {\n if (this._isEnabled) {\n return;\n }\n this._isEnabled = true;\n\n // Try emitting immediately (e.g. when enabled after load),\n // otherwise schedule for `load` or fall back to unload.\n this._tryEmitOrSchedule();\n if (this._didEmit) {\n return;\n }\n\n window.addEventListener('pagehide', this._onPageHide);\n }\n\n override disable(): void {\n this._isEnabled = false;\n this._unsubscribeAll();\n this._lastEntry = undefined;\n this._didEmit = false;\n this._retryCount = 0;\n }\n\n private _getLatestNavigationEntry(): PerformanceNavigationTiming | undefined {\n const entries = performance?.getEntriesByType?.('navigation') as\n | PerformanceNavigationTiming[]\n | undefined;\n if (!entries || entries.length === 0) {\n return;\n }\n\n return entries[entries.length - 1];\n }\n\n private _calculateBackoffDelay(): number {\n return this._retryCount * BASE_DELAY_MS;\n }\n\n /**\n * Attempts to emit the navigation timing event.\n *\n * - Emits immediately if a complete `PerformanceNavigationTiming` entry is available.\n * - If the page is still loading, waits for `window.load` and retries.\n * - If the page is already loaded but the entry is not finalized yet, schedules one\n * deferred re-check (to allow the browser to populate the timing fields).\n *\n * This method can be called multiple times (from `enable()`, the load handler, or the\n * deferred timeout), so it must be safe to re-enter.\n */\n private _tryEmitOrSchedule(): void {\n if (this._didEmit) {\n return;\n }\n\n const entry = this._getLatestNavigationEntry();\n if (entry) {\n this._lastEntry = entry;\n }\n\n // Prefer emitting a \"complete\" navigation entry.\n if (entry && entry.loadEventEnd > 0) {\n this._emitAndCleanup(entry);\n return;\n }\n\n // If the document is still loading, wait for `load` and try again.\n if (document.readyState !== 'complete') {\n window.addEventListener('load', this._onLoad, { once: true });\n return;\n }\n\n // If the document is already complete but navigation timings are not finalized yet,\n // schedule a deferred re-check with linear backoff to allow the browser to finish\n // populating the entry.\n if (\n this._completeDelayTimeoutId !== undefined ||\n this._retryCount > MAX_RETRIES\n ) {\n return;\n } else {\n const delay = this._calculateBackoffDelay();\n this._retryCount++;\n\n this._completeDelayTimeoutId = window.setTimeout(() => {\n this._completeDelayTimeoutId = undefined;\n this._tryEmitOrSchedule();\n }, delay);\n }\n }\n\n private _handleUnload(): void {\n if (this._didEmit) {\n return;\n }\n\n const entry = this._getLatestNavigationEntry() ?? this._lastEntry;\n if (!entry) {\n this._unsubscribeAll();\n return;\n }\n\n // Emit even if partial (e.g. loadEventEnd === 0).\n this._emitAndCleanup(entry);\n }\n\n private _emitAndCleanup(entry: PerformanceNavigationTiming): void {\n if (this._didEmit) {\n return;\n }\n\n this._didEmit = true;\n\n this._emitNavigationTiming(entry);\n this._lastEntry = undefined;\n this._unsubscribeAll();\n }\n\n private _emitNavigationTiming(entry: PerformanceNavigationTiming) {\n if (!entry) {\n return;\n }\n\n this.logger.emit({\n eventName: NAVIGATION_TIMING_EVENT_NAME,\n severityNumber: SeverityNumber.INFO,\n attributes: {\n [ATTR_NAVIGATION_TYPE]: entry.type,\n [ATTR_NAVIGATION_URL]: entry.name,\n [ATTR_NAVIGATION_DURATION]: entry.duration,\n [ATTR_NAVIGATION_DOM_COMPLETE]: entry.domComplete,\n [ATTR_NAVIGATION_DOM_CONTENT_LOADED_EVENT_END]:\n entry.domContentLoadedEventEnd,\n [ATTR_NAVIGATION_DOM_CONTENT_LOADED_EVENT_START]:\n entry.domContentLoadedEventStart,\n [ATTR_NAVIGATION_DOM_INTERACTIVE]: entry.domInteractive,\n [ATTR_NAVIGATION_LOAD_EVENT_END]: entry.loadEventEnd,\n [ATTR_NAVIGATION_LOAD_EVENT_START]: entry.loadEventStart,\n [ATTR_NAVIGATION_REDIRECT_COUNT]: entry.redirectCount,\n [ATTR_NAVIGATION_UNLOAD_EVENT_END]: entry.unloadEventEnd,\n [ATTR_NAVIGATION_UNLOAD_EVENT_START]: entry.unloadEventStart,\n [ATTR_NAVIGATION_FETCH_START]: entry.fetchStart,\n [ATTR_NAVIGATION_DOMAIN_LOOKUP_START]: entry.domainLookupStart,\n [ATTR_NAVIGATION_DOMAIN_LOOKUP_END]: entry.domainLookupEnd,\n [ATTR_NAVIGATION_CONNECT_START]: entry.connectStart,\n [ATTR_NAVIGATION_CONNECT_END]: entry.connectEnd,\n [ATTR_NAVIGATION_SECURE_CONNECTION_START]: entry.secureConnectionStart,\n [ATTR_NAVIGATION_REQUEST_START]: entry.requestStart,\n [ATTR_NAVIGATION_RESPONSE_START]: entry.responseStart,\n [ATTR_NAVIGATION_RESPONSE_END]: entry.responseEnd,\n [ATTR_NAVIGATION_TRANSFER_SIZE]: entry.transferSize,\n [ATTR_NAVIGATION_ENCODED_BODY_SIZE]: entry.encodedBodySize,\n [ATTR_NAVIGATION_DECODED_BODY_SIZE]: entry.decodedBodySize,\n },\n });\n }\n\n private _unsubscribeAll(): void {\n if (this._completeDelayTimeoutId) {\n clearTimeout(this._completeDelayTimeoutId);\n this._completeDelayTimeoutId = undefined;\n }\n\n window.removeEventListener('load', this._onLoad);\n window.removeEventListener('pagehide', this._onPageHide);\n }\n}\n"],"mappings":";;;;AAoCA,MAAM,gBAAgB;AACtB,MAAM,cAAc;;;;AAKpB,IAAa,kCAAb,cAAqD,oBAA2D;CAC9G;CACA,WAAmB;CACnB;CACA,cAAsB;CACtB,aAAqB;CAErB,gBAAwB;AACtB,OAAK,oBAAoB;;CAG3B,oBAA4B;AAC1B,OAAK,eAAe;;CAGtB,YAAY,SAAgD,EAAE,EAAE;AAC9D,QAAM,oDAAoD,SAAS,OAAO;;CAG5E,OAA0B;AACxB,SAAO,EAAE;;CAGX,SAAwB;AACtB,MAAI,KAAK,WACP;AAEF,OAAK,aAAa;AAIlB,OAAK,oBAAoB;AACzB,MAAI,KAAK,SACP;AAGF,SAAO,iBAAiB,YAAY,KAAK,YAAY;;CAGvD,UAAyB;AACvB,OAAK,aAAa;AAClB,OAAK,iBAAiB;AACtB,OAAK,aAAa,KAAA;AAClB,OAAK,WAAW;AAChB,OAAK,cAAc;;CAGrB,4BAA6E;EAC3E,MAAM,UAAU,aAAa,mBAAmB,aAAa;AAG7D,MAAI,CAAC,WAAW,QAAQ,WAAW,EACjC;AAGF,SAAO,QAAQ,QAAQ,SAAS;;CAGlC,yBAAyC;AACvC,SAAO,KAAK,cAAc;;;;;;;;;;;;;CAc5B,qBAAmC;AACjC,MAAI,KAAK,SACP;EAGF,MAAM,QAAQ,KAAK,2BAA2B;AAC9C,MAAI,MACF,MAAK,aAAa;AAIpB,MAAI,SAAS,MAAM,eAAe,GAAG;AACnC,QAAK,gBAAgB,MAAM;AAC3B;;AAIF,MAAI,SAAS,eAAe,YAAY;AACtC,UAAO,iBAAiB,QAAQ,KAAK,SAAS,EAAE,MAAM,MAAM,CAAC;AAC7D;;AAMF,MACE,KAAK,4BAA4B,KAAA,KACjC,KAAK,cAAc,YAEnB;OACK;GACL,MAAM,QAAQ,KAAK,wBAAwB;AAC3C,QAAK;AAEL,QAAK,0BAA0B,OAAO,iBAAiB;AACrD,SAAK,0BAA0B,KAAA;AAC/B,SAAK,oBAAoB;MACxB,MAAM;;;CAIb,gBAA8B;AAC5B,MAAI,KAAK,SACP;EAGF,MAAM,QAAQ,KAAK,2BAA2B,IAAI,KAAK;AACvD,MAAI,CAAC,OAAO;AACV,QAAK,iBAAiB;AACtB;;AAIF,OAAK,gBAAgB,MAAM;;CAG7B,gBAAwB,OAA0C;AAChE,MAAI,KAAK,SACP;AAGF,OAAK,WAAW;AAEhB,OAAK,sBAAsB,MAAM;AACjC,OAAK,aAAa,KAAA;AAClB,OAAK,iBAAiB;;CAGxB,sBAA8B,OAAoC;AAChE,MAAI,CAAC,MACH;AAGF,OAAK,OAAO,KAAK;GACf,WAAW;GACX,gBAAgB,eAAe;GAC/B,YAAY;KACT,uBAAuB,MAAM;KAC7B,sBAAsB,MAAM;KAC5B,2BAA2B,MAAM;KACjC,+BAA+B,MAAM;KACrC,+CACC,MAAM;KACP,iDACC,MAAM;KACP,kCAAkC,MAAM;KACxC,iCAAiC,MAAM;KACvC,mCAAmC,MAAM;KACzC,iCAAiC,MAAM;KACvC,mCAAmC,MAAM;KACzC,qCAAqC,MAAM;KAC3C,8BAA8B,MAAM;KACpC,sCAAsC,MAAM;KAC5C,oCAAoC,MAAM;KAC1C,gCAAgC,MAAM;KACtC,8BAA8B,MAAM;KACpC,0CAA0C,MAAM;KAChD,gCAAgC,MAAM;KACtC,iCAAiC,MAAM;KACvC,+BAA+B,MAAM;KACrC,gCAAgC,MAAM;KACtC,oCAAoC,MAAM;KAC1C,oCAAoC,MAAM;IAC5C;GACF,CAAC;;CAGJ,kBAAgC;AAC9B,MAAI,KAAK,yBAAyB;AAChC,gBAAa,KAAK,wBAAwB;AAC1C,QAAK,0BAA0B,KAAA;;AAGjC,SAAO,oBAAoB,QAAQ,KAAK,QAAQ;AAChD,SAAO,oBAAoB,YAAY,KAAK,YAAY"}
1
+ {"version":3,"file":"instrumentation.js","names":[],"sources":["../../src/navigation-timing/instrumentation.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { SeverityNumber } from '@opentelemetry/api-logs';\nimport { InstrumentationBase } from '@opentelemetry/instrumentation';\nimport { version } from '../../package.json' with { type: 'json' };\nimport {\n ATTR_NAVIGATION_CONNECT_END,\n ATTR_NAVIGATION_CONNECT_START,\n ATTR_NAVIGATION_DECODED_BODY_SIZE,\n ATTR_NAVIGATION_DOM_COMPLETE,\n ATTR_NAVIGATION_DOM_CONTENT_LOADED_EVENT_END,\n ATTR_NAVIGATION_DOM_CONTENT_LOADED_EVENT_START,\n ATTR_NAVIGATION_DOM_INTERACTIVE,\n ATTR_NAVIGATION_DOMAIN_LOOKUP_END,\n ATTR_NAVIGATION_DOMAIN_LOOKUP_START,\n ATTR_NAVIGATION_DURATION,\n ATTR_NAVIGATION_ENCODED_BODY_SIZE,\n ATTR_NAVIGATION_FETCH_START,\n ATTR_NAVIGATION_LOAD_EVENT_END,\n ATTR_NAVIGATION_LOAD_EVENT_START,\n ATTR_NAVIGATION_REDIRECT_COUNT,\n ATTR_NAVIGATION_REQUEST_START,\n ATTR_NAVIGATION_RESPONSE_END,\n ATTR_NAVIGATION_RESPONSE_START,\n ATTR_NAVIGATION_SECURE_CONNECTION_START,\n ATTR_NAVIGATION_TRANSFER_SIZE,\n ATTR_NAVIGATION_TYPE,\n ATTR_NAVIGATION_UNLOAD_EVENT_END,\n ATTR_NAVIGATION_UNLOAD_EVENT_START,\n ATTR_NAVIGATION_URL,\n NAVIGATION_TIMING_EVENT_NAME,\n} from './semconv.ts';\nimport type { NavigationTimingInstrumentationConfig } from './types.ts';\n\nconst BASE_DELAY_MS = 50;\nconst MAX_RETRIES = 5;\n\n/**\n * This class automatically instruments navigation timing within the browser.\n */\nexport class NavigationTimingInstrumentation extends InstrumentationBase<NavigationTimingInstrumentationConfig> {\n private _lastEntry?: PerformanceNavigationTiming;\n private _completeDelayTimeoutId?: number;\n private _retryCount = 0;\n private _didEmit = false;\n\n // Use `declare` to prevent JS class field initializers from running after\n // super(), which would reset values set by the enable() call that\n // InstrumentationBase makes during its constructor.\n private declare _isEnabled: boolean;\n private declare _onLoad: () => void;\n private declare _onPageHide: () => void;\n\n constructor(config: NavigationTimingInstrumentationConfig = {}) {\n super(\n '@opentelemetry/browser-instrumentation/navigation-timing',\n version,\n config,\n );\n }\n\n protected override init() {\n return [];\n }\n\n override enable(): void {\n if (this._isEnabled) {\n return;\n }\n this._isEnabled = true;\n this._onLoad = () => this._tryEmitOrSchedule();\n this._onPageHide = () => this._handleUnload();\n\n // Try emitting immediately (e.g. when enabled after load),\n // otherwise schedule for `load` or fall back to unload.\n this._tryEmitOrSchedule();\n if (this._didEmit) {\n return;\n }\n\n window.addEventListener('pagehide', this._onPageHide);\n }\n\n override disable(): void {\n this._isEnabled = false;\n this._unsubscribeAll();\n this._lastEntry = undefined;\n this._didEmit = false;\n this._retryCount = 0;\n }\n\n private _getLatestNavigationEntry(): PerformanceNavigationTiming | undefined {\n const entries = performance?.getEntriesByType?.('navigation') as\n | PerformanceNavigationTiming[]\n | undefined;\n if (!entries || entries.length === 0) {\n return;\n }\n\n return entries[entries.length - 1];\n }\n\n private _calculateBackoffDelay(): number {\n return this._retryCount * BASE_DELAY_MS;\n }\n\n /**\n * Attempts to emit the navigation timing event.\n *\n * - Emits immediately if a complete `PerformanceNavigationTiming` entry is available.\n * - If the page is still loading, waits for `window.load` and retries.\n * - If the page is already loaded but the entry is not finalized yet, schedules one\n * deferred re-check (to allow the browser to populate the timing fields).\n *\n * This method can be called multiple times (from `enable()`, the load handler, or the\n * deferred timeout), so it must be safe to re-enter.\n */\n private _tryEmitOrSchedule(): void {\n if (this._didEmit) {\n return;\n }\n\n const entry = this._getLatestNavigationEntry();\n if (entry) {\n this._lastEntry = entry;\n }\n\n // Prefer emitting a \"complete\" navigation entry.\n if (entry && entry.loadEventEnd > 0) {\n this._emitAndCleanup(entry);\n return;\n }\n\n // If the document is still loading, wait for `load` and try again.\n if (document.readyState !== 'complete') {\n window.addEventListener('load', this._onLoad, { once: true });\n return;\n }\n\n // If the document is already complete but navigation timings are not finalized yet,\n // schedule a deferred re-check with linear backoff to allow the browser to finish\n // populating the entry.\n if (this._completeDelayTimeoutId !== undefined) {\n return;\n }\n if (this._retryCount > MAX_RETRIES) {\n if (this._lastEntry) {\n this._diag.warn(\n 'Navigation timing: retries exhausted, emitting incomplete entry',\n );\n this._emitAndCleanup(this._lastEntry);\n } else {\n this._diag.warn(\n 'Navigation timing: retries exhausted with no entry available',\n );\n this._unsubscribeAll();\n }\n return;\n }\n\n const delay = this._calculateBackoffDelay();\n this._retryCount++;\n\n this._completeDelayTimeoutId = window.setTimeout(() => {\n this._completeDelayTimeoutId = undefined;\n this._tryEmitOrSchedule();\n }, delay);\n }\n\n private _handleUnload(): void {\n if (this._didEmit) {\n return;\n }\n\n const entry = this._getLatestNavigationEntry() ?? this._lastEntry;\n if (entry) {\n this._emitAndCleanup(entry);\n } else {\n this._diag.warn('Navigation timing: no entry available at unload');\n this._unsubscribeAll();\n }\n }\n\n private _emitAndCleanup(entry: PerformanceNavigationTiming): void {\n if (this._didEmit) {\n return;\n }\n\n this._didEmit = true;\n\n this._emitNavigationTiming(entry);\n this._lastEntry = undefined;\n this._unsubscribeAll();\n }\n\n private _emitNavigationTiming(entry: PerformanceNavigationTiming) {\n if (!entry) {\n return;\n }\n\n this.logger.emit({\n eventName: NAVIGATION_TIMING_EVENT_NAME,\n severityNumber: SeverityNumber.INFO,\n attributes: {\n [ATTR_NAVIGATION_TYPE]: entry.type,\n [ATTR_NAVIGATION_URL]: entry.name,\n [ATTR_NAVIGATION_DURATION]: entry.duration,\n [ATTR_NAVIGATION_DOM_COMPLETE]: entry.domComplete,\n [ATTR_NAVIGATION_DOM_CONTENT_LOADED_EVENT_END]:\n entry.domContentLoadedEventEnd,\n [ATTR_NAVIGATION_DOM_CONTENT_LOADED_EVENT_START]:\n entry.domContentLoadedEventStart,\n [ATTR_NAVIGATION_DOM_INTERACTIVE]: entry.domInteractive,\n [ATTR_NAVIGATION_LOAD_EVENT_END]: entry.loadEventEnd,\n [ATTR_NAVIGATION_LOAD_EVENT_START]: entry.loadEventStart,\n [ATTR_NAVIGATION_REDIRECT_COUNT]: entry.redirectCount,\n [ATTR_NAVIGATION_UNLOAD_EVENT_END]: entry.unloadEventEnd,\n [ATTR_NAVIGATION_UNLOAD_EVENT_START]: entry.unloadEventStart,\n [ATTR_NAVIGATION_FETCH_START]: entry.fetchStart,\n [ATTR_NAVIGATION_DOMAIN_LOOKUP_START]: entry.domainLookupStart,\n [ATTR_NAVIGATION_DOMAIN_LOOKUP_END]: entry.domainLookupEnd,\n [ATTR_NAVIGATION_CONNECT_START]: entry.connectStart,\n [ATTR_NAVIGATION_CONNECT_END]: entry.connectEnd,\n [ATTR_NAVIGATION_SECURE_CONNECTION_START]: entry.secureConnectionStart,\n [ATTR_NAVIGATION_REQUEST_START]: entry.requestStart,\n [ATTR_NAVIGATION_RESPONSE_START]: entry.responseStart,\n [ATTR_NAVIGATION_RESPONSE_END]: entry.responseEnd,\n [ATTR_NAVIGATION_TRANSFER_SIZE]: entry.transferSize,\n [ATTR_NAVIGATION_ENCODED_BODY_SIZE]: entry.encodedBodySize,\n [ATTR_NAVIGATION_DECODED_BODY_SIZE]: entry.decodedBodySize,\n },\n });\n }\n\n private _unsubscribeAll(): void {\n if (this._completeDelayTimeoutId) {\n clearTimeout(this._completeDelayTimeoutId);\n this._completeDelayTimeoutId = undefined;\n }\n\n if (this._onLoad) {\n window.removeEventListener('load', this._onLoad);\n }\n if (this._onPageHide) {\n window.removeEventListener('pagehide', this._onPageHide);\n }\n }\n}\n"],"mappings":";;;;;AAqCA,MAAM,gBAAgB;AACtB,MAAM,cAAc;;;;AAKpB,IAAa,kCAAb,cAAqD,oBAA2D;CAC9G;CACA;CACA,cAAsB;CACtB,WAAmB;CASnB,YAAY,SAAgD,EAAE,EAAE;AAC9D,QACE,4DACA,SACA,OACD;;CAGH,OAA0B;AACxB,SAAO,EAAE;;CAGX,SAAwB;AACtB,MAAI,KAAK,WACP;AAEF,OAAK,aAAa;AAClB,OAAK,gBAAgB,KAAK,oBAAoB;AAC9C,OAAK,oBAAoB,KAAK,eAAe;AAI7C,OAAK,oBAAoB;AACzB,MAAI,KAAK,SACP;AAGF,SAAO,iBAAiB,YAAY,KAAK,YAAY;;CAGvD,UAAyB;AACvB,OAAK,aAAa;AAClB,OAAK,iBAAiB;AACtB,OAAK,aAAa,KAAA;AAClB,OAAK,WAAW;AAChB,OAAK,cAAc;;CAGrB,4BAA6E;EAC3E,MAAM,UAAU,aAAa,mBAAmB,aAAa;AAG7D,MAAI,CAAC,WAAW,QAAQ,WAAW,EACjC;AAGF,SAAO,QAAQ,QAAQ,SAAS;;CAGlC,yBAAyC;AACvC,SAAO,KAAK,cAAc;;;;;;;;;;;;;CAc5B,qBAAmC;AACjC,MAAI,KAAK,SACP;EAGF,MAAM,QAAQ,KAAK,2BAA2B;AAC9C,MAAI,MACF,MAAK,aAAa;AAIpB,MAAI,SAAS,MAAM,eAAe,GAAG;AACnC,QAAK,gBAAgB,MAAM;AAC3B;;AAIF,MAAI,SAAS,eAAe,YAAY;AACtC,UAAO,iBAAiB,QAAQ,KAAK,SAAS,EAAE,MAAM,MAAM,CAAC;AAC7D;;AAMF,MAAI,KAAK,4BAA4B,KAAA,EACnC;AAEF,MAAI,KAAK,cAAc,aAAa;AAClC,OAAI,KAAK,YAAY;AACnB,SAAK,MAAM,KACT,kEACD;AACD,SAAK,gBAAgB,KAAK,WAAW;UAChC;AACL,SAAK,MAAM,KACT,+DACD;AACD,SAAK,iBAAiB;;AAExB;;EAGF,MAAM,QAAQ,KAAK,wBAAwB;AAC3C,OAAK;AAEL,OAAK,0BAA0B,OAAO,iBAAiB;AACrD,QAAK,0BAA0B,KAAA;AAC/B,QAAK,oBAAoB;KACxB,MAAM;;CAGX,gBAA8B;AAC5B,MAAI,KAAK,SACP;EAGF,MAAM,QAAQ,KAAK,2BAA2B,IAAI,KAAK;AACvD,MAAI,MACF,MAAK,gBAAgB,MAAM;OACtB;AACL,QAAK,MAAM,KAAK,kDAAkD;AAClE,QAAK,iBAAiB;;;CAI1B,gBAAwB,OAA0C;AAChE,MAAI,KAAK,SACP;AAGF,OAAK,WAAW;AAEhB,OAAK,sBAAsB,MAAM;AACjC,OAAK,aAAa,KAAA;AAClB,OAAK,iBAAiB;;CAGxB,sBAA8B,OAAoC;AAChE,MAAI,CAAC,MACH;AAGF,OAAK,OAAO,KAAK;GACf,WAAW;GACX,gBAAgB,eAAe;GAC/B,YAAY;KACT,uBAAuB,MAAM;KAC7B,sBAAsB,MAAM;KAC5B,2BAA2B,MAAM;KACjC,+BAA+B,MAAM;KACrC,+CACC,MAAM;KACP,iDACC,MAAM;KACP,kCAAkC,MAAM;KACxC,iCAAiC,MAAM;KACvC,mCAAmC,MAAM;KACzC,iCAAiC,MAAM;KACvC,mCAAmC,MAAM;KACzC,qCAAqC,MAAM;KAC3C,8BAA8B,MAAM;KACpC,sCAAsC,MAAM;KAC5C,oCAAoC,MAAM;KAC1C,gCAAgC,MAAM;KACtC,8BAA8B,MAAM;KACpC,0CAA0C,MAAM;KAChD,gCAAgC,MAAM;KACtC,iCAAiC,MAAM;KACvC,+BAA+B,MAAM;KACrC,gCAAgC,MAAM;KACtC,oCAAoC,MAAM;KAC1C,oCAAoC,MAAM;IAC5C;GACF,CAAC;;CAGJ,kBAAgC;AAC9B,MAAI,KAAK,yBAAyB;AAChC,gBAAa,KAAK,wBAAwB;AAC1C,QAAK,0BAA0B,KAAA;;AAGjC,MAAI,KAAK,QACP,QAAO,oBAAoB,QAAQ,KAAK,QAAQ;AAElD,MAAI,KAAK,YACP,QAAO,oBAAoB,YAAY,KAAK,YAAY"}
@@ -0,0 +1,6 @@
1
+ //#region package.json
2
+ var version = "0.2.0";
3
+ //#endregion
4
+ export { version };
5
+
6
+ //# sourceMappingURL=package.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"package.js","names":[],"sources":["../package.json"],"sourcesContent":[""],"mappings":""}
@@ -1,2 +1,3 @@
1
+ import { UserActionInstrumentationConfig } from "./types.js";
1
2
  import { UserActionInstrumentation } from "./instrumentation.js";
2
- export { UserActionInstrumentation };
3
+ export { UserActionInstrumentation, type UserActionInstrumentationConfig };
@@ -1,4 +1,5 @@
1
- import { getElementCSSSelector } from "../web-utils/dist/getElementCSSSelector.js";
1
+ import { version } from "../package.js";
2
+ import { getElementCSSSelector } from "../utils/getElementCSSSelector.js";
2
3
  import { ATTR_CSS_SELECTOR, ATTR_MOUSE_EVENT_BUTTON, ATTR_PAGE_X, ATTR_PAGE_Y, ATTR_TAGS, ATTR_TAG_NAME, CLICK_EVENT_NAME } from "./semconv.js";
3
4
  import { SeverityNumber } from "@opentelemetry/api-logs";
4
5
  import { InstrumentationBase } from "@opentelemetry/instrumentation";
@@ -10,7 +11,7 @@ const OTEL_ELEMENT_ATTRIBUTE_PREFIX = "data-otel-";
10
11
  */
11
12
  var UserActionInstrumentation = class extends InstrumentationBase {
12
13
  constructor(config = {}) {
13
- super("@opentelemetry/instrumentation-user-action", "0.1.0", config);
14
+ super("@opentelemetry/browser-instrumentation/user-action", version, config);
14
15
  }
15
16
  init() {
16
17
  return [];
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.js","names":[],"sources":["../../src/user-action/instrumentation.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { SeverityNumber } from '@opentelemetry/api-logs';\nimport { InstrumentationBase } from '@opentelemetry/instrumentation';\nimport { getElementCSSSelector } from '@opentelemetry/web-utils';\nimport {\n ATTR_CSS_SELECTOR,\n ATTR_MOUSE_EVENT_BUTTON,\n ATTR_PAGE_X,\n ATTR_PAGE_Y,\n ATTR_TAG_NAME,\n ATTR_TAGS,\n CLICK_EVENT_NAME,\n} from './semconv.ts';\nimport type {\n AutoCapturedUserAction,\n MouseButton,\n UserActionInstrumentationConfig,\n} from './types.ts';\n\nconst DEFAULT_AUTO_CAPTURED_ACTIONS: AutoCapturedUserAction[] = ['click'];\nconst OTEL_ELEMENT_ATTRIBUTE_PREFIX = 'data-otel-';\n\n/**\n * This class automatically instruments different User Actions within the browser.\n */\nexport class UserActionInstrumentation extends InstrumentationBase<UserActionInstrumentationConfig> {\n private declare _onClickHandler?: (event: MouseEvent) => void;\n\n constructor(config: UserActionInstrumentationConfig = {}) {\n super('@opentelemetry/instrumentation-user-action', '0.1.0', config);\n }\n\n protected override init() {\n return [];\n }\n\n private _getMouseButtonFromMouseEvent(event: MouseEvent): MouseButton {\n switch (event.button) {\n case 0:\n return 'left';\n case 1:\n return 'middle';\n case 2:\n return 'right';\n default:\n return 'left';\n }\n }\n\n private onClick(event: MouseEvent) {\n const element = event.target;\n\n if (!(element instanceof HTMLElement)) {\n return;\n }\n\n if (element.hasAttribute('disabled')) {\n return;\n }\n\n const cssSelector = getElementCSSSelector(element, {\n useIdForTargetElement: true,\n useIdForAncestors: true,\n });\n const otelPrefixedAttributes: Record<string, string> = {};\n\n // Grab all the attributes in the element that start with data-otel-*\n for (const attr of element.attributes) {\n if (attr.name.startsWith(OTEL_ELEMENT_ATTRIBUTE_PREFIX)) {\n otelPrefixedAttributes[\n attr.name.slice(OTEL_ELEMENT_ATTRIBUTE_PREFIX.length)\n ] = attr.value;\n }\n }\n\n this.logger.emit({\n severityNumber: SeverityNumber.INFO,\n eventName: CLICK_EVENT_NAME,\n attributes: {\n [ATTR_PAGE_X]: event.pageX,\n [ATTR_PAGE_Y]: event.pageY,\n [ATTR_TAG_NAME]: element.tagName,\n [ATTR_TAGS]: otelPrefixedAttributes,\n [ATTR_MOUSE_EVENT_BUTTON]: this._getMouseButtonFromMouseEvent(event),\n [ATTR_CSS_SELECTOR]: cssSelector,\n },\n });\n }\n\n override enable(): void {\n const autoCapturedActions =\n this._config.autoCapturedActions ?? DEFAULT_AUTO_CAPTURED_ACTIONS;\n if (!this._onClickHandler) {\n this._onClickHandler = this.onClick.bind(this);\n }\n\n if (autoCapturedActions.includes('click')) {\n document.addEventListener('click', this._onClickHandler, true);\n }\n }\n\n override disable(): void {\n if (this._onClickHandler) {\n document.removeEventListener('click', this._onClickHandler, true);\n }\n }\n}\n"],"mappings":";;;;;AAuBA,MAAM,gCAA0D,CAAC,QAAQ;AACzE,MAAM,gCAAgC;;;;AAKtC,IAAa,4BAAb,cAA+C,oBAAqD;CAGlG,YAAY,SAA0C,EAAE,EAAE;AACxD,QAAM,8CAA8C,SAAS,OAAO;;CAGtE,OAA0B;AACxB,SAAO,EAAE;;CAGX,8BAAsC,OAAgC;AACpE,UAAQ,MAAM,QAAd;GACE,KAAK,EACH,QAAO;GACT,KAAK,EACH,QAAO;GACT,KAAK,EACH,QAAO;GACT,QACE,QAAO;;;CAIb,QAAgB,OAAmB;EACjC,MAAM,UAAU,MAAM;AAEtB,MAAI,EAAE,mBAAmB,aACvB;AAGF,MAAI,QAAQ,aAAa,WAAW,CAClC;EAGF,MAAM,cAAc,sBAAsB,SAAS;GACjD,uBAAuB;GACvB,mBAAmB;GACpB,CAAC;EACF,MAAM,yBAAiD,EAAE;AAGzD,OAAK,MAAM,QAAQ,QAAQ,WACzB,KAAI,KAAK,KAAK,WAAW,8BAA8B,CACrD,wBACE,KAAK,KAAK,MAAM,GAAqC,IACnD,KAAK;AAIb,OAAK,OAAO,KAAK;GACf,gBAAgB,eAAe;GAC/B,WAAW;GACX,YAAY;KACT,cAAc,MAAM;KACpB,cAAc,MAAM;KACpB,gBAAgB,QAAQ;KACxB,YAAY;KACZ,0BAA0B,KAAK,8BAA8B,MAAM;KACnE,oBAAoB;IACtB;GACF,CAAC;;CAGJ,SAAwB;EACtB,MAAM,sBACJ,KAAK,QAAQ,uBAAuB;AACtC,MAAI,CAAC,KAAK,gBACR,MAAK,kBAAkB,KAAK,QAAQ,KAAK,KAAK;AAGhD,MAAI,oBAAoB,SAAS,QAAQ,CACvC,UAAS,iBAAiB,SAAS,KAAK,iBAAiB,KAAK;;CAIlE,UAAyB;AACvB,MAAI,KAAK,gBACP,UAAS,oBAAoB,SAAS,KAAK,iBAAiB,KAAK"}
1
+ {"version":3,"file":"instrumentation.js","names":[],"sources":["../../src/user-action/instrumentation.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { SeverityNumber } from '@opentelemetry/api-logs';\nimport { InstrumentationBase } from '@opentelemetry/instrumentation';\nimport { getElementCSSSelector } from '#instrumentation-utils';\nimport { version } from '../../package.json' with { type: 'json' };\nimport {\n ATTR_CSS_SELECTOR,\n ATTR_MOUSE_EVENT_BUTTON,\n ATTR_PAGE_X,\n ATTR_PAGE_Y,\n ATTR_TAG_NAME,\n ATTR_TAGS,\n CLICK_EVENT_NAME,\n} from './semconv.ts';\nimport type {\n AutoCapturedUserAction,\n MouseButton,\n UserActionInstrumentationConfig,\n} from './types.ts';\n\nconst DEFAULT_AUTO_CAPTURED_ACTIONS: AutoCapturedUserAction[] = ['click'];\nconst OTEL_ELEMENT_ATTRIBUTE_PREFIX = 'data-otel-';\n\n/**\n * This class automatically instruments different User Actions within the browser.\n */\nexport class UserActionInstrumentation extends InstrumentationBase<UserActionInstrumentationConfig> {\n private declare _onClickHandler?: (event: MouseEvent) => void;\n\n constructor(config: UserActionInstrumentationConfig = {}) {\n super(\n '@opentelemetry/browser-instrumentation/user-action',\n version,\n config,\n );\n }\n\n protected override init() {\n return [];\n }\n\n private _getMouseButtonFromMouseEvent(event: MouseEvent): MouseButton {\n switch (event.button) {\n case 0:\n return 'left';\n case 1:\n return 'middle';\n case 2:\n return 'right';\n default:\n return 'left';\n }\n }\n\n private onClick(event: MouseEvent) {\n const element = event.target;\n\n if (!(element instanceof HTMLElement)) {\n return;\n }\n\n if (element.hasAttribute('disabled')) {\n return;\n }\n\n const cssSelector = getElementCSSSelector(element, {\n useIdForTargetElement: true,\n useIdForAncestors: true,\n });\n const otelPrefixedAttributes: Record<string, string> = {};\n\n // Grab all the attributes in the element that start with data-otel-*\n for (const attr of element.attributes) {\n if (attr.name.startsWith(OTEL_ELEMENT_ATTRIBUTE_PREFIX)) {\n otelPrefixedAttributes[\n attr.name.slice(OTEL_ELEMENT_ATTRIBUTE_PREFIX.length)\n ] = attr.value;\n }\n }\n\n this.logger.emit({\n severityNumber: SeverityNumber.INFO,\n eventName: CLICK_EVENT_NAME,\n attributes: {\n [ATTR_PAGE_X]: event.pageX,\n [ATTR_PAGE_Y]: event.pageY,\n [ATTR_TAG_NAME]: element.tagName,\n [ATTR_TAGS]: otelPrefixedAttributes,\n [ATTR_MOUSE_EVENT_BUTTON]: this._getMouseButtonFromMouseEvent(event),\n [ATTR_CSS_SELECTOR]: cssSelector,\n },\n });\n }\n\n override enable(): void {\n const autoCapturedActions =\n this._config.autoCapturedActions ?? DEFAULT_AUTO_CAPTURED_ACTIONS;\n if (!this._onClickHandler) {\n this._onClickHandler = this.onClick.bind(this);\n }\n\n if (autoCapturedActions.includes('click')) {\n document.addEventListener('click', this._onClickHandler, true);\n }\n }\n\n override disable(): void {\n if (this._onClickHandler) {\n document.removeEventListener('click', this._onClickHandler, true);\n }\n }\n}\n"],"mappings":";;;;;;AAwBA,MAAM,gCAA0D,CAAC,QAAQ;AACzE,MAAM,gCAAgC;;;;AAKtC,IAAa,4BAAb,cAA+C,oBAAqD;CAGlG,YAAY,SAA0C,EAAE,EAAE;AACxD,QACE,sDACA,SACA,OACD;;CAGH,OAA0B;AACxB,SAAO,EAAE;;CAGX,8BAAsC,OAAgC;AACpE,UAAQ,MAAM,QAAd;GACE,KAAK,EACH,QAAO;GACT,KAAK,EACH,QAAO;GACT,KAAK,EACH,QAAO;GACT,QACE,QAAO;;;CAIb,QAAgB,OAAmB;EACjC,MAAM,UAAU,MAAM;AAEtB,MAAI,EAAE,mBAAmB,aACvB;AAGF,MAAI,QAAQ,aAAa,WAAW,CAClC;EAGF,MAAM,cAAc,sBAAsB,SAAS;GACjD,uBAAuB;GACvB,mBAAmB;GACpB,CAAC;EACF,MAAM,yBAAiD,EAAE;AAGzD,OAAK,MAAM,QAAQ,QAAQ,WACzB,KAAI,KAAK,KAAK,WAAW,8BAA8B,CACrD,wBACE,KAAK,KAAK,MAAM,GAAqC,IACnD,KAAK;AAIb,OAAK,OAAO,KAAK;GACf,gBAAgB,eAAe;GAC/B,WAAW;GACX,YAAY;KACT,cAAc,MAAM;KACpB,cAAc,MAAM;KACpB,gBAAgB,QAAQ;KACxB,YAAY;KACZ,0BAA0B,KAAK,8BAA8B,MAAM;KACnE,oBAAoB;IACtB;GACF,CAAC;;CAGJ,SAAwB;EACtB,MAAM,sBACJ,KAAK,QAAQ,uBAAuB;AACtC,MAAI,CAAC,KAAK,gBACR,MAAK,kBAAkB,KAAK,QAAQ,KAAK,KAAK;AAGhD,MAAI,oBAAoB,SAAS,QAAQ,CACvC,UAAS,iBAAiB,SAAS,KAAK,iBAAiB,KAAK;;CAIlE,UAAyB;AACvB,MAAI,KAAK,gBACP,UAAS,oBAAoB,SAAS,KAAK,iBAAiB,KAAK"}
@@ -1,4 +1,4 @@
1
- //#region ../web-utils/dist/getElementCSSSelector.js
1
+ //#region src/utils/getElementCSSSelector.ts
2
2
  /**
3
3
  * Generates the CSS selector of a given element in the DOM tree.
4
4
  *
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getElementCSSSelector.js","names":[],"sources":["../../src/utils/getElementCSSSelector.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\ntype GetElementCSSSelectorOptions = {\n /**\n * If true, the function will attempt to use element ID to create condensed CSS selector.\n */\n useIdForTargetElement?: boolean;\n /**\n * If true, the function will attempt to use element ID for all ancestor elements to create condensed CSS selector.\n */\n useIdForAncestors?: boolean;\n};\n\n/**\n * Generates the CSS selector of a given element in the DOM tree.\n *\n * @example #main > div:nth-child(2) > button.submit\n * @example #unique-id\n */\nexport const getElementCSSSelector = (\n element: Node,\n {\n useIdForTargetElement = false,\n useIdForAncestors = false,\n }: GetElementCSSSelectorOptions = {},\n): string => {\n // Handle document node\n if (element.nodeType === Node.DOCUMENT_NODE) {\n return '';\n }\n\n const htmlElement = element as HTMLElement;\n const nodeValue = getNodeSelector(\n htmlElement,\n useIdForTargetElement || useIdForAncestors,\n );\n\n // If optimized and found an ID selector, stop recursion early\n if (nodeValue.startsWith('#')) {\n return nodeValue;\n }\n\n const parent = htmlElement.parentElement;\n const parentSelector = parent\n ? getElementCSSSelector(parent, {\n useIdForAncestors,\n useIdForTargetElement: false,\n })\n : '';\n\n return parentSelector ? `${parentSelector} > ${nodeValue}` : nodeValue;\n};\n\nconst getNodeSelector = (element: Node, useElementId = false): string => {\n if (element.nodeType !== Node.ELEMENT_NODE) {\n return '';\n }\n\n const htmlElement = element as HTMLElement;\n const id = htmlElement.getAttribute('id');\n\n // Use ID if requested and it's unique\n if (useElementId && id) {\n // Check if ID is unique in the document\n const elementsWithSameId = htmlElement.ownerDocument.querySelectorAll(\n `#${CSS.escape(id)}`,\n );\n\n if (elementsWithSameId.length === 1) {\n return `#${CSS.escape(id)}`;\n }\n }\n\n let selector = getFullClassSelector(htmlElement);\n // Add nth-child if there are siblings with the same tag and classes\n const index = getNthChild(htmlElement);\n\n if (index > 0) {\n selector += `:nth-child(${index})`;\n }\n\n return selector;\n};\n\nconst getNthChild = (element: HTMLElement): number => {\n // parentElement is needed to access children\n if (!element.parentElement) {\n return 0;\n }\n\n const selector = getFullClassSelector(element);\n\n // Get all siblings that match the same selector\n const siblings = Array.from(element.parentElement.children).filter(\n (sibling) => getFullClassSelector(sibling) === selector,\n );\n\n // Only add nth-child if there are multiple matching siblings\n if (siblings.length > 1) {\n return siblings.indexOf(element) + 1;\n }\n\n return 0;\n};\n\nconst getFullClassSelector = (element: Element): string =>\n element.localName +\n (element.classList.length > 0\n ? Array.from(element.classList)\n .map((cls) => `.${CSS.escape(cls)}`)\n .join('')\n : '');\n"],"mappings":";;;;;;;AAsBA,MAAa,yBACX,SACA,EACE,wBAAwB,OACxB,oBAAoB,UACY,EAAE,KACzB;AAEX,KAAI,QAAQ,aAAa,KAAK,cAC5B,QAAO;CAGT,MAAM,cAAc;CACpB,MAAM,YAAY,gBAChB,aACA,yBAAyB,kBAC1B;AAGD,KAAI,UAAU,WAAW,IAAI,CAC3B,QAAO;CAGT,MAAM,SAAS,YAAY;CAC3B,MAAM,iBAAiB,SACnB,sBAAsB,QAAQ;EAC5B;EACA,uBAAuB;EACxB,CAAC,GACF;AAEJ,QAAO,iBAAiB,GAAG,eAAe,KAAK,cAAc;;AAG/D,MAAM,mBAAmB,SAAe,eAAe,UAAkB;AACvE,KAAI,QAAQ,aAAa,KAAK,aAC5B,QAAO;CAGT,MAAM,cAAc;CACpB,MAAM,KAAK,YAAY,aAAa,KAAK;AAGzC,KAAI,gBAAgB;MAES,YAAY,cAAc,iBACnD,IAAI,IAAI,OAAO,GAAG,GACnB,CAEsB,WAAW,EAChC,QAAO,IAAI,IAAI,OAAO,GAAG;;CAI7B,IAAI,WAAW,qBAAqB,YAAY;CAEhD,MAAM,QAAQ,YAAY,YAAY;AAEtC,KAAI,QAAQ,EACV,aAAY,cAAc,MAAM;AAGlC,QAAO;;AAGT,MAAM,eAAe,YAAiC;AAEpD,KAAI,CAAC,QAAQ,cACX,QAAO;CAGT,MAAM,WAAW,qBAAqB,QAAQ;CAG9C,MAAM,WAAW,MAAM,KAAK,QAAQ,cAAc,SAAS,CAAC,QACzD,YAAY,qBAAqB,QAAQ,KAAK,SAChD;AAGD,KAAI,SAAS,SAAS,EACpB,QAAO,SAAS,QAAQ,QAAQ,GAAG;AAGrC,QAAO;;AAGT,MAAM,wBAAwB,YAC5B,QAAQ,aACP,QAAQ,UAAU,SAAS,IACxB,MAAM,KAAK,QAAQ,UAAU,CAC1B,KAAK,QAAQ,IAAI,IAAI,OAAO,IAAI,GAAG,CACnC,KAAK,GAAG,GACX"}
@@ -1,3 +1,4 @@
1
+ import { version } from "../package.js";
1
2
  import { ATTR_WEB_VITAL_DELTA, ATTR_WEB_VITAL_ID, ATTR_WEB_VITAL_NAME, ATTR_WEB_VITAL_NAVIGATION_TYPE, ATTR_WEB_VITAL_RATING, ATTR_WEB_VITAL_VALUE, WEB_VITAL_EVENT_NAME } from "./semconv.js";
2
3
  import { SeverityNumber } from "@opentelemetry/api-logs";
3
4
  import { InstrumentationBase, safeExecuteInTheMiddle } from "@opentelemetry/instrumentation";
@@ -15,7 +16,7 @@ var WebVitalsInstrumentation = class extends InstrumentationBase {
15
16
  _applyCustomLogRecordData;
16
17
  _includeRawAttribution;
17
18
  constructor(config = {}) {
18
- super("@opentelemetry/instrumentation-web-vitals", "0.1.0", config);
19
+ super("@opentelemetry/browser-instrumentation/web-vitals", version, config);
19
20
  this._applyCustomLogRecordData = config.applyCustomLogRecordData;
20
21
  this._includeRawAttribution = config.includeRawAttribution ?? false;
21
22
  }
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.js","names":[],"sources":["../../src/web-vitals/instrumentation.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Attributes } from '@opentelemetry/api';\nimport type { LogRecord } from '@opentelemetry/api-logs';\nimport { SeverityNumber } from '@opentelemetry/api-logs';\nimport {\n InstrumentationBase,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport type {\n CLSMetricWithAttribution,\n INPMetricWithAttribution,\n MetricWithAttribution,\n} from 'web-vitals/attribution';\nimport { onCLS, onFCP, onINP, onLCP, onTTFB } from 'web-vitals/attribution';\nimport {\n ATTR_WEB_VITAL_DELTA,\n ATTR_WEB_VITAL_ID,\n ATTR_WEB_VITAL_NAME,\n ATTR_WEB_VITAL_NAVIGATION_TYPE,\n ATTR_WEB_VITAL_RATING,\n ATTR_WEB_VITAL_VALUE,\n WEB_VITAL_EVENT_NAME,\n} from './semconv.ts';\nimport type { WebVitalsInstrumentationConfig } from './types.ts';\n\n/**\n * Instrumentation for Core Web Vitals using the `web-vitals` library.\n * https://github.com/GoogleChrome/web-vitals\n *\n * Note: The `web-vitals` library does not support removing listeners once\n * registered. Calling `disable()` will stop emitting logs, but the underlying\n * listeners remain active. Calling `enable()` again will resume emission.\n */\nexport class WebVitalsInstrumentation extends InstrumentationBase<WebVitalsInstrumentationConfig> {\n // Using `declare` is required here: InstrumentationBase calls enable() during\n // construction, and standard field initialization would reset this flag after\n // super() returns, breaking the duplicate-registration guard.\n private declare _isEnabled: boolean;\n private declare _listenersRegistered: boolean;\n private _applyCustomLogRecordData?: (logRecord: LogRecord) => void;\n private _includeRawAttribution: boolean;\n\n constructor(config: WebVitalsInstrumentationConfig = {}) {\n super('@opentelemetry/instrumentation-web-vitals', '0.1.0', config);\n this._applyCustomLogRecordData = config.applyCustomLogRecordData;\n this._includeRawAttribution = config.includeRawAttribution ?? false;\n }\n\n protected override init() {\n return [];\n }\n\n /**\n * Enables the instrumentation and registers web-vitals listeners.\n * Listeners are registered only once. If disabled, subsequent calls resume emission.\n */\n override enable(): void {\n if (typeof PerformanceObserver === 'undefined') {\n this._diag.debug(\n 'PerformanceObserver not supported, web vitals will not be collected',\n );\n return;\n }\n\n this._isEnabled = true;\n\n if (this._listenersRegistered) {\n this._diag.debug('Listeners already registered, resuming emission');\n return;\n }\n\n this._listenersRegistered = true;\n this._diag.debug(`Registering listeners`);\n // CLS is only supported in Chromium. See:\n // https://github.com/GoogleChrome/web-vitals?tab=readme-ov-file#browser-support\n onCLS((metric) => this._emitWebVital(metric));\n onINP((metric) => this._emitWebVital(metric));\n onLCP((metric) => this._emitWebVital(metric));\n onFCP((metric) => this._emitWebVital(metric));\n onTTFB((metric) => this._emitWebVital(metric));\n }\n\n /**\n * Disables the instrumentation, pausing log emission.\n * Listeners remain active due to web-vitals library limitations.\n */\n override disable(): void {\n this._isEnabled = false;\n this._diag.debug('Instrumentation disabled, pausing emission');\n }\n\n /**\n * Gets the timestamp for a metric based on attribution timing.\n * Returns undefined to let OTel use the current time for metrics without\n * specific timing information.\n */\n private _getTimestampForMetric(\n metric: MetricWithAttribution,\n ): number | undefined {\n if (metric.name === 'CLS') {\n const { attribution } = metric as CLSMetricWithAttribution;\n if (attribution.largestShiftTime !== undefined) {\n return attribution.largestShiftTime;\n }\n return undefined;\n }\n if (metric.name === 'INP') {\n const { attribution } = metric as INPMetricWithAttribution;\n return attribution.interactionTime;\n }\n // FCP, LCP, TTFB: metric.value is already DOMHighResTimeStamp of the event\n return metric.value;\n }\n\n private _emitWebVital(metric: MetricWithAttribution): void {\n if (!this._isEnabled) {\n return;\n }\n const attributes: Attributes = {\n [ATTR_WEB_VITAL_NAME]: metric.name.toLowerCase(),\n [ATTR_WEB_VITAL_VALUE]: metric.value,\n // `delta` equals `value` on the first emission; subsequent emissions report only the change\n [ATTR_WEB_VITAL_DELTA]: metric.delta,\n [ATTR_WEB_VITAL_RATING]: metric.rating,\n [ATTR_WEB_VITAL_ID]: metric.id,\n [ATTR_WEB_VITAL_NAVIGATION_TYPE]: metric.navigationType,\n };\n\n const timestamp = this._getTimestampForMetric(metric);\n\n const logRecord: LogRecord = {\n eventName: WEB_VITAL_EVENT_NAME,\n severityNumber: SeverityNumber.INFO,\n attributes,\n ...(this._includeRawAttribution\n ? { body: JSON.stringify(metric.attribution) }\n : {}),\n ...(timestamp !== undefined ? { timestamp } : {}),\n };\n\n if (this._applyCustomLogRecordData) {\n safeExecuteInTheMiddle(\n () => this._applyCustomLogRecordData?.(logRecord),\n (error) => {\n if (error) {\n this._diag.error('applyCustomLogRecordData hook failed', error);\n }\n },\n true,\n );\n }\n\n this.logger.emit(logRecord);\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAqCA,IAAa,2BAAb,cAA8C,oBAAoD;CAMhG;CACA;CAEA,YAAY,SAAyC,EAAE,EAAE;AACvD,QAAM,6CAA6C,SAAS,OAAO;AACnE,OAAK,4BAA4B,OAAO;AACxC,OAAK,yBAAyB,OAAO,yBAAyB;;CAGhE,OAA0B;AACxB,SAAO,EAAE;;;;;;CAOX,SAAwB;AACtB,MAAI,OAAO,wBAAwB,aAAa;AAC9C,QAAK,MAAM,MACT,sEACD;AACD;;AAGF,OAAK,aAAa;AAElB,MAAI,KAAK,sBAAsB;AAC7B,QAAK,MAAM,MAAM,kDAAkD;AACnE;;AAGF,OAAK,uBAAuB;AAC5B,OAAK,MAAM,MAAM,wBAAwB;AAGzC,SAAO,WAAW,KAAK,cAAc,OAAO,CAAC;AAC7C,SAAO,WAAW,KAAK,cAAc,OAAO,CAAC;AAC7C,SAAO,WAAW,KAAK,cAAc,OAAO,CAAC;AAC7C,SAAO,WAAW,KAAK,cAAc,OAAO,CAAC;AAC7C,UAAQ,WAAW,KAAK,cAAc,OAAO,CAAC;;;;;;CAOhD,UAAyB;AACvB,OAAK,aAAa;AAClB,OAAK,MAAM,MAAM,6CAA6C;;;;;;;CAQhE,uBACE,QACoB;AACpB,MAAI,OAAO,SAAS,OAAO;GACzB,MAAM,EAAE,gBAAgB;AACxB,OAAI,YAAY,qBAAqB,KAAA,EACnC,QAAO,YAAY;AAErB;;AAEF,MAAI,OAAO,SAAS,OAAO;GACzB,MAAM,EAAE,gBAAgB;AACxB,UAAO,YAAY;;AAGrB,SAAO,OAAO;;CAGhB,cAAsB,QAAqC;AACzD,MAAI,CAAC,KAAK,WACR;EAEF,MAAM,aAAyB;IAC5B,sBAAsB,OAAO,KAAK,aAAa;IAC/C,uBAAuB,OAAO;IAE9B,uBAAuB,OAAO;IAC9B,wBAAwB,OAAO;IAC/B,oBAAoB,OAAO;IAC3B,iCAAiC,OAAO;GAC1C;EAED,MAAM,YAAY,KAAK,uBAAuB,OAAO;EAErD,MAAM,YAAuB;GAC3B,WAAW;GACX,gBAAgB,eAAe;GAC/B;GACA,GAAI,KAAK,yBACL,EAAE,MAAM,KAAK,UAAU,OAAO,YAAY,EAAE,GAC5C,EAAE;GACN,GAAI,cAAc,KAAA,IAAY,EAAE,WAAW,GAAG,EAAE;GACjD;AAED,MAAI,KAAK,0BACP,8BACQ,KAAK,4BAA4B,UAAU,GAChD,UAAU;AACT,OAAI,MACF,MAAK,MAAM,MAAM,wCAAwC,MAAM;KAGnE,KACD;AAGH,OAAK,OAAO,KAAK,UAAU"}
1
+ {"version":3,"file":"instrumentation.js","names":[],"sources":["../../src/web-vitals/instrumentation.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Attributes } from '@opentelemetry/api';\nimport type { LogRecord } from '@opentelemetry/api-logs';\nimport { SeverityNumber } from '@opentelemetry/api-logs';\nimport {\n InstrumentationBase,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport type {\n CLSMetricWithAttribution,\n INPMetricWithAttribution,\n MetricWithAttribution,\n} from 'web-vitals/attribution';\nimport { onCLS, onFCP, onINP, onLCP, onTTFB } from 'web-vitals/attribution';\nimport { version } from '../../package.json' with { type: 'json' };\nimport {\n ATTR_WEB_VITAL_DELTA,\n ATTR_WEB_VITAL_ID,\n ATTR_WEB_VITAL_NAME,\n ATTR_WEB_VITAL_NAVIGATION_TYPE,\n ATTR_WEB_VITAL_RATING,\n ATTR_WEB_VITAL_VALUE,\n WEB_VITAL_EVENT_NAME,\n} from './semconv.ts';\nimport type { WebVitalsInstrumentationConfig } from './types.ts';\n\n/**\n * Instrumentation for Core Web Vitals using the `web-vitals` library.\n * https://github.com/GoogleChrome/web-vitals\n *\n * Note: The `web-vitals` library does not support removing listeners once\n * registered. Calling `disable()` will stop emitting logs, but the underlying\n * listeners remain active. Calling `enable()` again will resume emission.\n */\nexport class WebVitalsInstrumentation extends InstrumentationBase<WebVitalsInstrumentationConfig> {\n // Using `declare` is required here: InstrumentationBase calls enable() during\n // construction, and standard field initialization would reset this flag after\n // super() returns, breaking the duplicate-registration guard.\n private declare _isEnabled: boolean;\n private declare _listenersRegistered: boolean;\n private _applyCustomLogRecordData?: (logRecord: LogRecord) => void;\n private _includeRawAttribution: boolean;\n\n constructor(config: WebVitalsInstrumentationConfig = {}) {\n super('@opentelemetry/browser-instrumentation/web-vitals', version, config);\n this._applyCustomLogRecordData = config.applyCustomLogRecordData;\n this._includeRawAttribution = config.includeRawAttribution ?? false;\n }\n\n protected override init() {\n return [];\n }\n\n /**\n * Enables the instrumentation and registers web-vitals listeners.\n * Listeners are registered only once. If disabled, subsequent calls resume emission.\n */\n override enable(): void {\n if (typeof PerformanceObserver === 'undefined') {\n this._diag.debug(\n 'PerformanceObserver not supported, web vitals will not be collected',\n );\n return;\n }\n\n this._isEnabled = true;\n\n if (this._listenersRegistered) {\n this._diag.debug('Listeners already registered, resuming emission');\n return;\n }\n\n this._listenersRegistered = true;\n this._diag.debug(`Registering listeners`);\n // CLS is only supported in Chromium. See:\n // https://github.com/GoogleChrome/web-vitals?tab=readme-ov-file#browser-support\n onCLS((metric) => this._emitWebVital(metric));\n onINP((metric) => this._emitWebVital(metric));\n onLCP((metric) => this._emitWebVital(metric));\n onFCP((metric) => this._emitWebVital(metric));\n onTTFB((metric) => this._emitWebVital(metric));\n }\n\n /**\n * Disables the instrumentation, pausing log emission.\n * Listeners remain active due to web-vitals library limitations.\n */\n override disable(): void {\n this._isEnabled = false;\n this._diag.debug('Instrumentation disabled, pausing emission');\n }\n\n /**\n * Gets the timestamp for a metric based on attribution timing.\n * Returns undefined to let OTel use the current time for metrics without\n * specific timing information.\n */\n private _getTimestampForMetric(\n metric: MetricWithAttribution,\n ): number | undefined {\n if (metric.name === 'CLS') {\n const { attribution } = metric as CLSMetricWithAttribution;\n if (attribution.largestShiftTime !== undefined) {\n return attribution.largestShiftTime;\n }\n return undefined;\n }\n if (metric.name === 'INP') {\n const { attribution } = metric as INPMetricWithAttribution;\n return attribution.interactionTime;\n }\n // FCP, LCP, TTFB: metric.value is already DOMHighResTimeStamp of the event\n return metric.value;\n }\n\n private _emitWebVital(metric: MetricWithAttribution): void {\n if (!this._isEnabled) {\n return;\n }\n const attributes: Attributes = {\n [ATTR_WEB_VITAL_NAME]: metric.name.toLowerCase(),\n [ATTR_WEB_VITAL_VALUE]: metric.value,\n // `delta` equals `value` on the first emission; subsequent emissions report only the change\n [ATTR_WEB_VITAL_DELTA]: metric.delta,\n [ATTR_WEB_VITAL_RATING]: metric.rating,\n [ATTR_WEB_VITAL_ID]: metric.id,\n [ATTR_WEB_VITAL_NAVIGATION_TYPE]: metric.navigationType,\n };\n\n const timestamp = this._getTimestampForMetric(metric);\n\n const logRecord: LogRecord = {\n eventName: WEB_VITAL_EVENT_NAME,\n severityNumber: SeverityNumber.INFO,\n attributes,\n ...(this._includeRawAttribution\n ? { body: JSON.stringify(metric.attribution) }\n : {}),\n ...(timestamp !== undefined ? { timestamp } : {}),\n };\n\n if (this._applyCustomLogRecordData) {\n safeExecuteInTheMiddle(\n () => this._applyCustomLogRecordData?.(logRecord),\n (error) => {\n if (error) {\n this._diag.error('applyCustomLogRecordData hook failed', error);\n }\n },\n true,\n );\n }\n\n this.logger.emit(logRecord);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAsCA,IAAa,2BAAb,cAA8C,oBAAoD;CAMhG;CACA;CAEA,YAAY,SAAyC,EAAE,EAAE;AACvD,QAAM,qDAAqD,SAAS,OAAO;AAC3E,OAAK,4BAA4B,OAAO;AACxC,OAAK,yBAAyB,OAAO,yBAAyB;;CAGhE,OAA0B;AACxB,SAAO,EAAE;;;;;;CAOX,SAAwB;AACtB,MAAI,OAAO,wBAAwB,aAAa;AAC9C,QAAK,MAAM,MACT,sEACD;AACD;;AAGF,OAAK,aAAa;AAElB,MAAI,KAAK,sBAAsB;AAC7B,QAAK,MAAM,MAAM,kDAAkD;AACnE;;AAGF,OAAK,uBAAuB;AAC5B,OAAK,MAAM,MAAM,wBAAwB;AAGzC,SAAO,WAAW,KAAK,cAAc,OAAO,CAAC;AAC7C,SAAO,WAAW,KAAK,cAAc,OAAO,CAAC;AAC7C,SAAO,WAAW,KAAK,cAAc,OAAO,CAAC;AAC7C,SAAO,WAAW,KAAK,cAAc,OAAO,CAAC;AAC7C,UAAQ,WAAW,KAAK,cAAc,OAAO,CAAC;;;;;;CAOhD,UAAyB;AACvB,OAAK,aAAa;AAClB,OAAK,MAAM,MAAM,6CAA6C;;;;;;;CAQhE,uBACE,QACoB;AACpB,MAAI,OAAO,SAAS,OAAO;GACzB,MAAM,EAAE,gBAAgB;AACxB,OAAI,YAAY,qBAAqB,KAAA,EACnC,QAAO,YAAY;AAErB;;AAEF,MAAI,OAAO,SAAS,OAAO;GACzB,MAAM,EAAE,gBAAgB;AACxB,UAAO,YAAY;;AAGrB,SAAO,OAAO;;CAGhB,cAAsB,QAAqC;AACzD,MAAI,CAAC,KAAK,WACR;EAEF,MAAM,aAAyB;IAC5B,sBAAsB,OAAO,KAAK,aAAa;IAC/C,uBAAuB,OAAO;IAE9B,uBAAuB,OAAO;IAC9B,wBAAwB,OAAO;IAC/B,oBAAoB,OAAO;IAC3B,iCAAiC,OAAO;GAC1C;EAED,MAAM,YAAY,KAAK,uBAAuB,OAAO;EAErD,MAAM,YAAuB;GAC3B,WAAW;GACX,gBAAgB,eAAe;GAC/B;GACA,GAAI,KAAK,yBACL,EAAE,MAAM,KAAK,UAAU,OAAO,YAAY,EAAE,GAC5C,EAAE;GACN,GAAI,cAAc,KAAA,IAAY,EAAE,WAAW,GAAG,EAAE;GACjD;AAED,MAAI,KAAK,0BACP,8BACQ,KAAK,4BAA4B,UAAU,GAChD,UAAU;AACT,OAAI,MACF,MAAK,MAAM,MAAM,wCAAwC,MAAM;KAGnE,KACD;AAGH,OAAK,OAAO,KAAK,UAAU"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opentelemetry/browser-instrumentation",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "OpenTelemetry browser instrumentations.",
5
5
  "keywords": [
6
6
  "opentelemetry",
@@ -21,6 +21,10 @@
21
21
  "directory": "packages/instrumentation"
22
22
  },
23
23
  "type": "module",
24
+ "imports": {
25
+ "#instrumentation-utils": "./src/utils/index.ts",
26
+ "#instrumentation-test-utils": "./src/test-utils/index.ts"
27
+ },
24
28
  "exports": {
25
29
  "./experimental/navigation-timing": "./dist/navigation-timing/index.js",
26
30
  "./experimental/user-action": "./dist/user-action/index.js",
@@ -46,8 +50,7 @@
46
50
  "@opentelemetry/api": "^1.9.0"
47
51
  },
48
52
  "devDependencies": {
49
- "@opentelemetry/test-utils": "*",
50
- "@opentelemetry/web-utils": "*"
53
+ "@opentelemetry/sdk-logs": "^0.213.0"
51
54
  },
52
55
  "publishConfig": {
53
56
  "access": "public"
@@ -1 +0,0 @@
1
- {"version":3,"file":"getElementCSSSelector.js","names":[],"sources":["../../../../web-utils/dist/getElementCSSSelector.js"],"sourcesContent":["//#region src/getElementCSSSelector.ts\n/**\n* Generates the CSS selector of a given element in the DOM tree.\n*\n* @example #main > div:nth-child(2) > button.submit\n* @example #unique-id\n*/\nconst getElementCSSSelector = (element, { useIdForTargetElement = false, useIdForAncestors = false } = {}) => {\n\tif (element.nodeType === Node.DOCUMENT_NODE) return \"\";\n\tconst htmlElement = element;\n\tconst nodeValue = getNodeSelector(htmlElement, useIdForTargetElement || useIdForAncestors);\n\tif (nodeValue.startsWith(\"#\")) return nodeValue;\n\tconst parent = htmlElement.parentElement;\n\tconst parentSelector = parent ? getElementCSSSelector(parent, {\n\t\tuseIdForAncestors,\n\t\tuseIdForTargetElement: false\n\t}) : \"\";\n\treturn parentSelector ? `${parentSelector} > ${nodeValue}` : nodeValue;\n};\nconst getNodeSelector = (element, useElementId = false) => {\n\tif (element.nodeType !== Node.ELEMENT_NODE) return \"\";\n\tconst htmlElement = element;\n\tconst id = htmlElement.getAttribute(\"id\");\n\tif (useElementId && id) {\n\t\tif (htmlElement.ownerDocument.querySelectorAll(`#${CSS.escape(id)}`).length === 1) return `#${CSS.escape(id)}`;\n\t}\n\tlet selector = getFullClassSelector(htmlElement);\n\tconst index = getNthChild(htmlElement);\n\tif (index > 0) selector += `:nth-child(${index})`;\n\treturn selector;\n};\nconst getNthChild = (element) => {\n\tif (!element.parentElement) return 0;\n\tconst selector = getFullClassSelector(element);\n\tconst siblings = Array.from(element.parentElement.children).filter((sibling) => getFullClassSelector(sibling) === selector);\n\tif (siblings.length > 1) return siblings.indexOf(element) + 1;\n\treturn 0;\n};\nconst getFullClassSelector = (element) => element.localName + (element.classList.length > 0 ? Array.from(element.classList).map((cls) => `.${CSS.escape(cls)}`).join(\"\") : \"\");\n//#endregion\nexport { getElementCSSSelector };\n\n//# sourceMappingURL=getElementCSSSelector.js.map"],"mappings":";;;;;;;AAOA,MAAM,yBAAyB,SAAS,EAAE,wBAAwB,OAAO,oBAAoB,UAAU,EAAE,KAAK;AAC7G,KAAI,QAAQ,aAAa,KAAK,cAAe,QAAO;CACpD,MAAM,cAAc;CACpB,MAAM,YAAY,gBAAgB,aAAa,yBAAyB,kBAAkB;AAC1F,KAAI,UAAU,WAAW,IAAI,CAAE,QAAO;CACtC,MAAM,SAAS,YAAY;CAC3B,MAAM,iBAAiB,SAAS,sBAAsB,QAAQ;EAC7D;EACA,uBAAuB;EACvB,CAAC,GAAG;AACL,QAAO,iBAAiB,GAAG,eAAe,KAAK,cAAc;;AAE9D,MAAM,mBAAmB,SAAS,eAAe,UAAU;AAC1D,KAAI,QAAQ,aAAa,KAAK,aAAc,QAAO;CACnD,MAAM,cAAc;CACpB,MAAM,KAAK,YAAY,aAAa,KAAK;AACzC,KAAI,gBAAgB;MACf,YAAY,cAAc,iBAAiB,IAAI,IAAI,OAAO,GAAG,GAAG,CAAC,WAAW,EAAG,QAAO,IAAI,IAAI,OAAO,GAAG;;CAE7G,IAAI,WAAW,qBAAqB,YAAY;CAChD,MAAM,QAAQ,YAAY,YAAY;AACtC,KAAI,QAAQ,EAAG,aAAY,cAAc,MAAM;AAC/C,QAAO;;AAER,MAAM,eAAe,YAAY;AAChC,KAAI,CAAC,QAAQ,cAAe,QAAO;CACnC,MAAM,WAAW,qBAAqB,QAAQ;CAC9C,MAAM,WAAW,MAAM,KAAK,QAAQ,cAAc,SAAS,CAAC,QAAQ,YAAY,qBAAqB,QAAQ,KAAK,SAAS;AAC3H,KAAI,SAAS,SAAS,EAAG,QAAO,SAAS,QAAQ,QAAQ,GAAG;AAC5D,QAAO;;AAER,MAAM,wBAAwB,YAAY,QAAQ,aAAa,QAAQ,UAAU,SAAS,IAAI,MAAM,KAAK,QAAQ,UAAU,CAAC,KAAK,QAAQ,IAAI,IAAI,OAAO,IAAI,GAAG,CAAC,KAAK,GAAG,GAAG"}