@opentelemetry/sdk-trace-web 1.1.0 → 1.3.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 (48) hide show
  1. package/build/esm/StackContextManager.d.ts +50 -0
  2. package/build/esm/StackContextManager.js +148 -0
  3. package/build/esm/StackContextManager.js.map +1 -0
  4. package/build/esm/WebTracerProvider.d.ts +24 -0
  5. package/build/esm/WebTracerProvider.js +74 -0
  6. package/build/esm/WebTracerProvider.js.map +1 -0
  7. package/build/esm/enums/PerformanceTimingNames.d.ts +25 -0
  8. package/build/esm/enums/PerformanceTimingNames.js +41 -0
  9. package/build/esm/enums/PerformanceTimingNames.js.map +1 -0
  10. package/build/esm/index.d.ts +6 -0
  11. package/build/esm/index.js +21 -0
  12. package/build/esm/index.js.map +1 -0
  13. package/build/esm/types.d.ts +46 -0
  14. package/build/esm/types.js +17 -0
  15. package/build/esm/types.js.map +1 -0
  16. package/build/esm/utils.d.ts +81 -0
  17. package/build/esm/utils.js +315 -0
  18. package/build/esm/utils.js.map +1 -0
  19. package/build/esm/version.d.ts +2 -0
  20. package/build/esm/version.js +18 -0
  21. package/build/esm/version.js.map +1 -0
  22. package/build/esnext/StackContextManager.d.ts +50 -0
  23. package/build/esnext/StackContextManager.js +111 -0
  24. package/build/esnext/StackContextManager.js.map +1 -0
  25. package/build/esnext/WebTracerProvider.d.ts +24 -0
  26. package/build/esnext/WebTracerProvider.js +53 -0
  27. package/build/esnext/WebTracerProvider.js.map +1 -0
  28. package/build/esnext/enums/PerformanceTimingNames.d.ts +25 -0
  29. package/build/esnext/enums/PerformanceTimingNames.js +41 -0
  30. package/build/esnext/enums/PerformanceTimingNames.js.map +1 -0
  31. package/build/esnext/index.d.ts +6 -0
  32. package/build/esnext/index.js +21 -0
  33. package/build/esnext/index.js.map +1 -0
  34. package/build/esnext/types.d.ts +46 -0
  35. package/build/esnext/types.js +17 -0
  36. package/build/esnext/types.js.map +1 -0
  37. package/build/esnext/utils.d.ts +81 -0
  38. package/build/esnext/utils.js +312 -0
  39. package/build/esnext/utils.js.map +1 -0
  40. package/build/esnext/version.d.ts +2 -0
  41. package/build/esnext/version.js +18 -0
  42. package/build/esnext/version.js.map +1 -0
  43. package/build/src/utils.js +1 -1
  44. package/build/src/utils.js.map +1 -1
  45. package/build/src/version.d.ts +1 -1
  46. package/build/src/version.js +1 -1
  47. package/build/src/version.js.map +1 -1
  48. package/package.json +15 -13
@@ -0,0 +1,315 @@
1
+ /*
2
+ * Copyright The OpenTelemetry Authors
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { PerformanceTimingNames as PTN } from './enums/PerformanceTimingNames';
17
+ import { hrTimeToNanoseconds, timeInputToHrTime, urlMatches, } from '@opentelemetry/core';
18
+ import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
19
+ // Used to normalize relative URLs
20
+ var urlNormalizingAnchor;
21
+ function getUrlNormalizingAnchor() {
22
+ if (!urlNormalizingAnchor) {
23
+ urlNormalizingAnchor = document.createElement('a');
24
+ }
25
+ return urlNormalizingAnchor;
26
+ }
27
+ /**
28
+ * Helper function to be able to use enum as typed key in type and in interface when using forEach
29
+ * @param obj
30
+ * @param key
31
+ */
32
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
33
+ export function hasKey(obj, key) {
34
+ return key in obj;
35
+ }
36
+ /**
37
+ * Helper function for starting an event on span based on {@link PerformanceEntries}
38
+ * @param span
39
+ * @param performanceName name of performance entry for time start
40
+ * @param entries
41
+ */
42
+ export function addSpanNetworkEvent(span, performanceName, entries) {
43
+ if (hasKey(entries, performanceName) &&
44
+ typeof entries[performanceName] === 'number') {
45
+ span.addEvent(performanceName, entries[performanceName]);
46
+ return span;
47
+ }
48
+ return undefined;
49
+ }
50
+ /**
51
+ * Helper function for adding network events
52
+ * @param span
53
+ * @param resource
54
+ */
55
+ export function addSpanNetworkEvents(span, resource) {
56
+ addSpanNetworkEvent(span, PTN.FETCH_START, resource);
57
+ addSpanNetworkEvent(span, PTN.DOMAIN_LOOKUP_START, resource);
58
+ addSpanNetworkEvent(span, PTN.DOMAIN_LOOKUP_END, resource);
59
+ addSpanNetworkEvent(span, PTN.CONNECT_START, resource);
60
+ addSpanNetworkEvent(span, PTN.SECURE_CONNECTION_START, resource);
61
+ addSpanNetworkEvent(span, PTN.CONNECT_END, resource);
62
+ addSpanNetworkEvent(span, PTN.REQUEST_START, resource);
63
+ addSpanNetworkEvent(span, PTN.RESPONSE_START, resource);
64
+ addSpanNetworkEvent(span, PTN.RESPONSE_END, resource);
65
+ var encodedLength = resource[PTN.ENCODED_BODY_SIZE];
66
+ if (encodedLength !== undefined) {
67
+ span.setAttribute(SemanticAttributes.HTTP_RESPONSE_CONTENT_LENGTH, encodedLength);
68
+ }
69
+ var decodedLength = resource[PTN.DECODED_BODY_SIZE];
70
+ // Spec: Not set if transport encoding not used (in which case encoded and decoded sizes match)
71
+ if (decodedLength !== undefined && encodedLength !== decodedLength) {
72
+ span.setAttribute(SemanticAttributes.HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED, decodedLength);
73
+ }
74
+ }
75
+ /**
76
+ * sort resources by startTime
77
+ * @param filteredResources
78
+ */
79
+ export function sortResources(filteredResources) {
80
+ return filteredResources.slice().sort(function (a, b) {
81
+ var valueA = a[PTN.FETCH_START];
82
+ var valueB = b[PTN.FETCH_START];
83
+ if (valueA > valueB) {
84
+ return 1;
85
+ }
86
+ else if (valueA < valueB) {
87
+ return -1;
88
+ }
89
+ return 0;
90
+ });
91
+ }
92
+ /**
93
+ * Get closest performance resource ignoring the resources that have been
94
+ * already used.
95
+ * @param spanUrl
96
+ * @param startTimeHR
97
+ * @param endTimeHR
98
+ * @param resources
99
+ * @param ignoredResources
100
+ * @param initiatorType
101
+ */
102
+ export function getResource(spanUrl, startTimeHR, endTimeHR, resources, ignoredResources, initiatorType) {
103
+ if (ignoredResources === void 0) { ignoredResources = new WeakSet(); }
104
+ // de-relativize the URL before usage (does no harm to absolute URLs)
105
+ var parsedSpanUrl = parseUrl(spanUrl);
106
+ spanUrl = parsedSpanUrl.toString();
107
+ var filteredResources = filterResourcesForSpan(spanUrl, startTimeHR, endTimeHR, resources, ignoredResources, initiatorType);
108
+ if (filteredResources.length === 0) {
109
+ return {
110
+ mainRequest: undefined,
111
+ };
112
+ }
113
+ if (filteredResources.length === 1) {
114
+ return {
115
+ mainRequest: filteredResources[0],
116
+ };
117
+ }
118
+ var sorted = sortResources(filteredResources);
119
+ if (parsedSpanUrl.origin !== location.origin && sorted.length > 1) {
120
+ var corsPreFlightRequest = sorted[0];
121
+ var mainRequest = findMainRequest(sorted, corsPreFlightRequest[PTN.RESPONSE_END], endTimeHR);
122
+ var responseEnd = corsPreFlightRequest[PTN.RESPONSE_END];
123
+ var fetchStart = mainRequest[PTN.FETCH_START];
124
+ // no corsPreFlightRequest
125
+ if (fetchStart < responseEnd) {
126
+ mainRequest = corsPreFlightRequest;
127
+ corsPreFlightRequest = undefined;
128
+ }
129
+ return {
130
+ corsPreFlightRequest: corsPreFlightRequest,
131
+ mainRequest: mainRequest,
132
+ };
133
+ }
134
+ else {
135
+ return {
136
+ mainRequest: filteredResources[0],
137
+ };
138
+ }
139
+ }
140
+ /**
141
+ * Will find the main request skipping the cors pre flight requests
142
+ * @param resources
143
+ * @param corsPreFlightRequestEndTime
144
+ * @param spanEndTimeHR
145
+ */
146
+ function findMainRequest(resources, corsPreFlightRequestEndTime, spanEndTimeHR) {
147
+ var spanEndTime = hrTimeToNanoseconds(spanEndTimeHR);
148
+ var minTime = hrTimeToNanoseconds(timeInputToHrTime(corsPreFlightRequestEndTime));
149
+ var mainRequest = resources[1];
150
+ var bestGap;
151
+ var length = resources.length;
152
+ for (var i = 1; i < length; i++) {
153
+ var resource = resources[i];
154
+ var resourceStartTime = hrTimeToNanoseconds(timeInputToHrTime(resource[PTN.FETCH_START]));
155
+ var resourceEndTime = hrTimeToNanoseconds(timeInputToHrTime(resource[PTN.RESPONSE_END]));
156
+ var currentGap = spanEndTime - resourceEndTime;
157
+ if (resourceStartTime >= minTime && (!bestGap || currentGap < bestGap)) {
158
+ bestGap = currentGap;
159
+ mainRequest = resource;
160
+ }
161
+ }
162
+ return mainRequest;
163
+ }
164
+ /**
165
+ * Filter all resources that has started and finished according to span start time and end time.
166
+ * It will return the closest resource to a start time
167
+ * @param spanUrl
168
+ * @param startTimeHR
169
+ * @param endTimeHR
170
+ * @param resources
171
+ * @param ignoredResources
172
+ */
173
+ function filterResourcesForSpan(spanUrl, startTimeHR, endTimeHR, resources, ignoredResources, initiatorType) {
174
+ var startTime = hrTimeToNanoseconds(startTimeHR);
175
+ var endTime = hrTimeToNanoseconds(endTimeHR);
176
+ var filteredResources = resources.filter(function (resource) {
177
+ var resourceStartTime = hrTimeToNanoseconds(timeInputToHrTime(resource[PTN.FETCH_START]));
178
+ var resourceEndTime = hrTimeToNanoseconds(timeInputToHrTime(resource[PTN.RESPONSE_END]));
179
+ return (resource.initiatorType.toLowerCase() ===
180
+ (initiatorType || 'xmlhttprequest') &&
181
+ resource.name === spanUrl &&
182
+ resourceStartTime >= startTime &&
183
+ resourceEndTime <= endTime);
184
+ });
185
+ if (filteredResources.length > 0) {
186
+ filteredResources = filteredResources.filter(function (resource) {
187
+ return !ignoredResources.has(resource);
188
+ });
189
+ }
190
+ return filteredResources;
191
+ }
192
+ /**
193
+ * Parses url using URL constructor or fallback to anchor element.
194
+ * @param url
195
+ */
196
+ export function parseUrl(url) {
197
+ if (typeof URL === 'function') {
198
+ return new URL(url, location.href);
199
+ }
200
+ var element = getUrlNormalizingAnchor();
201
+ element.href = url;
202
+ return element;
203
+ }
204
+ /**
205
+ * Parses url using URL constructor or fallback to anchor element and serialize
206
+ * it to a string.
207
+ *
208
+ * Performs the steps described in https://html.spec.whatwg.org/multipage/urls-and-fetching.html#parse-a-url
209
+ *
210
+ * @param url
211
+ */
212
+ export function normalizeUrl(url) {
213
+ var urlLike = parseUrl(url);
214
+ return urlLike.href;
215
+ }
216
+ /**
217
+ * Get element XPath
218
+ * @param target - target element
219
+ * @param optimised - when id attribute of element is present the xpath can be
220
+ * simplified to contain id
221
+ */
222
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
223
+ export function getElementXPath(target, optimised) {
224
+ if (target.nodeType === Node.DOCUMENT_NODE) {
225
+ return '/';
226
+ }
227
+ var targetValue = getNodeValue(target, optimised);
228
+ if (optimised && targetValue.indexOf('@id') > 0) {
229
+ return targetValue;
230
+ }
231
+ var xpath = '';
232
+ if (target.parentNode) {
233
+ xpath += getElementXPath(target.parentNode, false);
234
+ }
235
+ xpath += targetValue;
236
+ return xpath;
237
+ }
238
+ /**
239
+ * get node index within the siblings
240
+ * @param target
241
+ */
242
+ function getNodeIndex(target) {
243
+ if (!target.parentNode) {
244
+ return 0;
245
+ }
246
+ var allowedTypes = [target.nodeType];
247
+ if (target.nodeType === Node.CDATA_SECTION_NODE) {
248
+ allowedTypes.push(Node.TEXT_NODE);
249
+ }
250
+ var elements = Array.from(target.parentNode.childNodes);
251
+ elements = elements.filter(function (element) {
252
+ var localName = element.localName;
253
+ return (allowedTypes.indexOf(element.nodeType) >= 0 &&
254
+ localName === target.localName);
255
+ });
256
+ if (elements.length >= 1) {
257
+ return elements.indexOf(target) + 1; // xpath starts from 1
258
+ }
259
+ // if there are no other similar child xpath doesn't need index
260
+ return 0;
261
+ }
262
+ /**
263
+ * get node value for xpath
264
+ * @param target
265
+ * @param optimised
266
+ */
267
+ function getNodeValue(target, optimised) {
268
+ var nodeType = target.nodeType;
269
+ var index = getNodeIndex(target);
270
+ var nodeValue = '';
271
+ if (nodeType === Node.ELEMENT_NODE) {
272
+ var id = target.getAttribute('id');
273
+ if (optimised && id) {
274
+ return "//*[@id=\"" + id + "\"]";
275
+ }
276
+ nodeValue = target.localName;
277
+ }
278
+ else if (nodeType === Node.TEXT_NODE ||
279
+ nodeType === Node.CDATA_SECTION_NODE) {
280
+ nodeValue = 'text()';
281
+ }
282
+ else if (nodeType === Node.COMMENT_NODE) {
283
+ nodeValue = 'comment()';
284
+ }
285
+ else {
286
+ return '';
287
+ }
288
+ // if index is 1 it can be omitted in xpath
289
+ if (nodeValue && index > 1) {
290
+ return "/" + nodeValue + "[" + index + "]";
291
+ }
292
+ return "/" + nodeValue;
293
+ }
294
+ /**
295
+ * Checks if trace headers should be propagated
296
+ * @param spanUrl
297
+ * @private
298
+ */
299
+ export function shouldPropagateTraceHeaders(spanUrl, propagateTraceHeaderCorsUrls) {
300
+ var propagateTraceHeaderUrls = propagateTraceHeaderCorsUrls || [];
301
+ if (typeof propagateTraceHeaderUrls === 'string' ||
302
+ propagateTraceHeaderUrls instanceof RegExp) {
303
+ propagateTraceHeaderUrls = [propagateTraceHeaderUrls];
304
+ }
305
+ var parsedSpanUrl = parseUrl(spanUrl);
306
+ if (parsedSpanUrl.origin === location.origin) {
307
+ return true;
308
+ }
309
+ else {
310
+ return propagateTraceHeaderUrls.some(function (propagateTraceHeaderUrl) {
311
+ return urlMatches(spanUrl, propagateTraceHeaderUrl);
312
+ });
313
+ }
314
+ }
315
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAOH,OAAO,EAAE,sBAAsB,IAAI,GAAG,EAAE,MAAM,gCAAgC,CAAC;AAE/E,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EACjB,UAAU,GACX,MAAM,qBAAqB,CAAC;AAC7B,OAAO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AAC,CAAC;IAExC,IAAI,aAAa,CAAC,MAAM,KAAK,QAAQ,CAAC,MAAM,EAAE;QAC5C,OAAO,IAAI,CAAC;KACb;SAAM;QACL,OAAO,wBAAwB,CAAC,IAAI,CAAC,UAAA,uBAAuB;YAC1D,OAAA,UAAU,CAAC,OAAO,EAAE,uBAAuB,CAAC;QAA5C,CAA4C,CAC7C,CAAC;KACH;AACH,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n PerformanceEntries,\n PerformanceResourceTimingInfo,\n PropagateTraceHeaderCorsUrls,\n} from './types';\nimport { PerformanceTimingNames as PTN } from './enums/PerformanceTimingNames';\nimport * as api from '@opentelemetry/api';\nimport {\n hrTimeToNanoseconds,\n timeInputToHrTime,\n urlMatches,\n} from '@opentelemetry/core';\nimport { SemanticAttributes } from '@opentelemetry/semantic-conventions';\n\n// Used to normalize relative URLs\nlet urlNormalizingAnchor: HTMLAnchorElement | undefined;\nfunction getUrlNormalizingAnchor(): HTMLAnchorElement {\n if (!urlNormalizingAnchor) {\n urlNormalizingAnchor = document.createElement('a');\n }\n\n return urlNormalizingAnchor;\n}\n\n/**\n * Helper function to be able to use enum as typed key in type and in interface when using forEach\n * @param obj\n * @param key\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function hasKey<O>(obj: O, key: keyof any): key is keyof O {\n return key in obj;\n}\n\n/**\n * Helper function for starting an event on span based on {@link PerformanceEntries}\n * @param span\n * @param performanceName name of performance entry for time start\n * @param entries\n */\nexport function addSpanNetworkEvent(\n span: api.Span,\n performanceName: string,\n entries: PerformanceEntries\n): api.Span | undefined {\n if (\n hasKey(entries, performanceName) &&\n typeof entries[performanceName] === 'number'\n ) {\n span.addEvent(performanceName, entries[performanceName]);\n return span;\n }\n return undefined;\n}\n\n/**\n * Helper function for adding network events\n * @param span\n * @param resource\n */\nexport function addSpanNetworkEvents(\n span: api.Span,\n resource: PerformanceEntries\n): void {\n addSpanNetworkEvent(span, PTN.FETCH_START, resource);\n addSpanNetworkEvent(span, PTN.DOMAIN_LOOKUP_START, resource);\n addSpanNetworkEvent(span, PTN.DOMAIN_LOOKUP_END, resource);\n addSpanNetworkEvent(span, PTN.CONNECT_START, resource);\n addSpanNetworkEvent(span, PTN.SECURE_CONNECTION_START, resource);\n addSpanNetworkEvent(span, PTN.CONNECT_END, resource);\n addSpanNetworkEvent(span, PTN.REQUEST_START, resource);\n addSpanNetworkEvent(span, PTN.RESPONSE_START, resource);\n addSpanNetworkEvent(span, PTN.RESPONSE_END, resource);\n const encodedLength = resource[PTN.ENCODED_BODY_SIZE];\n if (encodedLength !== undefined) {\n span.setAttribute(\n SemanticAttributes.HTTP_RESPONSE_CONTENT_LENGTH,\n encodedLength\n );\n }\n const decodedLength = resource[PTN.DECODED_BODY_SIZE];\n // Spec: Not set if transport encoding not used (in which case encoded and decoded sizes match)\n if (decodedLength !== undefined && encodedLength !== decodedLength) {\n span.setAttribute(\n SemanticAttributes.HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,\n decodedLength\n );\n }\n}\n\n/**\n * sort resources by startTime\n * @param filteredResources\n */\nexport function sortResources(filteredResources: PerformanceResourceTiming[]): PerformanceResourceTiming[] {\n return filteredResources.slice().sort((a, b) => {\n const valueA = a[PTN.FETCH_START];\n const valueB = b[PTN.FETCH_START];\n if (valueA > valueB) {\n return 1;\n } else if (valueA < valueB) {\n return -1;\n }\n return 0;\n });\n}\n\n/**\n * Get closest performance resource ignoring the resources that have been\n * already used.\n * @param spanUrl\n * @param startTimeHR\n * @param endTimeHR\n * @param resources\n * @param ignoredResources\n * @param initiatorType\n */\nexport function getResource(\n spanUrl: string,\n startTimeHR: api.HrTime,\n endTimeHR: api.HrTime,\n resources: PerformanceResourceTiming[],\n ignoredResources: WeakSet<PerformanceResourceTiming> = new WeakSet<PerformanceResourceTiming>(),\n initiatorType?: string\n): PerformanceResourceTimingInfo {\n // de-relativize the URL before usage (does no harm to absolute URLs)\n const parsedSpanUrl = parseUrl(spanUrl);\n spanUrl = parsedSpanUrl.toString();\n\n const filteredResources = filterResourcesForSpan(\n spanUrl,\n startTimeHR,\n endTimeHR,\n resources,\n ignoredResources,\n initiatorType\n );\n\n if (filteredResources.length === 0) {\n return {\n mainRequest: undefined,\n };\n }\n if (filteredResources.length === 1) {\n return {\n mainRequest: filteredResources[0],\n };\n }\n const sorted = sortResources(filteredResources);\n\n if (parsedSpanUrl.origin !== location.origin && sorted.length > 1) {\n let corsPreFlightRequest: PerformanceResourceTiming | undefined = sorted[0];\n let mainRequest: PerformanceResourceTiming = findMainRequest(\n sorted,\n corsPreFlightRequest[PTN.RESPONSE_END],\n endTimeHR\n );\n\n const responseEnd = corsPreFlightRequest[PTN.RESPONSE_END];\n const fetchStart = mainRequest[PTN.FETCH_START];\n\n // no corsPreFlightRequest\n if (fetchStart < responseEnd) {\n mainRequest = corsPreFlightRequest;\n corsPreFlightRequest = undefined;\n }\n\n return {\n corsPreFlightRequest,\n mainRequest,\n };\n } else {\n return {\n mainRequest: filteredResources[0],\n };\n }\n}\n\n/**\n * Will find the main request skipping the cors pre flight requests\n * @param resources\n * @param corsPreFlightRequestEndTime\n * @param spanEndTimeHR\n */\nfunction findMainRequest(\n resources: PerformanceResourceTiming[],\n corsPreFlightRequestEndTime: number,\n spanEndTimeHR: api.HrTime\n): PerformanceResourceTiming {\n const spanEndTime = hrTimeToNanoseconds(spanEndTimeHR);\n const minTime = hrTimeToNanoseconds(\n timeInputToHrTime(corsPreFlightRequestEndTime)\n );\n\n let mainRequest: PerformanceResourceTiming = resources[1];\n let bestGap;\n\n const length = resources.length;\n for (let i = 1; i < length; i++) {\n const resource = resources[i];\n const resourceStartTime = hrTimeToNanoseconds(\n timeInputToHrTime(resource[PTN.FETCH_START])\n );\n\n const resourceEndTime = hrTimeToNanoseconds(\n timeInputToHrTime(resource[PTN.RESPONSE_END])\n );\n\n const currentGap = spanEndTime - resourceEndTime;\n\n if (resourceStartTime >= minTime && (!bestGap || currentGap < bestGap)) {\n bestGap = currentGap;\n mainRequest = resource;\n }\n }\n return mainRequest;\n}\n\n/**\n * Filter all resources that has started and finished according to span start time and end time.\n * It will return the closest resource to a start time\n * @param spanUrl\n * @param startTimeHR\n * @param endTimeHR\n * @param resources\n * @param ignoredResources\n */\nfunction filterResourcesForSpan(\n spanUrl: string,\n startTimeHR: api.HrTime,\n endTimeHR: api.HrTime,\n resources: PerformanceResourceTiming[],\n ignoredResources: WeakSet<PerformanceResourceTiming>,\n initiatorType?: string\n) {\n const startTime = hrTimeToNanoseconds(startTimeHR);\n const endTime = hrTimeToNanoseconds(endTimeHR);\n let filteredResources = resources.filter(resource => {\n const resourceStartTime = hrTimeToNanoseconds(\n timeInputToHrTime(resource[PTN.FETCH_START])\n );\n const resourceEndTime = hrTimeToNanoseconds(\n timeInputToHrTime(resource[PTN.RESPONSE_END])\n );\n\n return (\n resource.initiatorType.toLowerCase() ===\n (initiatorType || 'xmlhttprequest') &&\n resource.name === spanUrl &&\n resourceStartTime >= startTime &&\n resourceEndTime <= endTime\n );\n });\n\n if (filteredResources.length > 0) {\n filteredResources = filteredResources.filter(resource => {\n return !ignoredResources.has(resource);\n });\n }\n\n return filteredResources;\n}\n\n/**\n * The URLLike interface represents an URL and HTMLAnchorElement compatible fields.\n */\nexport interface URLLike {\n hash: string;\n host: string;\n hostname: string;\n href: string;\n readonly origin: string;\n password: string;\n pathname: string;\n port: string;\n protocol: string;\n search: string;\n username: string;\n}\n\n/**\n * Parses url using URL constructor or fallback to anchor element.\n * @param url\n */\nexport function parseUrl(url: string): URLLike {\n if (typeof URL === 'function') {\n return new URL(url, location.href);\n }\n const element = getUrlNormalizingAnchor();\n element.href = url;\n return element;\n}\n\n/**\n * Parses url using URL constructor or fallback to anchor element and serialize\n * it to a string.\n *\n * Performs the steps described in https://html.spec.whatwg.org/multipage/urls-and-fetching.html#parse-a-url\n *\n * @param url\n */\nexport function normalizeUrl(url: string): string {\n const urlLike = parseUrl(url);\n return urlLike.href;\n}\n\n/**\n * Get element XPath\n * @param target - target element\n * @param optimised - when id attribute of element is present the xpath can be\n * simplified to contain id\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\nexport function getElementXPath(target: any, optimised?: boolean): string {\n if (target.nodeType === Node.DOCUMENT_NODE) {\n return '/';\n }\n const targetValue = getNodeValue(target, optimised);\n if (optimised && targetValue.indexOf('@id') > 0) {\n return targetValue;\n }\n let xpath = '';\n if (target.parentNode) {\n xpath += getElementXPath(target.parentNode, false);\n }\n xpath += targetValue;\n\n return xpath;\n}\n\n/**\n * get node index within the siblings\n * @param target\n */\nfunction getNodeIndex(target: HTMLElement): number {\n if (!target.parentNode) {\n return 0;\n }\n const allowedTypes = [target.nodeType];\n if (target.nodeType === Node.CDATA_SECTION_NODE) {\n allowedTypes.push(Node.TEXT_NODE);\n }\n let elements = Array.from(target.parentNode.childNodes);\n elements = elements.filter((element: Node) => {\n const localName = (element as HTMLElement).localName;\n return (\n allowedTypes.indexOf(element.nodeType) >= 0 &&\n localName === target.localName\n );\n });\n if (elements.length >= 1) {\n return elements.indexOf(target) + 1; // xpath starts from 1\n }\n // if there are no other similar child xpath doesn't need index\n return 0;\n}\n\n/**\n * get node value for xpath\n * @param target\n * @param optimised\n */\nfunction getNodeValue(target: HTMLElement, optimised?: boolean): string {\n const nodeType = target.nodeType;\n const index = getNodeIndex(target);\n let nodeValue = '';\n if (nodeType === Node.ELEMENT_NODE) {\n const id = target.getAttribute('id');\n if (optimised && id) {\n return `//*[@id=\"${id}\"]`;\n }\n nodeValue = target.localName;\n } else if (\n nodeType === Node.TEXT_NODE ||\n nodeType === Node.CDATA_SECTION_NODE\n ) {\n nodeValue = 'text()';\n } else if (nodeType === Node.COMMENT_NODE) {\n nodeValue = 'comment()';\n } else {\n return '';\n }\n // if index is 1 it can be omitted in xpath\n if (nodeValue && index > 1) {\n return `/${nodeValue}[${index}]`;\n }\n return `/${nodeValue}`;\n}\n\n/**\n * Checks if trace headers should be propagated\n * @param spanUrl\n * @private\n */\nexport function shouldPropagateTraceHeaders(\n spanUrl: string,\n propagateTraceHeaderCorsUrls?: PropagateTraceHeaderCorsUrls\n): boolean {\n let propagateTraceHeaderUrls = propagateTraceHeaderCorsUrls || [];\n if (\n typeof propagateTraceHeaderUrls === 'string' ||\n propagateTraceHeaderUrls instanceof RegExp\n ) {\n propagateTraceHeaderUrls = [propagateTraceHeaderUrls];\n }\n const parsedSpanUrl = parseUrl(spanUrl);\n\n if (parsedSpanUrl.origin === location.origin) {\n return true;\n } else {\n return propagateTraceHeaderUrls.some(propagateTraceHeaderUrl =>\n urlMatches(spanUrl, propagateTraceHeaderUrl)\n );\n }\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export declare const VERSION = "1.3.0";
2
+ //# sourceMappingURL=version.d.ts.map
@@ -0,0 +1,18 @@
1
+ /*
2
+ * Copyright The OpenTelemetry Authors
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ // this is autogenerated file, see scripts/version-update.js
17
+ export var VERSION = '1.3.0';
18
+ //# sourceMappingURL=version.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,4DAA4D;AAC5D,MAAM,CAAC,IAAM,OAAO,GAAG,OAAO,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.3.0';\n"]}
@@ -0,0 +1,50 @@
1
+ import { Context, ContextManager } from '@opentelemetry/api';
2
+ /**
3
+ * Stack Context Manager for managing the state in web
4
+ * it doesn't fully support the async calls though
5
+ */
6
+ export declare class StackContextManager implements ContextManager {
7
+ /**
8
+ * whether the context manager is enabled or not
9
+ */
10
+ private _enabled;
11
+ /**
12
+ * Keeps the reference to current context
13
+ */
14
+ _currentContext: Context;
15
+ /**
16
+ *
17
+ * @param context
18
+ * @param target Function to be executed within the context
19
+ */
20
+ private _bindFunction;
21
+ /**
22
+ * Returns the active context
23
+ */
24
+ active(): Context;
25
+ /**
26
+ * Binds a the certain context or the active one to the target function and then returns the target
27
+ * @param context A context (span) to be bind to target
28
+ * @param target a function or event emitter. When target or one of its callbacks is called,
29
+ * the provided context will be used as the active context for the duration of the call.
30
+ */
31
+ bind<T>(context: Context, target: T): T;
32
+ /**
33
+ * Disable the context manager (clears the current context)
34
+ */
35
+ disable(): this;
36
+ /**
37
+ * Enables the context manager and creates a default(root) context
38
+ */
39
+ enable(): this;
40
+ /**
41
+ * Calls the callback function [fn] with the provided [context]. If [context] is undefined then it will use the window.
42
+ * The context will be set as active
43
+ * @param context
44
+ * @param fn Callback function
45
+ * @param thisArg optional receiver to be used for calling fn
46
+ * @param args optional arguments forwarded to fn
47
+ */
48
+ with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(context: Context | null, fn: F, thisArg?: ThisParameterType<F>, ...args: A): ReturnType<F>;
49
+ }
50
+ //# sourceMappingURL=StackContextManager.d.ts.map
@@ -0,0 +1,111 @@
1
+ /*
2
+ * Copyright The OpenTelemetry Authors
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { ROOT_CONTEXT } from '@opentelemetry/api';
17
+ /**
18
+ * Stack Context Manager for managing the state in web
19
+ * it doesn't fully support the async calls though
20
+ */
21
+ export class StackContextManager {
22
+ constructor() {
23
+ /**
24
+ * whether the context manager is enabled or not
25
+ */
26
+ this._enabled = false;
27
+ /**
28
+ * Keeps the reference to current context
29
+ */
30
+ this._currentContext = ROOT_CONTEXT;
31
+ }
32
+ /**
33
+ *
34
+ * @param context
35
+ * @param target Function to be executed within the context
36
+ */
37
+ // eslint-disable-next-line @typescript-eslint/ban-types
38
+ _bindFunction(context = ROOT_CONTEXT, target) {
39
+ const manager = this;
40
+ const contextWrapper = function (...args) {
41
+ return manager.with(context, () => target.apply(this, args));
42
+ };
43
+ Object.defineProperty(contextWrapper, 'length', {
44
+ enumerable: false,
45
+ configurable: true,
46
+ writable: false,
47
+ value: target.length,
48
+ });
49
+ return contextWrapper;
50
+ }
51
+ /**
52
+ * Returns the active context
53
+ */
54
+ active() {
55
+ return this._currentContext;
56
+ }
57
+ /**
58
+ * Binds a the certain context or the active one to the target function and then returns the target
59
+ * @param context A context (span) to be bind to target
60
+ * @param target a function or event emitter. When target or one of its callbacks is called,
61
+ * the provided context will be used as the active context for the duration of the call.
62
+ */
63
+ bind(context, target) {
64
+ // if no specific context to propagate is given, we use the current one
65
+ if (context === undefined) {
66
+ context = this.active();
67
+ }
68
+ if (typeof target === 'function') {
69
+ return this._bindFunction(context, target);
70
+ }
71
+ return target;
72
+ }
73
+ /**
74
+ * Disable the context manager (clears the current context)
75
+ */
76
+ disable() {
77
+ this._currentContext = ROOT_CONTEXT;
78
+ this._enabled = false;
79
+ return this;
80
+ }
81
+ /**
82
+ * Enables the context manager and creates a default(root) context
83
+ */
84
+ enable() {
85
+ if (this._enabled) {
86
+ return this;
87
+ }
88
+ this._enabled = true;
89
+ this._currentContext = ROOT_CONTEXT;
90
+ return this;
91
+ }
92
+ /**
93
+ * Calls the callback function [fn] with the provided [context]. If [context] is undefined then it will use the window.
94
+ * The context will be set as active
95
+ * @param context
96
+ * @param fn Callback function
97
+ * @param thisArg optional receiver to be used for calling fn
98
+ * @param args optional arguments forwarded to fn
99
+ */
100
+ with(context, fn, thisArg, ...args) {
101
+ const previousContext = this._currentContext;
102
+ this._currentContext = context || ROOT_CONTEXT;
103
+ try {
104
+ return fn.call(thisArg, ...args);
105
+ }
106
+ finally {
107
+ this._currentContext = previousContext;
108
+ }
109
+ }
110
+ }
111
+ //# sourceMappingURL=StackContextManager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"StackContextManager.js","sourceRoot":"","sources":["../../src/StackContextManager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAA2B,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAE3E;;;GAGG;AACH,MAAM,OAAO,mBAAmB;IAAhC;QACE;;WAEG;QACK,aAAQ,GAAG,KAAK,CAAC;QAEzB;;WAEG;QACI,oBAAe,GAAG,YAAY,CAAC;IA6FxC,CAAC;IA3FC;;;;OAIG;IACH,wDAAwD;IAChD,aAAa,CACnB,OAAO,GAAG,YAA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,EAAK,EACL,OAA8B,EAC9B,GAAG,IAAO;QAEV,MAAM,eAAe,GAAG,IAAI,CAAC,eAAe,CAAC;QAC7C,IAAI,CAAC,eAAe,GAAG,OAAO,IAAI,YAAY,CAAC;QAE/C,IAAI;YACF,OAAO,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,CAAC;SAClC;gBAAS;YACR,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;SACxC;IACH,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, ContextManager, ROOT_CONTEXT } from '@opentelemetry/api';\n\n/**\n * Stack Context Manager for managing the state in web\n * it doesn't fully support the async calls though\n */\nexport class StackContextManager implements ContextManager {\n /**\n * whether the context manager is enabled or not\n */\n private _enabled = false;\n\n /**\n * Keeps the reference to current context\n */\n public _currentContext = ROOT_CONTEXT;\n\n /**\n *\n * @param context\n * @param target Function to be executed within the context\n */\n // eslint-disable-next-line @typescript-eslint/ban-types\n private _bindFunction<T extends Function>(\n context = ROOT_CONTEXT,\n target: T\n ): T {\n const manager = this;\n const contextWrapper = function (this: unknown, ...args: unknown[]) {\n return manager.with(context, () => target.apply(this, args));\n };\n Object.defineProperty(contextWrapper, 'length', {\n enumerable: false,\n configurable: true,\n writable: false,\n value: target.length,\n });\n return (contextWrapper as unknown) as T;\n }\n\n /**\n * Returns the active context\n */\n active(): Context {\n return this._currentContext;\n }\n\n /**\n * Binds a the certain context or the active one to the target function and then returns the target\n * @param context A context (span) to be bind to target\n * @param target a function or event emitter. When target or one of its callbacks is called,\n * the provided context will be used as the active context for the duration of the call.\n */\n bind<T>(context: Context, target: T): T {\n // if no specific context to propagate is given, we use the current one\n if (context === undefined) {\n context = this.active();\n }\n if (typeof target === 'function') {\n return this._bindFunction(context, target);\n }\n return target;\n }\n\n /**\n * Disable the context manager (clears the current context)\n */\n disable(): this {\n this._currentContext = ROOT_CONTEXT;\n this._enabled = false;\n return this;\n }\n\n /**\n * Enables the context manager and creates a default(root) context\n */\n enable(): this {\n if (this._enabled) {\n return this;\n }\n this._enabled = true;\n this._currentContext = ROOT_CONTEXT;\n return this;\n }\n\n /**\n * Calls the callback function [fn] with the provided [context]. If [context] is undefined then it will use the window.\n * The context will be set as active\n * @param context\n * @param fn Callback function\n * @param thisArg optional receiver to be used for calling fn\n * @param args optional arguments forwarded to fn\n */\n with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n context: Context | null,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F> {\n const previousContext = this._currentContext;\n this._currentContext = context || ROOT_CONTEXT;\n\n try {\n return fn.call(thisArg, ...args);\n } finally {\n this._currentContext = previousContext;\n }\n }\n}\n"]}
@@ -0,0 +1,24 @@
1
+ import { BasicTracerProvider, SDKRegistrationConfig, TracerConfig } from '@opentelemetry/sdk-trace-base';
2
+ /**
3
+ * WebTracerConfig provides an interface for configuring a Web Tracer.
4
+ */
5
+ export declare type WebTracerConfig = TracerConfig;
6
+ /**
7
+ * This class represents a web tracer with {@link StackContextManager}
8
+ */
9
+ export declare class WebTracerProvider extends BasicTracerProvider {
10
+ /**
11
+ * Constructs a new Tracer instance.
12
+ * @param config Web Tracer config
13
+ */
14
+ constructor(config?: WebTracerConfig);
15
+ /**
16
+ * Register this TracerProvider for use with the OpenTelemetry API.
17
+ * Undefined values may be replaced with defaults, and
18
+ * null values will be skipped.
19
+ *
20
+ * @param config Configuration object for SDK registration
21
+ */
22
+ register(config?: SDKRegistrationConfig): void;
23
+ }
24
+ //# sourceMappingURL=WebTracerProvider.d.ts.map
@@ -0,0 +1,53 @@
1
+ /*
2
+ * Copyright The OpenTelemetry Authors
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * https://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { BasicTracerProvider, } from '@opentelemetry/sdk-trace-base';
17
+ import { StackContextManager } from './StackContextManager';
18
+ /**
19
+ * This class represents a web tracer with {@link StackContextManager}
20
+ */
21
+ export class WebTracerProvider extends BasicTracerProvider {
22
+ /**
23
+ * Constructs a new Tracer instance.
24
+ * @param config Web Tracer config
25
+ */
26
+ constructor(config = {}) {
27
+ super(config);
28
+ if (config.contextManager) {
29
+ throw ('contextManager should be defined in register method not in' +
30
+ ' constructor');
31
+ }
32
+ if (config.propagator) {
33
+ throw 'propagator should be defined in register method not in constructor';
34
+ }
35
+ }
36
+ /**
37
+ * Register this TracerProvider for use with the OpenTelemetry API.
38
+ * Undefined values may be replaced with defaults, and
39
+ * null values will be skipped.
40
+ *
41
+ * @param config Configuration object for SDK registration
42
+ */
43
+ register(config = {}) {
44
+ if (config.contextManager === undefined) {
45
+ config.contextManager = new StackContextManager();
46
+ }
47
+ if (config.contextManager) {
48
+ config.contextManager.enable();
49
+ }
50
+ super.register(config);
51
+ }
52
+ }
53
+ //# sourceMappingURL=WebTracerProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WebTracerProvider.js","sourceRoot":"","sources":["../../src/WebTracerProvider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EACL,mBAAmB,GAGpB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAO5D;;GAEG;AACH,MAAM,OAAO,iBAAkB,SAAQ,mBAAmB;IACxD;;;OAGG;IACH,YAAY,SAA0B,EAAE;QACtC,KAAK,CAAC,MAAM,CAAC,CAAC;QAEd,IAAK,MAAgC,CAAC,cAAc,EAAE;YACpD,MAAM,CACJ,4DAA4D;gBAC5D,cAAc,CACf,CAAC;SACH;QACD,IAAK,MAAgC,CAAC,UAAU,EAAE;YAChD,MAAM,oEAAoE,CAAC;SAC5E;IACH,CAAC;IAED;;;;;;OAMG;IACM,QAAQ,CAAC,SAAgC,EAAE;QAClD,IAAI,MAAM,CAAC,cAAc,KAAK,SAAS,EAAE;YACvC,MAAM,CAAC,cAAc,GAAG,IAAI,mBAAmB,EAAE,CAAC;SACnD;QACD,IAAI,MAAM,CAAC,cAAc,EAAE;YACzB,MAAM,CAAC,cAAc,CAAC,MAAM,EAAE,CAAC;SAChC;QAED,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IACzB,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BasicTracerProvider,\n SDKRegistrationConfig,\n TracerConfig,\n} from '@opentelemetry/sdk-trace-base';\nimport { StackContextManager } from './StackContextManager';\n\n/**\n * WebTracerConfig provides an interface for configuring a Web Tracer.\n */\nexport type WebTracerConfig = TracerConfig;\n\n/**\n * This class represents a web tracer with {@link StackContextManager}\n */\nexport class WebTracerProvider extends BasicTracerProvider {\n /**\n * Constructs a new Tracer instance.\n * @param config Web Tracer config\n */\n constructor(config: WebTracerConfig = {}) {\n super(config);\n\n if ((config as SDKRegistrationConfig).contextManager) {\n throw (\n 'contextManager should be defined in register method not in' +\n ' constructor'\n );\n }\n if ((config as SDKRegistrationConfig).propagator) {\n throw 'propagator should be defined in register method not in constructor';\n }\n }\n\n /**\n * Register this TracerProvider for use with the OpenTelemetry API.\n * Undefined values may be replaced with defaults, and\n * null values will be skipped.\n *\n * @param config Configuration object for SDK registration\n */\n override register(config: SDKRegistrationConfig = {}): void {\n if (config.contextManager === undefined) {\n config.contextManager = new StackContextManager();\n }\n if (config.contextManager) {\n config.contextManager.enable();\n }\n\n super.register(config);\n }\n}\n"]}