@opentelemetry/instrumentation-xml-http-request 0.27.0 → 0.28.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/README.md CHANGED
@@ -1,8 +1,6 @@
1
1
  # OpenTelemetry XMLHttpRequest Instrumentation for web
2
2
 
3
3
  [![NPM Published Version][npm-img]][npm-url]
4
- [![dependencies][dependencies-image]][dependencies-url]
5
- [![devDependencies][devDependencies-image]][devDependencies-url]
6
4
  [![Apache License][license-image]][license-image]
7
5
 
8
6
  This module provides auto instrumentation for web using XMLHttpRequest .
@@ -82,9 +80,5 @@ Apache 2.0 - See [LICENSE][license-url] for more information.
82
80
  [discussions-url]: https://github.com/open-telemetry/opentelemetry-js/discussions
83
81
  [license-url]: https://github.com/open-telemetry/opentelemetry-js/blob/main/LICENSE
84
82
  [license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat
85
- [dependencies-image]: https://status.david-dm.org/gh/open-telemetry/opentelemetry-js.svg?path=packages%2Fopentelemetry-instrumentation-xml-http-request
86
- [dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-instrumentation-xml-http-request
87
- [devDependencies-image]: https://status.david-dm.org/gh/open-telemetry/opentelemetry-js.svg?path=packages%2Fopentelemetry-instrumentation-xml-http-request&type=dev
88
- [devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-instrumentation-xml-http-request&type=dev
89
83
  [npm-url]: https://www.npmjs.com/package/@opentelemetry/instrumentation-xml-http-request
90
84
  [npm-img]: https://badge.fury.io/js/%40opentelemetry%2Finstrumentation-xml-http-request.svg
@@ -6,7 +6,7 @@ export declare type OpenFunction = (method: string, url: string, async?: boolean
6
6
  /**
7
7
  * method "send" from XMLHttpRequest
8
8
  */
9
- export declare type SendFunction = (body?: SendBody) => void;
9
+ export declare type SendFunction = typeof XMLHttpRequest.prototype.send;
10
10
  export declare type SendBody = string | Document | Blob | ArrayBufferView | ArrayBuffer | FormData | URLSearchParams | ReadableStream<Uint8Array> | null;
11
11
  /**
12
12
  * interface to store information in weak map about spans, resources and
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","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 * as api from '@opentelemetry/api';\n\n/**\n * method \"open\" from XMLHttpRequest\n */\nexport type OpenFunction = (\n method: string,\n url: string,\n async?: boolean,\n user?: string | null,\n pass?: string | null\n) => void;\n\n/**\n * method \"send\" from XMLHttpRequest\n */\nexport type SendFunction = (body?: SendBody) => void;\n\nexport type SendBody =\n | string\n | Document\n | Blob\n | ArrayBufferView\n | ArrayBuffer\n | FormData\n // eslint-disable-next-line node/no-unsupported-features/node-builtins\n | URLSearchParams\n | ReadableStream<Uint8Array>\n | null;\n\n/**\n * interface to store information in weak map about spans, resources and\n * callbacks\n */\nexport interface XhrMem {\n status?: number;\n statusText?: string;\n // span assigned to xhr\n span: api.Span;\n // span url - not available on types.Span\n spanUrl?: string;\n // startTime of send function - used to filter cors preflight requests\n sendStartTime?: api.HrTime;\n // resources created between send and end plus some additional timeout\n createdResources?: {\n observer: PerformanceObserver;\n entries: PerformanceResourceTiming[];\n };\n // callback to remove events from xhr once the span ends\n callbackToRemoveEvents?: Function;\n}\n\nexport type PropagateTraceHeaderCorsUrl = string | RegExp;\n\nexport type PropagateTraceHeaderCorsUrls =\n | PropagateTraceHeaderCorsUrl\n | PropagateTraceHeaderCorsUrl[];\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","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 * as api from '@opentelemetry/api';\n\n/**\n * method \"open\" from XMLHttpRequest\n */\nexport type OpenFunction = (\n method: string,\n url: string,\n async?: boolean,\n user?: string | null,\n pass?: string | null\n) => void;\n\n/**\n * method \"send\" from XMLHttpRequest\n */\nexport type SendFunction = typeof XMLHttpRequest.prototype.send;\n\nexport type SendBody =\n | string\n | Document\n | Blob\n | ArrayBufferView\n | ArrayBuffer\n | FormData\n // eslint-disable-next-line node/no-unsupported-features/node-builtins\n | URLSearchParams\n | ReadableStream<Uint8Array>\n | null;\n\n/**\n * interface to store information in weak map about spans, resources and\n * callbacks\n */\nexport interface XhrMem {\n status?: number;\n statusText?: string;\n // span assigned to xhr\n span: api.Span;\n // span url - not available on types.Span\n spanUrl?: string;\n // startTime of send function - used to filter cors preflight requests\n sendStartTime?: api.HrTime;\n // resources created between send and end plus some additional timeout\n createdResources?: {\n observer: PerformanceObserver;\n entries: PerformanceResourceTiming[];\n };\n // callback to remove events from xhr once the span ends\n callbackToRemoveEvents?: Function;\n}\n\nexport type PropagateTraceHeaderCorsUrl = string | RegExp;\n\nexport type PropagateTraceHeaderCorsUrls =\n | PropagateTraceHeaderCorsUrl\n | PropagateTraceHeaderCorsUrl[];\n"]}
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "0.27.0";
1
+ export declare const VERSION = "0.28.0";
2
2
  //# sourceMappingURL=version.d.ts.map
@@ -14,5 +14,5 @@
14
14
  * limitations under the License.
15
15
  */
16
16
  // this is autogenerated file, see scripts/version-update.js
17
- export var VERSION = '0.27.0';
17
+ export var VERSION = '0.28.0';
18
18
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,4DAA4D;AAC5D,MAAM,CAAC,IAAM,OAAO,GAAG,QAAQ,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 = '0.27.0';\n"]}
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,4DAA4D;AAC5D,MAAM,CAAC,IAAM,OAAO,GAAG,QAAQ,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 = '0.28.0';\n"]}
@@ -41,7 +41,7 @@ export declare class XMLHttpRequestInstrumentation extends InstrumentationBase<X
41
41
  /**
42
42
  * Adds custom headers to XMLHttpRequest
43
43
  * @param xhr
44
- * @param span
44
+ * @param spanUrl
45
45
  * @private
46
46
  */
47
47
  private _addHeaders;
package/build/esm/xhr.js CHANGED
@@ -32,10 +32,15 @@ import * as api from '@opentelemetry/api';
32
32
  import { isWrapped, InstrumentationBase, safeExecuteInTheMiddle, } from '@opentelemetry/instrumentation';
33
33
  import { hrTime, isUrlIgnored, otperformance } from '@opentelemetry/core';
34
34
  import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
35
- import { addSpanNetworkEvents, getResource, parseUrl, PerformanceTimingNames as PTN, shouldPropagateTraceHeaders, getUrlNormalizingAnchor } from '@opentelemetry/sdk-trace-web';
35
+ import { addSpanNetworkEvents, getResource, PerformanceTimingNames as PTN, shouldPropagateTraceHeaders } from '@opentelemetry/sdk-trace-web';
36
36
  import { EventNames } from './enums/EventNames';
37
37
  import { VERSION } from './version';
38
38
  import { AttributeNames } from './enums/AttributeNames';
39
+ function parseUrl(url) {
40
+ var element = document.createElement('a');
41
+ element.href = url;
42
+ return element;
43
+ }
39
44
  // how long to wait for observer to collect information about resources
40
45
  // this is needed as event "load" is called before observer
41
46
  // hard to say how long it should really wait, seems like 300ms is
@@ -63,11 +68,12 @@ var XMLHttpRequestInstrumentation = /** @class */ (function (_super) {
63
68
  /**
64
69
  * Adds custom headers to XMLHttpRequest
65
70
  * @param xhr
66
- * @param span
71
+ * @param spanUrl
67
72
  * @private
68
73
  */
69
74
  XMLHttpRequestInstrumentation.prototype._addHeaders = function (xhr, spanUrl) {
70
- if (!shouldPropagateTraceHeaders(spanUrl, this._getConfig().propagateTraceHeaderCorsUrls)) {
75
+ var url = parseUrl(spanUrl).href;
76
+ if (!shouldPropagateTraceHeaders(url, this._getConfig().propagateTraceHeaderCorsUrls)) {
71
77
  var headers_1 = {};
72
78
  api.propagation.inject(api.context.active(), headers_1);
73
79
  if (Object.keys(headers_1).length > 0) {
@@ -143,18 +149,17 @@ var XMLHttpRequestInstrumentation = /** @class */ (function (_super) {
143
149
  XMLHttpRequestInstrumentation.prototype._addResourceObserver = function (xhr, spanUrl) {
144
150
  var xhrMem = this._xhrMem.get(xhr);
145
151
  if (!xhrMem ||
146
- typeof window.PerformanceObserver === 'undefined' ||
147
- typeof window.PerformanceResourceTiming === 'undefined') {
152
+ PerformanceObserver == null ||
153
+ PerformanceResourceTiming == null) {
148
154
  return;
149
155
  }
150
156
  xhrMem.createdResources = {
151
157
  observer: new PerformanceObserver(function (list) {
152
158
  var entries = list.getEntries();
153
- var urlNormalizingAnchor = getUrlNormalizingAnchor();
154
- urlNormalizingAnchor.href = spanUrl;
159
+ var parsedUrl = parseUrl(spanUrl);
155
160
  entries.forEach(function (entry) {
156
161
  if (entry.initiatorType === 'xmlhttprequest' &&
157
- entry.name === urlNormalizingAnchor.href) {
162
+ entry.name === parsedUrl.href) {
158
163
  if (xhrMem.createdResources) {
159
164
  xhrMem.createdResources.entries.push(entry);
160
165
  }
@@ -196,7 +201,7 @@ var XMLHttpRequestInstrumentation = /** @class */ (function (_super) {
196
201
  // ts thinks this is the perf_hooks module, but it is the browser performance api
197
202
  resources = otperformance.getEntriesByType('resource');
198
203
  }
199
- var resource = getResource(spanUrl, startTime, endTime, resources, this._usedResources);
204
+ var resource = getResource(parseUrl(spanUrl).href, startTime, endTime, resources, this._usedResources);
200
205
  if (resource.mainRequest) {
201
206
  var mainRequest = resource.mainRequest;
202
207
  this._markResourceAsUsed(mainRequest);
@@ -1 +1 @@
1
- {"version":3,"file":"xhr.js","sourceRoot":"","sources":["../../src/xhr.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;AAEH,OAAO,KAAK,GAAG,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EACL,SAAS,EACT,mBAAmB,EAEnB,sBAAsB,GACvB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,aAAa,EAA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I,CAAC,OAAO,CAAC,cAAc,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;QAC/C,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;QAE/C,IAAI,CAAC,WAAW,GAAG,CAAC,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,IAAI,OAAO,EAA0B,CAAC;QACrD,IAAI,CAAC,cAAc,GAAG,IAAI,OAAO,EAA6B,CAAC;IACjE,CAAC;IACH,oCAAC;AAAD,CAAC,AAhdD,CAAmD,mBAAmB,GAgdrE","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 * as api from '@opentelemetry/api';\nimport {\n isWrapped,\n InstrumentationBase,\n InstrumentationConfig,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport { hrTime, isUrlIgnored, otperformance } from '@opentelemetry/core';\nimport { SemanticAttributes } from '@opentelemetry/semantic-conventions';\nimport {\n addSpanNetworkEvents,\n getResource,\n parseUrl,\n PerformanceTimingNames as PTN,\n shouldPropagateTraceHeaders,\n getUrlNormalizingAnchor\n} from '@opentelemetry/sdk-trace-web';\nimport { EventNames } from './enums/EventNames';\nimport {\n OpenFunction,\n PropagateTraceHeaderCorsUrls,\n SendFunction,\n XhrMem,\n} from './types';\nimport { VERSION } from './version';\nimport { AttributeNames } from './enums/AttributeNames';\n\n// how long to wait for observer to collect information about resources\n// this is needed as event \"load\" is called before observer\n// hard to say how long it should really wait, seems like 300ms is\n// safe enough\nconst OBSERVER_WAIT_TIME_MS = 300;\n\nexport type XHRCustomAttributeFunction = (\n span: api.Span,\n xhr: XMLHttpRequest\n) => void;\n\n/**\n * XMLHttpRequest config\n */\nexport interface XMLHttpRequestInstrumentationConfig\n extends InstrumentationConfig {\n /**\n * The number of timing resources is limited, after the limit\n * (chrome 250, safari 150) the information is not collected anymore.\n * The only way to prevent that is to regularly clean the resources\n * whenever it is possible. This is needed only when PerformanceObserver\n * is not available\n */\n clearTimingResources?: boolean;\n /** URLs which should include trace headers when origin doesn't match */\n propagateTraceHeaderCorsUrls?: PropagateTraceHeaderCorsUrls;\n /**\n * URLs that partially match any regex in ignoreUrls will not be traced.\n * In addition, URLs that are _exact matches_ of strings in ignoreUrls will\n * also not be traced.\n */\n ignoreUrls?: Array<string | RegExp>;\n /** Function for adding custom attributes on the span */\n applyCustomAttributesOnSpan?: XHRCustomAttributeFunction;\n}\n\n/**\n * This class represents a XMLHttpRequest plugin for auto instrumentation\n */\nexport class XMLHttpRequestInstrumentation extends InstrumentationBase<XMLHttpRequest> {\n readonly component: string = 'xml-http-request';\n readonly version: string = VERSION;\n moduleName = this.component;\n\n private _tasksCount = 0;\n private _xhrMem = new WeakMap<XMLHttpRequest, XhrMem>();\n private _usedResources = new WeakSet<PerformanceResourceTiming>();\n\n constructor(config?: XMLHttpRequestInstrumentationConfig) {\n super(\n '@opentelemetry/instrumentation-xml-http-request',\n VERSION,\n config\n );\n }\n\n init() {}\n\n private _getConfig(): XMLHttpRequestInstrumentationConfig {\n return this._config;\n }\n\n /**\n * Adds custom headers to XMLHttpRequest\n * @param xhr\n * @param span\n * @private\n */\n private _addHeaders(xhr: XMLHttpRequest, spanUrl: string) {\n if (\n !shouldPropagateTraceHeaders(\n spanUrl,\n this._getConfig().propagateTraceHeaderCorsUrls\n )\n ) {\n const headers: Partial<Record<string, unknown>> = {};\n api.propagation.inject(api.context.active(), headers);\n if (Object.keys(headers).length > 0) {\n this._diag.debug('headers inject skipped due to CORS policy');\n }\n return;\n }\n const headers: { [key: string]: unknown } = {};\n api.propagation.inject(api.context.active(), headers);\n Object.keys(headers).forEach(key => {\n xhr.setRequestHeader(key, String(headers[key]));\n });\n }\n\n /**\n * Add cors pre flight child span\n * @param span\n * @param corsPreFlightRequest\n * @private\n */\n private _addChildSpan(\n span: api.Span,\n corsPreFlightRequest: PerformanceResourceTiming\n ): void {\n api.context.with(api.trace.setSpan(api.context.active(), span), () => {\n const childSpan = this.tracer.startSpan('CORS Preflight', {\n startTime: corsPreFlightRequest[PTN.FETCH_START],\n });\n addSpanNetworkEvents(childSpan, corsPreFlightRequest);\n childSpan.end(corsPreFlightRequest[PTN.RESPONSE_END]);\n });\n }\n\n /**\n * Add attributes when span is going to end\n * @param span\n * @param xhr\n * @param spanUrl\n * @private\n */\n _addFinalSpanAttributes(span: api.Span, xhrMem: XhrMem, spanUrl?: string) {\n if (typeof spanUrl === 'string') {\n const parsedUrl = parseUrl(spanUrl);\n if (xhrMem.status !== undefined) {\n span.setAttribute(SemanticAttributes.HTTP_STATUS_CODE, xhrMem.status);\n }\n if (xhrMem.statusText !== undefined) {\n span.setAttribute(AttributeNames.HTTP_STATUS_TEXT, xhrMem.statusText);\n }\n span.setAttribute(SemanticAttributes.HTTP_HOST, parsedUrl.host);\n span.setAttribute(\n SemanticAttributes.HTTP_SCHEME,\n parsedUrl.protocol.replace(':', '')\n );\n\n // @TODO do we want to collect this or it will be collected earlier once only or\n // maybe when parent span is not available ?\n span.setAttribute(\n SemanticAttributes.HTTP_USER_AGENT,\n navigator.userAgent\n );\n }\n }\n\n private _applyAttributesAfterXHR(span: api.Span, xhr: XMLHttpRequest) {\n const applyCustomAttributesOnSpan = this._getConfig()\n .applyCustomAttributesOnSpan;\n if (typeof applyCustomAttributesOnSpan === 'function') {\n safeExecuteInTheMiddle(\n () => applyCustomAttributesOnSpan(span, xhr),\n error => {\n if (!error) {\n return;\n }\n\n this._diag.error('applyCustomAttributesOnSpan', error);\n },\n true\n );\n }\n }\n\n /**\n * will collect information about all resources created\n * between \"send\" and \"end\" with additional waiting for main resource\n * @param xhr\n * @param spanUrl\n * @private\n */\n private _addResourceObserver(xhr: XMLHttpRequest, spanUrl: string) {\n const xhrMem = this._xhrMem.get(xhr);\n if (\n !xhrMem ||\n typeof window.PerformanceObserver === 'undefined' ||\n typeof window.PerformanceResourceTiming === 'undefined'\n ) {\n return;\n }\n xhrMem.createdResources = {\n observer: new PerformanceObserver(list => {\n const entries = list.getEntries() as PerformanceResourceTiming[];\n const urlNormalizingAnchor = getUrlNormalizingAnchor();\n urlNormalizingAnchor.href = spanUrl;\n\n entries.forEach(entry => {\n if (\n entry.initiatorType === 'xmlhttprequest' &&\n entry.name === urlNormalizingAnchor.href\n ) {\n if (xhrMem.createdResources) {\n xhrMem.createdResources.entries.push(entry);\n }\n }\n });\n }),\n entries: [],\n };\n xhrMem.createdResources.observer.observe({\n entryTypes: ['resource'],\n });\n }\n\n /**\n * Clears the resource timings and all resources assigned with spans\n * when {@link XMLHttpRequestInstrumentationConfig.clearTimingResources} is\n * set to true (default false)\n * @private\n */\n private _clearResources() {\n if (this._tasksCount === 0 && this._getConfig().clearTimingResources) {\n ((otperformance as unknown) as Performance).clearResourceTimings();\n this._xhrMem = new WeakMap<XMLHttpRequest, XhrMem>();\n this._usedResources = new WeakSet<PerformanceResourceTiming>();\n }\n }\n\n /**\n * Finds appropriate resource and add network events to the span\n * @param span\n */\n private _findResourceAndAddNetworkEvents(\n xhrMem: XhrMem,\n span: api.Span,\n spanUrl?: string,\n startTime?: api.HrTime,\n endTime?: api.HrTime\n ): void {\n if (!spanUrl || !startTime || !endTime || !xhrMem.createdResources) {\n return;\n }\n\n let resources: PerformanceResourceTiming[] =\n xhrMem.createdResources.entries;\n\n if (!resources || !resources.length) {\n // fallback - either Observer is not available or it took longer\n // then OBSERVER_WAIT_TIME_MS and observer didn't collect enough\n // information\n // ts thinks this is the perf_hooks module, but it is the browser performance api\n resources = ((otperformance as unknown) as Performance).getEntriesByType(\n 'resource'\n ) as PerformanceResourceTiming[];\n }\n\n const resource = getResource(\n spanUrl,\n startTime,\n endTime,\n resources,\n this._usedResources\n );\n\n if (resource.mainRequest) {\n const mainRequest = resource.mainRequest;\n this._markResourceAsUsed(mainRequest);\n\n const corsPreFlightRequest = resource.corsPreFlightRequest;\n if (corsPreFlightRequest) {\n this._addChildSpan(span, corsPreFlightRequest);\n this._markResourceAsUsed(corsPreFlightRequest);\n }\n addSpanNetworkEvents(span, mainRequest);\n }\n }\n\n /**\n * Removes the previous information about span.\n * This might happened when the same xhr is used again.\n * @param xhr\n * @private\n */\n private _cleanPreviousSpanInformation(xhr: XMLHttpRequest) {\n const xhrMem = this._xhrMem.get(xhr);\n if (xhrMem) {\n const callbackToRemoveEvents = xhrMem.callbackToRemoveEvents;\n if (callbackToRemoveEvents) {\n callbackToRemoveEvents();\n }\n this._xhrMem.delete(xhr);\n }\n }\n\n /**\n * Creates a new span when method \"open\" is called\n * @param xhr\n * @param url\n * @param method\n * @private\n */\n private _createSpan(\n xhr: XMLHttpRequest,\n url: string,\n method: string\n ): api.Span | undefined {\n if (isUrlIgnored(url, this._getConfig().ignoreUrls)) {\n this._diag.debug('ignoring span as url matches ignored url');\n return;\n }\n const spanName = `HTTP ${method.toUpperCase()}`;\n\n const currentSpan = this.tracer.startSpan(spanName, {\n kind: api.SpanKind.CLIENT,\n attributes: {\n [SemanticAttributes.HTTP_METHOD]: method,\n [SemanticAttributes.HTTP_URL]: url,\n },\n });\n\n currentSpan.addEvent(EventNames.METHOD_OPEN);\n\n this._cleanPreviousSpanInformation(xhr);\n\n this._xhrMem.set(xhr, {\n span: currentSpan,\n spanUrl: url,\n });\n\n return currentSpan;\n }\n\n /**\n * Marks certain [resource]{@link PerformanceResourceTiming} when information\n * from this is used to add events to span.\n * This is done to avoid reusing the same resource again for next span\n * @param resource\n * @private\n */\n private _markResourceAsUsed(resource: PerformanceResourceTiming) {\n this._usedResources.add(resource);\n }\n\n /**\n * Patches the method open\n * @private\n */\n protected _patchOpen() {\n return (original: OpenFunction): OpenFunction => {\n const plugin = this;\n return function patchOpen(this: XMLHttpRequest, ...args): void {\n const method: string = args[0];\n const url: string = args[1];\n plugin._createSpan(this, url, method);\n\n return original.apply(this, args);\n };\n };\n }\n\n /**\n * Patches the method send\n * @private\n */\n protected _patchSend() {\n const plugin = this;\n\n function endSpanTimeout(\n eventName: string,\n xhrMem: XhrMem,\n endTime: api.HrTime\n ) {\n const callbackToRemoveEvents = xhrMem.callbackToRemoveEvents;\n\n if (typeof callbackToRemoveEvents === 'function') {\n callbackToRemoveEvents();\n }\n\n const { span, spanUrl, sendStartTime } = xhrMem;\n\n if (span) {\n plugin._findResourceAndAddNetworkEvents(\n xhrMem,\n span,\n spanUrl,\n sendStartTime,\n endTime\n );\n span.addEvent(eventName, endTime);\n plugin._addFinalSpanAttributes(span, xhrMem, spanUrl);\n span.end(endTime);\n plugin._tasksCount--;\n }\n plugin._clearResources();\n }\n\n function endSpan(eventName: string, xhr: XMLHttpRequest) {\n const xhrMem = plugin._xhrMem.get(xhr);\n if (!xhrMem) {\n return;\n }\n xhrMem.status = xhr.status;\n xhrMem.statusText = xhr.statusText;\n plugin._xhrMem.delete(xhr);\n\n if (xhrMem.span) {\n plugin._applyAttributesAfterXHR(xhrMem.span, xhr);\n }\n const endTime = hrTime();\n\n // the timeout is needed as observer doesn't have yet information\n // when event \"load\" is called. Also the time may differ depends on\n // browser and speed of computer\n setTimeout(() => {\n endSpanTimeout(eventName, xhrMem, endTime);\n }, OBSERVER_WAIT_TIME_MS);\n }\n\n function onError(this: XMLHttpRequest) {\n endSpan(EventNames.EVENT_ERROR, this);\n }\n\n function onAbort(this: XMLHttpRequest) {\n endSpan(EventNames.EVENT_ABORT, this);\n }\n\n function onTimeout(this: XMLHttpRequest) {\n endSpan(EventNames.EVENT_TIMEOUT, this);\n }\n\n function onLoad(this: XMLHttpRequest) {\n if (this.status < 299) {\n endSpan(EventNames.EVENT_LOAD, this);\n } else {\n endSpan(EventNames.EVENT_ERROR, this);\n }\n }\n\n function unregister(xhr: XMLHttpRequest) {\n xhr.removeEventListener('abort', onAbort);\n xhr.removeEventListener('error', onError);\n xhr.removeEventListener('load', onLoad);\n xhr.removeEventListener('timeout', onTimeout);\n const xhrMem = plugin._xhrMem.get(xhr);\n if (xhrMem) {\n xhrMem.callbackToRemoveEvents = undefined;\n }\n }\n\n return (original: SendFunction): SendFunction => {\n return function patchSend(this: XMLHttpRequest, ...args): void {\n const xhrMem = plugin._xhrMem.get(this);\n if (!xhrMem) {\n return original.apply(this, args);\n }\n const currentSpan = xhrMem.span;\n const spanUrl = xhrMem.spanUrl;\n\n if (currentSpan && spanUrl) {\n api.context.with(\n api.trace.setSpan(api.context.active(), currentSpan),\n () => {\n plugin._tasksCount++;\n xhrMem.sendStartTime = hrTime();\n currentSpan.addEvent(EventNames.METHOD_SEND);\n\n this.addEventListener('abort', onAbort);\n this.addEventListener('error', onError);\n this.addEventListener('load', onLoad);\n this.addEventListener('timeout', onTimeout);\n\n xhrMem.callbackToRemoveEvents = () => {\n unregister(this);\n if (xhrMem.createdResources) {\n xhrMem.createdResources.observer.disconnect();\n }\n };\n plugin._addHeaders(this, spanUrl);\n plugin._addResourceObserver(this, spanUrl);\n }\n );\n }\n return original.apply(this, args);\n };\n };\n }\n\n /**\n * implements enable function\n */\n override enable() {\n this._diag.debug('applying patch to', this.moduleName, this.version);\n\n if (isWrapped(XMLHttpRequest.prototype.open)) {\n this._unwrap(XMLHttpRequest.prototype, 'open');\n this._diag.debug('removing previous patch from method open');\n }\n\n if (isWrapped(XMLHttpRequest.prototype.send)) {\n this._unwrap(XMLHttpRequest.prototype, 'send');\n this._diag.debug('removing previous patch from method send');\n }\n\n this._wrap(XMLHttpRequest.prototype, 'open', this._patchOpen());\n this._wrap(XMLHttpRequest.prototype, 'send', this._patchSend());\n }\n\n /**\n * implements disable function\n */\n override disable() {\n this._diag.debug('removing patch from', this.moduleName, this.version);\n\n this._unwrap(XMLHttpRequest.prototype, 'open');\n this._unwrap(XMLHttpRequest.prototype, 'send');\n\n this._tasksCount = 0;\n this._xhrMem = new WeakMap<XMLHttpRequest, XhrMem>();\n this._usedResources = new WeakSet<PerformanceResourceTiming>();\n }\n}\n"]}
1
+ {"version":3,"file":"xhr.js","sourceRoot":"","sources":["../../src/xhr.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;AAEH,OAAO,KAAK,GAAG,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EACL,SAAS,EACT,mBAAmB,EAEnB,sBAAsB,GACvB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAC1E,OAAO,EAAE,kBAAkB,EAAE,MAAM,qCAAqC,CAAC;AACzE,OAAO,EACL,oBAAoB,EACpB,WAAW,EACX,sBAAsB,IAAI,GAAG,EAC7B,2BAA2B,EAE5B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAOhD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAExD,SAAS,QAAQ,CAAC,GAAW;IAC3B,IAAM,OAAO,GAAG,QAAQ,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;IAC5C,OAAO,CAAC,IAAI,GAAG,GAAG,CAAC;IACnB,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,uEAAuE;AACvE,2DAA2D;AAC3D,kEAAkE;AAClE,cAAc;AACd,IAAM,qBAAqB,GAAG,GAAG,CAAC;AAgClC;;GAEG;AACH;IAAmD,iDAAmC;IASpF,uCAAY,MAA4C;QAAxD,YACE,kBACE,iDAAiD,EACjD,OAAO,EACP,MAAM,CACP,SACF;QAdQ,eAAS,GAAW,kBAAkB,CAAC;QACvC,aAAO,GAAW,OAAO,CAAC;QACnC,gBAAU,GAAG,KAAI,CAAC,SAAS,CAAC;QAEpB,iBAAW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AAI,SAAS,CAAC,cAAc,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE;YAC5C,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;YAC/C,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,0CAA0C,CAAC,CAAC;SAC9D;QAED,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;QAChE,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;IAClE,CAAC;IAED;;OAEG;IACM,+CAAO,GAAhB;QACE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,qBAAqB,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QAEvE,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;QAC/C,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;QAE/C,IAAI,CAAC,WAAW,GAAG,CAAC,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,IAAI,OAAO,EAA0B,CAAC;QACrD,IAAI,CAAC,cAAc,GAAG,IAAI,OAAO,EAA6B,CAAC;IACjE,CAAC;IACH,oCAAC;AAAD,CAAC,AAhdD,CAAmD,mBAAmB,GAgdrE","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 * as api from '@opentelemetry/api';\nimport {\n isWrapped,\n InstrumentationBase,\n InstrumentationConfig,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport { hrTime, isUrlIgnored, otperformance } from '@opentelemetry/core';\nimport { SemanticAttributes } from '@opentelemetry/semantic-conventions';\nimport {\n addSpanNetworkEvents,\n getResource,\n PerformanceTimingNames as PTN,\n shouldPropagateTraceHeaders,\n URLLike\n} from '@opentelemetry/sdk-trace-web';\nimport { EventNames } from './enums/EventNames';\nimport {\n OpenFunction,\n PropagateTraceHeaderCorsUrls,\n SendFunction,\n XhrMem,\n} from './types';\nimport { VERSION } from './version';\nimport { AttributeNames } from './enums/AttributeNames';\n\nfunction parseUrl(url: string): URLLike {\n const element = document.createElement('a');\n element.href = url;\n return element;\n}\n\n// how long to wait for observer to collect information about resources\n// this is needed as event \"load\" is called before observer\n// hard to say how long it should really wait, seems like 300ms is\n// safe enough\nconst OBSERVER_WAIT_TIME_MS = 300;\n\nexport type XHRCustomAttributeFunction = (\n span: api.Span,\n xhr: XMLHttpRequest\n) => void;\n\n/**\n * XMLHttpRequest config\n */\nexport interface XMLHttpRequestInstrumentationConfig\n extends InstrumentationConfig {\n /**\n * The number of timing resources is limited, after the limit\n * (chrome 250, safari 150) the information is not collected anymore.\n * The only way to prevent that is to regularly clean the resources\n * whenever it is possible. This is needed only when PerformanceObserver\n * is not available\n */\n clearTimingResources?: boolean;\n /** URLs which should include trace headers when origin doesn't match */\n propagateTraceHeaderCorsUrls?: PropagateTraceHeaderCorsUrls;\n /**\n * URLs that partially match any regex in ignoreUrls will not be traced.\n * In addition, URLs that are _exact matches_ of strings in ignoreUrls will\n * also not be traced.\n */\n ignoreUrls?: Array<string | RegExp>;\n /** Function for adding custom attributes on the span */\n applyCustomAttributesOnSpan?: XHRCustomAttributeFunction;\n}\n\n/**\n * This class represents a XMLHttpRequest plugin for auto instrumentation\n */\nexport class XMLHttpRequestInstrumentation extends InstrumentationBase<XMLHttpRequest> {\n readonly component: string = 'xml-http-request';\n readonly version: string = VERSION;\n moduleName = this.component;\n\n private _tasksCount = 0;\n private _xhrMem = new WeakMap<XMLHttpRequest, XhrMem>();\n private _usedResources = new WeakSet<PerformanceResourceTiming>();\n\n constructor(config?: XMLHttpRequestInstrumentationConfig) {\n super(\n '@opentelemetry/instrumentation-xml-http-request',\n VERSION,\n config\n );\n }\n\n init() {}\n\n private _getConfig(): XMLHttpRequestInstrumentationConfig {\n return this._config;\n }\n\n /**\n * Adds custom headers to XMLHttpRequest\n * @param xhr\n * @param spanUrl\n * @private\n */\n private _addHeaders(xhr: XMLHttpRequest, spanUrl: string) {\n const url = parseUrl(spanUrl).href;\n if (\n !shouldPropagateTraceHeaders(\n url,\n this._getConfig().propagateTraceHeaderCorsUrls\n )\n ) {\n const headers: Partial<Record<string, unknown>> = {};\n api.propagation.inject(api.context.active(), headers);\n if (Object.keys(headers).length > 0) {\n this._diag.debug('headers inject skipped due to CORS policy');\n }\n return;\n }\n const headers: { [key: string]: unknown } = {};\n api.propagation.inject(api.context.active(), headers);\n Object.keys(headers).forEach(key => {\n xhr.setRequestHeader(key, String(headers[key]));\n });\n }\n\n /**\n * Add cors pre flight child span\n * @param span\n * @param corsPreFlightRequest\n * @private\n */\n private _addChildSpan(\n span: api.Span,\n corsPreFlightRequest: PerformanceResourceTiming\n ): void {\n api.context.with(api.trace.setSpan(api.context.active(), span), () => {\n const childSpan = this.tracer.startSpan('CORS Preflight', {\n startTime: corsPreFlightRequest[PTN.FETCH_START],\n });\n addSpanNetworkEvents(childSpan, corsPreFlightRequest);\n childSpan.end(corsPreFlightRequest[PTN.RESPONSE_END]);\n });\n }\n\n /**\n * Add attributes when span is going to end\n * @param span\n * @param xhr\n * @param spanUrl\n * @private\n */\n _addFinalSpanAttributes(span: api.Span, xhrMem: XhrMem, spanUrl?: string) {\n if (typeof spanUrl === 'string') {\n const parsedUrl = parseUrl(spanUrl);\n if (xhrMem.status !== undefined) {\n span.setAttribute(SemanticAttributes.HTTP_STATUS_CODE, xhrMem.status);\n }\n if (xhrMem.statusText !== undefined) {\n span.setAttribute(AttributeNames.HTTP_STATUS_TEXT, xhrMem.statusText);\n }\n span.setAttribute(SemanticAttributes.HTTP_HOST, parsedUrl.host);\n span.setAttribute(\n SemanticAttributes.HTTP_SCHEME,\n parsedUrl.protocol.replace(':', '')\n );\n\n // @TODO do we want to collect this or it will be collected earlier once only or\n // maybe when parent span is not available ?\n span.setAttribute(\n SemanticAttributes.HTTP_USER_AGENT,\n navigator.userAgent\n );\n }\n }\n\n private _applyAttributesAfterXHR(span: api.Span, xhr: XMLHttpRequest) {\n const applyCustomAttributesOnSpan = this._getConfig()\n .applyCustomAttributesOnSpan;\n if (typeof applyCustomAttributesOnSpan === 'function') {\n safeExecuteInTheMiddle(\n () => applyCustomAttributesOnSpan(span, xhr),\n error => {\n if (!error) {\n return;\n }\n\n this._diag.error('applyCustomAttributesOnSpan', error);\n },\n true\n );\n }\n }\n\n /**\n * will collect information about all resources created\n * between \"send\" and \"end\" with additional waiting for main resource\n * @param xhr\n * @param spanUrl\n * @private\n */\n private _addResourceObserver(xhr: XMLHttpRequest, spanUrl: string) {\n const xhrMem = this._xhrMem.get(xhr);\n if (\n !xhrMem ||\n PerformanceObserver == null ||\n PerformanceResourceTiming == null\n ) {\n return;\n }\n xhrMem.createdResources = {\n observer: new PerformanceObserver(list => {\n const entries = list.getEntries() as PerformanceResourceTiming[];\n const parsedUrl = parseUrl(spanUrl);\n\n entries.forEach(entry => {\n if (\n entry.initiatorType === 'xmlhttprequest' &&\n entry.name === parsedUrl.href\n ) {\n if (xhrMem.createdResources) {\n xhrMem.createdResources.entries.push(entry);\n }\n }\n });\n }),\n entries: [],\n };\n xhrMem.createdResources.observer.observe({\n entryTypes: ['resource'],\n });\n }\n\n /**\n * Clears the resource timings and all resources assigned with spans\n * when {@link XMLHttpRequestInstrumentationConfig.clearTimingResources} is\n * set to true (default false)\n * @private\n */\n private _clearResources() {\n if (this._tasksCount === 0 && this._getConfig().clearTimingResources) {\n ((otperformance as unknown) as Performance).clearResourceTimings();\n this._xhrMem = new WeakMap<XMLHttpRequest, XhrMem>();\n this._usedResources = new WeakSet<PerformanceResourceTiming>();\n }\n }\n\n /**\n * Finds appropriate resource and add network events to the span\n * @param span\n */\n private _findResourceAndAddNetworkEvents(\n xhrMem: XhrMem,\n span: api.Span,\n spanUrl?: string,\n startTime?: api.HrTime,\n endTime?: api.HrTime\n ): void {\n if (!spanUrl || !startTime || !endTime || !xhrMem.createdResources) {\n return;\n }\n\n let resources: PerformanceResourceTiming[] =\n xhrMem.createdResources.entries;\n\n if (!resources || !resources.length) {\n // fallback - either Observer is not available or it took longer\n // then OBSERVER_WAIT_TIME_MS and observer didn't collect enough\n // information\n // ts thinks this is the perf_hooks module, but it is the browser performance api\n resources = ((otperformance as unknown) as Performance).getEntriesByType(\n 'resource'\n ) as PerformanceResourceTiming[];\n }\n\n const resource = getResource(\n parseUrl(spanUrl).href,\n startTime,\n endTime,\n resources,\n this._usedResources\n );\n\n if (resource.mainRequest) {\n const mainRequest = resource.mainRequest;\n this._markResourceAsUsed(mainRequest);\n\n const corsPreFlightRequest = resource.corsPreFlightRequest;\n if (corsPreFlightRequest) {\n this._addChildSpan(span, corsPreFlightRequest);\n this._markResourceAsUsed(corsPreFlightRequest);\n }\n addSpanNetworkEvents(span, mainRequest);\n }\n }\n\n /**\n * Removes the previous information about span.\n * This might happened when the same xhr is used again.\n * @param xhr\n * @private\n */\n private _cleanPreviousSpanInformation(xhr: XMLHttpRequest) {\n const xhrMem = this._xhrMem.get(xhr);\n if (xhrMem) {\n const callbackToRemoveEvents = xhrMem.callbackToRemoveEvents;\n if (callbackToRemoveEvents) {\n callbackToRemoveEvents();\n }\n this._xhrMem.delete(xhr);\n }\n }\n\n /**\n * Creates a new span when method \"open\" is called\n * @param xhr\n * @param url\n * @param method\n * @private\n */\n private _createSpan(\n xhr: XMLHttpRequest,\n url: string,\n method: string\n ): api.Span | undefined {\n if (isUrlIgnored(url, this._getConfig().ignoreUrls)) {\n this._diag.debug('ignoring span as url matches ignored url');\n return;\n }\n const spanName = `HTTP ${method.toUpperCase()}`;\n\n const currentSpan = this.tracer.startSpan(spanName, {\n kind: api.SpanKind.CLIENT,\n attributes: {\n [SemanticAttributes.HTTP_METHOD]: method,\n [SemanticAttributes.HTTP_URL]: url,\n },\n });\n\n currentSpan.addEvent(EventNames.METHOD_OPEN);\n\n this._cleanPreviousSpanInformation(xhr);\n\n this._xhrMem.set(xhr, {\n span: currentSpan,\n spanUrl: url,\n });\n\n return currentSpan;\n }\n\n /**\n * Marks certain [resource]{@link PerformanceResourceTiming} when information\n * from this is used to add events to span.\n * This is done to avoid reusing the same resource again for next span\n * @param resource\n * @private\n */\n private _markResourceAsUsed(resource: PerformanceResourceTiming) {\n this._usedResources.add(resource);\n }\n\n /**\n * Patches the method open\n * @private\n */\n protected _patchOpen() {\n return (original: OpenFunction): OpenFunction => {\n const plugin = this;\n return function patchOpen(this: XMLHttpRequest, ...args): void {\n const method: string = args[0];\n const url: string = args[1];\n plugin._createSpan(this, url, method);\n\n return original.apply(this, args);\n };\n };\n }\n\n /**\n * Patches the method send\n * @private\n */\n protected _patchSend() {\n const plugin = this;\n\n function endSpanTimeout(\n eventName: string,\n xhrMem: XhrMem,\n endTime: api.HrTime\n ) {\n const callbackToRemoveEvents = xhrMem.callbackToRemoveEvents;\n\n if (typeof callbackToRemoveEvents === 'function') {\n callbackToRemoveEvents();\n }\n\n const { span, spanUrl, sendStartTime } = xhrMem;\n\n if (span) {\n plugin._findResourceAndAddNetworkEvents(\n xhrMem,\n span,\n spanUrl,\n sendStartTime,\n endTime\n );\n span.addEvent(eventName, endTime);\n plugin._addFinalSpanAttributes(span, xhrMem, spanUrl);\n span.end(endTime);\n plugin._tasksCount--;\n }\n plugin._clearResources();\n }\n\n function endSpan(eventName: string, xhr: XMLHttpRequest) {\n const xhrMem = plugin._xhrMem.get(xhr);\n if (!xhrMem) {\n return;\n }\n xhrMem.status = xhr.status;\n xhrMem.statusText = xhr.statusText;\n plugin._xhrMem.delete(xhr);\n\n if (xhrMem.span) {\n plugin._applyAttributesAfterXHR(xhrMem.span, xhr);\n }\n const endTime = hrTime();\n\n // the timeout is needed as observer doesn't have yet information\n // when event \"load\" is called. Also the time may differ depends on\n // browser and speed of computer\n setTimeout(() => {\n endSpanTimeout(eventName, xhrMem, endTime);\n }, OBSERVER_WAIT_TIME_MS);\n }\n\n function onError(this: XMLHttpRequest) {\n endSpan(EventNames.EVENT_ERROR, this);\n }\n\n function onAbort(this: XMLHttpRequest) {\n endSpan(EventNames.EVENT_ABORT, this);\n }\n\n function onTimeout(this: XMLHttpRequest) {\n endSpan(EventNames.EVENT_TIMEOUT, this);\n }\n\n function onLoad(this: XMLHttpRequest) {\n if (this.status < 299) {\n endSpan(EventNames.EVENT_LOAD, this);\n } else {\n endSpan(EventNames.EVENT_ERROR, this);\n }\n }\n\n function unregister(xhr: XMLHttpRequest) {\n xhr.removeEventListener('abort', onAbort);\n xhr.removeEventListener('error', onError);\n xhr.removeEventListener('load', onLoad);\n xhr.removeEventListener('timeout', onTimeout);\n const xhrMem = plugin._xhrMem.get(xhr);\n if (xhrMem) {\n xhrMem.callbackToRemoveEvents = undefined;\n }\n }\n\n return (original: SendFunction): SendFunction => {\n return function patchSend(this: XMLHttpRequest, ...args): void {\n const xhrMem = plugin._xhrMem.get(this);\n if (!xhrMem) {\n return original.apply(this, args);\n }\n const currentSpan = xhrMem.span;\n const spanUrl = xhrMem.spanUrl;\n\n if (currentSpan && spanUrl) {\n api.context.with(\n api.trace.setSpan(api.context.active(), currentSpan),\n () => {\n plugin._tasksCount++;\n xhrMem.sendStartTime = hrTime();\n currentSpan.addEvent(EventNames.METHOD_SEND);\n\n this.addEventListener('abort', onAbort);\n this.addEventListener('error', onError);\n this.addEventListener('load', onLoad);\n this.addEventListener('timeout', onTimeout);\n\n xhrMem.callbackToRemoveEvents = () => {\n unregister(this);\n if (xhrMem.createdResources) {\n xhrMem.createdResources.observer.disconnect();\n }\n };\n plugin._addHeaders(this, spanUrl);\n plugin._addResourceObserver(this, spanUrl);\n }\n );\n }\n return original.apply(this, args);\n };\n };\n }\n\n /**\n * implements enable function\n */\n override enable() {\n this._diag.debug('applying patch to', this.moduleName, this.version);\n\n if (isWrapped(XMLHttpRequest.prototype.open)) {\n this._unwrap(XMLHttpRequest.prototype, 'open');\n this._diag.debug('removing previous patch from method open');\n }\n\n if (isWrapped(XMLHttpRequest.prototype.send)) {\n this._unwrap(XMLHttpRequest.prototype, 'send');\n this._diag.debug('removing previous patch from method send');\n }\n\n this._wrap(XMLHttpRequest.prototype, 'open', this._patchOpen());\n this._wrap(XMLHttpRequest.prototype, 'send', this._patchSend());\n }\n\n /**\n * implements disable function\n */\n override disable() {\n this._diag.debug('removing patch from', this.moduleName, this.version);\n\n this._unwrap(XMLHttpRequest.prototype, 'open');\n this._unwrap(XMLHttpRequest.prototype, 'send');\n\n this._tasksCount = 0;\n this._xhrMem = new WeakMap<XMLHttpRequest, XhrMem>();\n this._usedResources = new WeakSet<PerformanceResourceTiming>();\n }\n}\n"]}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/http.md
3
+ */
4
+ export declare enum AttributeNames {
5
+ HTTP_STATUS_TEXT = "http.status_text"
6
+ }
7
+ //# sourceMappingURL=AttributeNames.d.ts.map
@@ -0,0 +1,23 @@
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
+ /**
17
+ * https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/http.md
18
+ */
19
+ export var AttributeNames;
20
+ (function (AttributeNames) {
21
+ AttributeNames["HTTP_STATUS_TEXT"] = "http.status_text";
22
+ })(AttributeNames || (AttributeNames = {}));
23
+ //# sourceMappingURL=AttributeNames.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AttributeNames.js","sourceRoot":"","sources":["../../../src/enums/AttributeNames.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH;;GAEG;AACH,MAAM,CAAN,IAAY,cAEX;AAFD,WAAY,cAAc;IACxB,uDAAqC,CAAA;AACvC,CAAC,EAFW,cAAc,KAAd,cAAc,QAEzB","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/**\n * https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/http.md\n */\nexport enum AttributeNames {\n HTTP_STATUS_TEXT = 'http.status_text',\n}\n"]}
@@ -0,0 +1,9 @@
1
+ export declare enum EventNames {
2
+ METHOD_OPEN = "open",
3
+ METHOD_SEND = "send",
4
+ EVENT_ABORT = "abort",
5
+ EVENT_ERROR = "error",
6
+ EVENT_LOAD = "loaded",
7
+ EVENT_TIMEOUT = "timeout"
8
+ }
9
+ //# sourceMappingURL=EventNames.d.ts.map
@@ -0,0 +1,25 @@
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
+ export var EventNames;
17
+ (function (EventNames) {
18
+ EventNames["METHOD_OPEN"] = "open";
19
+ EventNames["METHOD_SEND"] = "send";
20
+ EventNames["EVENT_ABORT"] = "abort";
21
+ EventNames["EVENT_ERROR"] = "error";
22
+ EventNames["EVENT_LOAD"] = "loaded";
23
+ EventNames["EVENT_TIMEOUT"] = "timeout";
24
+ })(EventNames || (EventNames = {}));
25
+ //# sourceMappingURL=EventNames.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EventNames.js","sourceRoot":"","sources":["../../../src/enums/EventNames.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,MAAM,CAAN,IAAY,UAOX;AAPD,WAAY,UAAU;IACpB,kCAAoB,CAAA;IACpB,kCAAoB,CAAA;IACpB,mCAAqB,CAAA;IACrB,mCAAqB,CAAA;IACrB,mCAAqB,CAAA;IACrB,uCAAyB,CAAA;AAC3B,CAAC,EAPW,UAAU,KAAV,UAAU,QAOrB","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\nexport enum EventNames {\n METHOD_OPEN = 'open',\n METHOD_SEND = 'send',\n EVENT_ABORT = 'abort',\n EVENT_ERROR = 'error',\n EVENT_LOAD = 'loaded',\n EVENT_TIMEOUT = 'timeout',\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export * from './xhr';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,17 @@
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
+ export * from './xhr';
17
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,cAAc,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\nexport * from './xhr';\n"]}
@@ -0,0 +1,29 @@
1
+ import * as api from '@opentelemetry/api';
2
+ /**
3
+ * method "open" from XMLHttpRequest
4
+ */
5
+ export declare type OpenFunction = (method: string, url: string, async?: boolean, user?: string | null, pass?: string | null) => void;
6
+ /**
7
+ * method "send" from XMLHttpRequest
8
+ */
9
+ export declare type SendFunction = typeof XMLHttpRequest.prototype.send;
10
+ export declare type SendBody = string | Document | Blob | ArrayBufferView | ArrayBuffer | FormData | URLSearchParams | ReadableStream<Uint8Array> | null;
11
+ /**
12
+ * interface to store information in weak map about spans, resources and
13
+ * callbacks
14
+ */
15
+ export interface XhrMem {
16
+ status?: number;
17
+ statusText?: string;
18
+ span: api.Span;
19
+ spanUrl?: string;
20
+ sendStartTime?: api.HrTime;
21
+ createdResources?: {
22
+ observer: PerformanceObserver;
23
+ entries: PerformanceResourceTiming[];
24
+ };
25
+ callbackToRemoveEvents?: Function;
26
+ }
27
+ export declare type PropagateTraceHeaderCorsUrl = string | RegExp;
28
+ export declare type PropagateTraceHeaderCorsUrls = PropagateTraceHeaderCorsUrl | PropagateTraceHeaderCorsUrl[];
29
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,17 @@
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
+ export {};
17
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","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 * as api from '@opentelemetry/api';\n\n/**\n * method \"open\" from XMLHttpRequest\n */\nexport type OpenFunction = (\n method: string,\n url: string,\n async?: boolean,\n user?: string | null,\n pass?: string | null\n) => void;\n\n/**\n * method \"send\" from XMLHttpRequest\n */\nexport type SendFunction = typeof XMLHttpRequest.prototype.send;\n\nexport type SendBody =\n | string\n | Document\n | Blob\n | ArrayBufferView\n | ArrayBuffer\n | FormData\n // eslint-disable-next-line node/no-unsupported-features/node-builtins\n | URLSearchParams\n | ReadableStream<Uint8Array>\n | null;\n\n/**\n * interface to store information in weak map about spans, resources and\n * callbacks\n */\nexport interface XhrMem {\n status?: number;\n statusText?: string;\n // span assigned to xhr\n span: api.Span;\n // span url - not available on types.Span\n spanUrl?: string;\n // startTime of send function - used to filter cors preflight requests\n sendStartTime?: api.HrTime;\n // resources created between send and end plus some additional timeout\n createdResources?: {\n observer: PerformanceObserver;\n entries: PerformanceResourceTiming[];\n };\n // callback to remove events from xhr once the span ends\n callbackToRemoveEvents?: Function;\n}\n\nexport type PropagateTraceHeaderCorsUrl = string | RegExp;\n\nexport type PropagateTraceHeaderCorsUrls =\n | PropagateTraceHeaderCorsUrl\n | PropagateTraceHeaderCorsUrl[];\n"]}
@@ -0,0 +1,2 @@
1
+ export declare const VERSION = "0.28.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 const VERSION = '0.28.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,MAAM,OAAO,GAAG,QAAQ,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 = '0.28.0';\n"]}
@@ -0,0 +1,126 @@
1
+ import * as api from '@opentelemetry/api';
2
+ import { InstrumentationBase, InstrumentationConfig } from '@opentelemetry/instrumentation';
3
+ import { OpenFunction, PropagateTraceHeaderCorsUrls, SendFunction, XhrMem } from './types';
4
+ export declare type XHRCustomAttributeFunction = (span: api.Span, xhr: XMLHttpRequest) => void;
5
+ /**
6
+ * XMLHttpRequest config
7
+ */
8
+ export interface XMLHttpRequestInstrumentationConfig extends InstrumentationConfig {
9
+ /**
10
+ * The number of timing resources is limited, after the limit
11
+ * (chrome 250, safari 150) the information is not collected anymore.
12
+ * The only way to prevent that is to regularly clean the resources
13
+ * whenever it is possible. This is needed only when PerformanceObserver
14
+ * is not available
15
+ */
16
+ clearTimingResources?: boolean;
17
+ /** URLs which should include trace headers when origin doesn't match */
18
+ propagateTraceHeaderCorsUrls?: PropagateTraceHeaderCorsUrls;
19
+ /**
20
+ * URLs that partially match any regex in ignoreUrls will not be traced.
21
+ * In addition, URLs that are _exact matches_ of strings in ignoreUrls will
22
+ * also not be traced.
23
+ */
24
+ ignoreUrls?: Array<string | RegExp>;
25
+ /** Function for adding custom attributes on the span */
26
+ applyCustomAttributesOnSpan?: XHRCustomAttributeFunction;
27
+ }
28
+ /**
29
+ * This class represents a XMLHttpRequest plugin for auto instrumentation
30
+ */
31
+ export declare class XMLHttpRequestInstrumentation extends InstrumentationBase<XMLHttpRequest> {
32
+ readonly component: string;
33
+ readonly version: string;
34
+ moduleName: string;
35
+ private _tasksCount;
36
+ private _xhrMem;
37
+ private _usedResources;
38
+ constructor(config?: XMLHttpRequestInstrumentationConfig);
39
+ init(): void;
40
+ private _getConfig;
41
+ /**
42
+ * Adds custom headers to XMLHttpRequest
43
+ * @param xhr
44
+ * @param spanUrl
45
+ * @private
46
+ */
47
+ private _addHeaders;
48
+ /**
49
+ * Add cors pre flight child span
50
+ * @param span
51
+ * @param corsPreFlightRequest
52
+ * @private
53
+ */
54
+ private _addChildSpan;
55
+ /**
56
+ * Add attributes when span is going to end
57
+ * @param span
58
+ * @param xhr
59
+ * @param spanUrl
60
+ * @private
61
+ */
62
+ _addFinalSpanAttributes(span: api.Span, xhrMem: XhrMem, spanUrl?: string): void;
63
+ private _applyAttributesAfterXHR;
64
+ /**
65
+ * will collect information about all resources created
66
+ * between "send" and "end" with additional waiting for main resource
67
+ * @param xhr
68
+ * @param spanUrl
69
+ * @private
70
+ */
71
+ private _addResourceObserver;
72
+ /**
73
+ * Clears the resource timings and all resources assigned with spans
74
+ * when {@link XMLHttpRequestInstrumentationConfig.clearTimingResources} is
75
+ * set to true (default false)
76
+ * @private
77
+ */
78
+ private _clearResources;
79
+ /**
80
+ * Finds appropriate resource and add network events to the span
81
+ * @param span
82
+ */
83
+ private _findResourceAndAddNetworkEvents;
84
+ /**
85
+ * Removes the previous information about span.
86
+ * This might happened when the same xhr is used again.
87
+ * @param xhr
88
+ * @private
89
+ */
90
+ private _cleanPreviousSpanInformation;
91
+ /**
92
+ * Creates a new span when method "open" is called
93
+ * @param xhr
94
+ * @param url
95
+ * @param method
96
+ * @private
97
+ */
98
+ private _createSpan;
99
+ /**
100
+ * Marks certain [resource]{@link PerformanceResourceTiming} when information
101
+ * from this is used to add events to span.
102
+ * This is done to avoid reusing the same resource again for next span
103
+ * @param resource
104
+ * @private
105
+ */
106
+ private _markResourceAsUsed;
107
+ /**
108
+ * Patches the method open
109
+ * @private
110
+ */
111
+ protected _patchOpen(): (original: OpenFunction) => OpenFunction;
112
+ /**
113
+ * Patches the method send
114
+ * @private
115
+ */
116
+ protected _patchSend(): (original: SendFunction) => SendFunction;
117
+ /**
118
+ * implements enable function
119
+ */
120
+ enable(): void;
121
+ /**
122
+ * implements disable function
123
+ */
124
+ disable(): void;
125
+ }
126
+ //# sourceMappingURL=xhr.d.ts.map