@opentelemetry/instrumentation-fetch 0.222.0 → 0.300.0-development.1

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 (85) hide show
  1. package/README.md +14 -11
  2. package/dist/_virtual/_rolldown/runtime.cjs +23 -0
  3. package/dist/fetch.cjs +318 -0
  4. package/dist/fetch.cjs.map +1 -0
  5. package/dist/fetch.d.cts +121 -0
  6. package/dist/fetch.d.cts.map +1 -0
  7. package/dist/fetch.d.mts +121 -0
  8. package/dist/fetch.d.mts.map +1 -0
  9. package/dist/fetch.mjs +315 -0
  10. package/dist/fetch.mjs.map +1 -0
  11. package/dist/index.cjs +3 -0
  12. package/dist/index.d.cts +2 -0
  13. package/dist/index.d.mts +2 -0
  14. package/dist/index.mjs +2 -0
  15. package/dist/semconv.cjs +13 -0
  16. package/dist/semconv.cjs.map +1 -0
  17. package/dist/semconv.mjs +13 -0
  18. package/dist/semconv.mjs.map +1 -0
  19. package/dist/types.d.cts +12 -0
  20. package/dist/types.d.cts.map +1 -0
  21. package/dist/types.d.mts +12 -0
  22. package/dist/types.d.mts.map +1 -0
  23. package/dist/utils.cjs +157 -0
  24. package/dist/utils.cjs.map +1 -0
  25. package/dist/utils.mjs +154 -0
  26. package/dist/utils.mjs.map +1 -0
  27. package/dist/version.cjs +6 -0
  28. package/dist/version.cjs.map +1 -0
  29. package/dist/version.mjs +6 -0
  30. package/dist/version.mjs.map +1 -0
  31. package/package.json +36 -34
  32. package/build/esm/fetch.d.ts +0 -118
  33. package/build/esm/fetch.js +0 -412
  34. package/build/esm/fetch.js.map +0 -1
  35. package/build/esm/index.d.ts +0 -3
  36. package/build/esm/index.js +0 -6
  37. package/build/esm/index.js.map +0 -1
  38. package/build/esm/semconv.d.ts +0 -9
  39. package/build/esm/semconv.js +0 -18
  40. package/build/esm/semconv.js.map +0 -1
  41. package/build/esm/types.d.ts +0 -27
  42. package/build/esm/types.js +0 -6
  43. package/build/esm/types.js.map +0 -1
  44. package/build/esm/utils.d.ts +0 -43
  45. package/build/esm/utils.js +0 -205
  46. package/build/esm/utils.js.map +0 -1
  47. package/build/esm/version.d.ts +0 -2
  48. package/build/esm/version.js +0 -7
  49. package/build/esm/version.js.map +0 -1
  50. package/build/esnext/fetch.d.ts +0 -118
  51. package/build/esnext/fetch.js +0 -412
  52. package/build/esnext/fetch.js.map +0 -1
  53. package/build/esnext/index.d.ts +0 -3
  54. package/build/esnext/index.js +0 -6
  55. package/build/esnext/index.js.map +0 -1
  56. package/build/esnext/semconv.d.ts +0 -9
  57. package/build/esnext/semconv.js +0 -18
  58. package/build/esnext/semconv.js.map +0 -1
  59. package/build/esnext/types.d.ts +0 -27
  60. package/build/esnext/types.js +0 -6
  61. package/build/esnext/types.js.map +0 -1
  62. package/build/esnext/utils.d.ts +0 -43
  63. package/build/esnext/utils.js +0 -205
  64. package/build/esnext/utils.js.map +0 -1
  65. package/build/esnext/version.d.ts +0 -2
  66. package/build/esnext/version.js +0 -7
  67. package/build/esnext/version.js.map +0 -1
  68. package/build/src/fetch.d.ts +0 -118
  69. package/build/src/fetch.js +0 -416
  70. package/build/src/fetch.js.map +0 -1
  71. package/build/src/index.d.ts +0 -3
  72. package/build/src/index.js +0 -10
  73. package/build/src/index.js.map +0 -1
  74. package/build/src/semconv.d.ts +0 -9
  75. package/build/src/semconv.js +0 -21
  76. package/build/src/semconv.js.map +0 -1
  77. package/build/src/types.d.ts +0 -27
  78. package/build/src/types.js +0 -7
  79. package/build/src/types.js.map +0 -1
  80. package/build/src/utils.d.ts +0 -43
  81. package/build/src/utils.js +0 -212
  82. package/build/src/utils.js.map +0 -1
  83. package/build/src/version.d.ts +0 -2
  84. package/build/src/version.js +0 -10
  85. package/build/src/version.js.map +0 -1
package/README.md CHANGED
@@ -3,7 +3,11 @@
3
3
  [![NPM Published Version][npm-img]][npm-url]
4
4
  [![Apache License][license-image]][license-image]
5
5
 
6
- **Note: This is an experimental package under active development. New releases may include breaking changes.**
6
+ > [!NOTE]
7
+ > `@opentelemetry/instrumentation-fetch` is deprecated.
8
+ > Vendors and users should plan moving to [instrumentations being developed in the opentelemetry-browser repository](https://github.com/open-telemetry/opentelemetry-browser/tree/main/packages/instrumentation#readme),
9
+ > specifically [`@opentelemetry/browser-instrumentation/experimental/fetch`](https://github.com/open-telemetry/opentelemetry-browser/tree/main/packages/instrumentation#fetch).
10
+ > Note that while the `@opentelemetry/browser-instrumentation` instrumentations cover the same Browser technologies, the emitted telemetry differs significantly.
7
11
 
8
12
  This module provides auto instrumentation for web using [fetch](https://developer.mozilla.org/en-US/docs/Web/API/fetch).
9
13
  (Note: This instrumentation does **not** instrument [Node.js' fetch](https://nodejs.org/api/globals.html#fetch). See [`@opentelemetry/instrumentation-undici`](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-undici) for that.)
@@ -17,22 +21,22 @@ npm install --save @opentelemetry/instrumentation-fetch
17
21
  ## Usage
18
22
 
19
23
  ```js
24
+ import { context, trace } from '@opentelemetry/api';
20
25
  import {
21
26
  ConsoleSpanExporter,
22
27
  SimpleSpanProcessor,
23
- WebTracerProvider,
24
- } from '@opentelemetry/sdk-trace-web';
28
+ TracerProvider,
29
+ } from '@opentelemetry/sdk-trace';
25
30
  import { FetchInstrumentation } from '@opentelemetry/instrumentation-fetch';
26
31
  import { ZoneContextManager } from '@opentelemetry/context-zone';
27
32
  import { registerInstrumentations } from '@opentelemetry/instrumentation';
28
33
 
29
- const provider = new WebTracerProvider({
34
+ const provider = new TracerProvider({
30
35
  spanProcessors: [new SimpleSpanProcessor(new ConsoleSpanExporter())]
31
36
  });
32
37
 
33
- provider.register({
34
- contextManager: new ZoneContextManager(),
35
- });
38
+ context.setGlobalContextManager(new ZoneContextManager().enable());
39
+ trace.setGlobalTracerProvider(provider);
36
40
 
37
41
  registerInstrumentations({
38
42
  instrumentations: [new FetchInstrumentation()],
@@ -40,12 +44,11 @@ registerInstrumentations({
40
44
 
41
45
  // or plugin can be also initialised separately and then set the tracer provider or meter provider
42
46
  const fetchInstrumentation = new FetchInstrumentation();
43
- const provider = new WebTracerProvider({
47
+ const provider = new TracerProvider({
44
48
  spanProcessors: [new SimpleSpanProcessor(new ConsoleSpanExporter())]
45
49
  });
46
- provider.register({
47
- contextManager: new ZoneContextManager(),
48
- });
50
+ context.setGlobalContextManager(new ZoneContextManager().enable());
51
+ trace.setGlobalTracerProvider(provider);
49
52
  fetchInstrumentation.setTracerProvider(provider);
50
53
 
51
54
  // and some test
@@ -0,0 +1,23 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+ //#endregion
23
+ exports.__toESM = __toESM;
package/dist/fetch.cjs ADDED
@@ -0,0 +1,318 @@
1
+ const require_runtime = require("./_virtual/_rolldown/runtime.cjs");
2
+ const require_semconv = require("./semconv.cjs");
3
+ const require_utils = require("./utils.cjs");
4
+ const require_version = require("./version.cjs");
5
+ let _opentelemetry_api = require("@opentelemetry/api");
6
+ let _opentelemetry_instrumentation = require("@opentelemetry/instrumentation");
7
+ let _opentelemetry_core = require("@opentelemetry/core");
8
+ _opentelemetry_core = require_runtime.__toESM(_opentelemetry_core);
9
+ let _opentelemetry_web_common = require("@opentelemetry/web-common");
10
+ _opentelemetry_web_common = require_runtime.__toESM(_opentelemetry_web_common);
11
+ let _opentelemetry_semantic_conventions = require("@opentelemetry/semantic-conventions");
12
+ //#region src/fetch.ts
13
+ const OBSERVER_WAIT_TIME_MS = 300;
14
+ const hasBrowserPerformanceAPI = typeof PerformanceObserver !== "undefined";
15
+ /**
16
+ * This class represents a fetch plugin for auto instrumentation
17
+ * @deprecated See https://github.com/open-telemetry/opentelemetry-browser/tree/main/packages/instrumentation#fetch
18
+ */
19
+ var FetchInstrumentation = class extends _opentelemetry_instrumentation.InstrumentationBase {
20
+ component = "fetch";
21
+ version = require_version.VERSION;
22
+ moduleName = this.component;
23
+ _usedResources = /* @__PURE__ */ new WeakSet();
24
+ _tasksCount = 0;
25
+ constructor(config = {}) {
26
+ super("@opentelemetry/instrumentation-fetch", require_version.VERSION, config);
27
+ }
28
+ init() {}
29
+ /**
30
+ * Add cors pre flight child span
31
+ * @param span
32
+ * @param corsPreFlightRequest
33
+ */
34
+ _addChildSpan(span, corsPreFlightRequest) {
35
+ const childSpan = this.tracer.startSpan("CORS Preflight", { startTime: corsPreFlightRequest[_opentelemetry_web_common.PerformanceTimingNames.FETCH_START] }, _opentelemetry_api.trace.setSpan(_opentelemetry_api.context.active(), span));
36
+ _opentelemetry_web_common.addSpanNetworkEvents(childSpan, corsPreFlightRequest, this.getConfig().ignoreNetworkEvents, void 0);
37
+ childSpan.end(corsPreFlightRequest[_opentelemetry_web_common.PerformanceTimingNames.RESPONSE_END]);
38
+ }
39
+ /**
40
+ * Adds more attributes to span just before ending it
41
+ * @param span
42
+ * @param response
43
+ */
44
+ _addFinalSpanAttributes(span, response) {
45
+ const parsedUrl = _opentelemetry_web_common.parseUrl(response.url);
46
+ span.setAttribute(_opentelemetry_semantic_conventions.ATTR_HTTP_RESPONSE_STATUS_CODE, response.status);
47
+ span.setAttribute(_opentelemetry_semantic_conventions.ATTR_SERVER_ADDRESS, parsedUrl.hostname);
48
+ const serverPort = require_utils.serverPortFromUrl(parsedUrl);
49
+ if (serverPort) span.setAttribute(_opentelemetry_semantic_conventions.ATTR_SERVER_PORT, serverPort);
50
+ }
51
+ /**
52
+ * Add headers
53
+ * @param options
54
+ * @param spanUrl
55
+ */
56
+ _addHeaders(options, spanUrl) {
57
+ if (!_opentelemetry_web_common.shouldPropagateTraceHeaders(spanUrl, this.getConfig().propagateTraceHeaderCorsUrls)) {
58
+ const headers = {};
59
+ _opentelemetry_api.propagation.inject(_opentelemetry_api.context.active(), headers);
60
+ if (Object.keys(headers).length > 0) this._diag.debug("headers inject skipped due to CORS policy");
61
+ return;
62
+ }
63
+ if (options instanceof Request) _opentelemetry_api.propagation.inject(_opentelemetry_api.context.active(), options.headers, { set: (h, k, v) => h.set(k, typeof v === "string" ? v : String(v)) });
64
+ else {
65
+ const headers = new Headers(options.headers);
66
+ _opentelemetry_api.propagation.inject(_opentelemetry_api.context.active(), headers, { set: (h, k, v) => h.set(k, typeof v === "string" ? v : String(v)) });
67
+ options.headers = headers;
68
+ }
69
+ }
70
+ /**
71
+ * Clears the resource timings and all resources assigned with spans
72
+ * when {@link FetchPluginConfig.clearTimingResources} is
73
+ * set to true (default false)
74
+ * @private
75
+ */
76
+ _clearResources() {
77
+ if (this._tasksCount === 0 && this.getConfig().clearTimingResources) {
78
+ performance.clearResourceTimings();
79
+ this._usedResources = /* @__PURE__ */ new WeakSet();
80
+ }
81
+ }
82
+ /**
83
+ * Creates a new span
84
+ * @param url
85
+ * @param options
86
+ */
87
+ _createSpan(url, options = {}) {
88
+ if (_opentelemetry_core.isUrlIgnored(url, this.getConfig().ignoreUrls)) {
89
+ this._diag.debug("ignoring span as url matches ignored url");
90
+ return;
91
+ }
92
+ const attributes = {};
93
+ const origMethod = options.method;
94
+ const normMethod = require_utils.normalizeHttpRequestMethod(options.method || "GET");
95
+ const name = normMethod;
96
+ attributes[_opentelemetry_semantic_conventions.ATTR_HTTP_REQUEST_METHOD] = normMethod;
97
+ if (normMethod !== origMethod) attributes[_opentelemetry_semantic_conventions.ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = origMethod;
98
+ attributes[_opentelemetry_semantic_conventions.ATTR_URL_FULL] = url;
99
+ return this.tracer.startSpan(name, {
100
+ kind: _opentelemetry_api.SpanKind.CLIENT,
101
+ attributes
102
+ });
103
+ }
104
+ /**
105
+ * Finds appropriate resource and add network events to the span
106
+ * @param span
107
+ * @param resourcesObserver
108
+ * @param endTime
109
+ */
110
+ _findResourceAndAddNetworkEvents(span, resourcesObserver, endTime) {
111
+ let resources = resourcesObserver.entries;
112
+ if (!resources.length) {
113
+ if (!performance.getEntriesByType) return;
114
+ resources = performance.getEntriesByType("resource");
115
+ }
116
+ const resource = _opentelemetry_web_common.getResource(resourcesObserver.spanUrl, resourcesObserver.startTime, endTime, resources, this._usedResources, "fetch");
117
+ if (resource.mainRequest) {
118
+ const mainRequest = resource.mainRequest;
119
+ this._markResourceAsUsed(mainRequest);
120
+ const corsPreFlightRequest = resource.corsPreFlightRequest;
121
+ if (corsPreFlightRequest) {
122
+ this._addChildSpan(span, corsPreFlightRequest);
123
+ this._markResourceAsUsed(corsPreFlightRequest);
124
+ }
125
+ _opentelemetry_web_common.addSpanNetworkEvents(span, mainRequest, this.getConfig().ignoreNetworkEvents, void 0);
126
+ }
127
+ }
128
+ /**
129
+ * Marks certain [resource]{@link PerformanceResourceTiming} when information
130
+ * from this is used to add events to span.
131
+ * This is done to avoid reusing the same resource again for next span
132
+ * @param resource
133
+ */
134
+ _markResourceAsUsed(resource) {
135
+ this._usedResources.add(resource);
136
+ }
137
+ /**
138
+ * Finish span, add attributes, network events etc.
139
+ * @param span
140
+ * @param spanData
141
+ * @param response
142
+ */
143
+ _endSpan(span, spanData, response) {
144
+ const endTime = _opentelemetry_core.millisToHrTime(Date.now());
145
+ const performanceEndTime = _opentelemetry_core.hrTime();
146
+ this._addFinalSpanAttributes(span, response);
147
+ if (response.status >= 400) {
148
+ span.setStatus({ code: _opentelemetry_api.SpanStatusCode.ERROR });
149
+ span.setAttribute(_opentelemetry_semantic_conventions.ATTR_ERROR_TYPE, String(response.status));
150
+ }
151
+ setTimeout(() => {
152
+ spanData.observer?.disconnect();
153
+ this._findResourceAndAddNetworkEvents(span, spanData, performanceEndTime);
154
+ this._tasksCount--;
155
+ this._clearResources();
156
+ span.end(endTime);
157
+ }, OBSERVER_WAIT_TIME_MS);
158
+ }
159
+ /**
160
+ * Patches the constructor of fetch
161
+ */
162
+ _patchConstructor() {
163
+ return (original) => {
164
+ const plugin = this;
165
+ return function patchConstructor(...args) {
166
+ if (!plugin._isEnabled) return original.apply(this, args);
167
+ const self = this;
168
+ const url = _opentelemetry_web_common.parseUrl(args[0] instanceof Request ? args[0].url : String(args[0])).href;
169
+ let options;
170
+ if (args[0] instanceof Request) options = args[1] != null ? new Request(args[0], args[1]) : args[0];
171
+ else options = args[1] || {};
172
+ const createdSpan = plugin._createSpan(url, options);
173
+ if (!createdSpan) return original.apply(this, args);
174
+ const spanData = plugin._prepareSpanData(url);
175
+ if (plugin.getConfig().measureRequestSize) require_utils.getFetchBodyLength(...args).then((bodyLength) => {
176
+ if (!bodyLength) return;
177
+ createdSpan.setAttribute(require_semconv.ATTR_HTTP_REQUEST_BODY_SIZE, bodyLength);
178
+ }).catch((error) => {
179
+ plugin._diag.warn("getFetchBodyLength", error);
180
+ });
181
+ function endSpanOnError(span, error) {
182
+ plugin._applyAttributesAfterFetch(span, options, error);
183
+ plugin._endSpan(span, spanData, {
184
+ status: error.status || 0,
185
+ statusText: error.message,
186
+ url
187
+ });
188
+ }
189
+ function endSpanOnSuccess(span, response) {
190
+ plugin._applyAttributesAfterFetch(span, options, response);
191
+ if (response.status >= 200 && response.status < 400) plugin._endSpan(span, spanData, response);
192
+ else plugin._endSpan(span, spanData, {
193
+ status: response.status,
194
+ statusText: response.statusText,
195
+ url
196
+ });
197
+ }
198
+ function onSuccess(span, response) {
199
+ try {
200
+ const body = response.clone().body;
201
+ if (body) {
202
+ const reader = body.getReader();
203
+ const read = () => {
204
+ reader.read().then(({ done }) => {
205
+ if (done) endSpanOnSuccess(span, response);
206
+ else read();
207
+ }, (error) => {
208
+ endSpanOnError(span, error);
209
+ });
210
+ };
211
+ read();
212
+ } else endSpanOnSuccess(span, response);
213
+ } catch (error) {
214
+ plugin._diag.error("Failed to read fetch response body", error);
215
+ plugin._endSpan(span, spanData, {
216
+ status: 0,
217
+ url
218
+ });
219
+ }
220
+ return response;
221
+ }
222
+ function onError(span, error) {
223
+ try {
224
+ endSpanOnError(span, error);
225
+ } catch (e) {
226
+ plugin._diag.error("Failed to end span on fetch error", e);
227
+ plugin._endSpan(span, spanData, {
228
+ status: error.status || 0,
229
+ url
230
+ });
231
+ }
232
+ throw error;
233
+ }
234
+ return _opentelemetry_api.context.with(_opentelemetry_api.trace.setSpan(_opentelemetry_api.context.active(), createdSpan), () => {
235
+ plugin._callRequestHook(createdSpan, options);
236
+ plugin._addHeaders(options, url);
237
+ plugin._tasksCount++;
238
+ return original.apply(self, options instanceof Request ? [options] : [url, options]).then(onSuccess.bind(self, createdSpan), onError.bind(self, createdSpan));
239
+ });
240
+ };
241
+ };
242
+ }
243
+ _applyAttributesAfterFetch(span, request, result) {
244
+ const applyCustomAttributesOnSpan = this.getConfig().applyCustomAttributesOnSpan;
245
+ if (applyCustomAttributesOnSpan) (0, _opentelemetry_instrumentation.safeExecuteInTheMiddle)(() => applyCustomAttributesOnSpan(span, request, result), (error) => {
246
+ if (!error) return;
247
+ this._diag.error("applyCustomAttributesOnSpan", error);
248
+ }, true);
249
+ }
250
+ _callRequestHook(span, request) {
251
+ const requestHook = this.getConfig().requestHook;
252
+ if (requestHook) (0, _opentelemetry_instrumentation.safeExecuteInTheMiddle)(() => requestHook(span, request), (error) => {
253
+ if (!error) return;
254
+ this._diag.error("requestHook", error);
255
+ }, true);
256
+ }
257
+ /**
258
+ * Prepares a span data - needed later for matching appropriate network
259
+ * resources
260
+ * @param spanUrl
261
+ */
262
+ _prepareSpanData(spanUrl) {
263
+ const startTime = _opentelemetry_core.hrTime();
264
+ const entries = [];
265
+ if (typeof PerformanceObserver !== "function") return {
266
+ entries,
267
+ startTime,
268
+ spanUrl
269
+ };
270
+ const observer = new PerformanceObserver((list) => {
271
+ list.getEntries().forEach((entry) => {
272
+ if (entry.initiatorType === "fetch" && entry.name === spanUrl) entries.push(entry);
273
+ });
274
+ });
275
+ observer.observe({ entryTypes: ["resource"] });
276
+ return {
277
+ entries,
278
+ observer,
279
+ startTime,
280
+ spanUrl
281
+ };
282
+ }
283
+ /**
284
+ * implements enable function
285
+ */
286
+ enable() {
287
+ if (!hasBrowserPerformanceAPI) {
288
+ this._diag.warn("this instrumentation is intended for web usage only, it does not instrument server-side fetch()");
289
+ return;
290
+ }
291
+ if (this._isEnabled) return;
292
+ if (this._isFetchPatched) {
293
+ this._diag.debug("fetch constructor already patched");
294
+ this._isEnabled = true;
295
+ return;
296
+ }
297
+ try {
298
+ this._wrap(globalThis, "fetch", this._patchConstructor());
299
+ this._isFetchPatched = true;
300
+ this._isEnabled = true;
301
+ } catch (err) {
302
+ this._diag.warn("Failed to patch globalThis.fetch; instrumentation will not be enabled. Another script may have locked globalThis.fetch via Object.defineProperty.", err);
303
+ }
304
+ }
305
+ /**
306
+ * deactivates fetch instrumentation
307
+ */
308
+ disable() {
309
+ if (!hasBrowserPerformanceAPI) return;
310
+ if (!this._isEnabled) return;
311
+ this._isEnabled = false;
312
+ this._usedResources = /* @__PURE__ */ new WeakSet();
313
+ }
314
+ };
315
+ //#endregion
316
+ exports.FetchInstrumentation = FetchInstrumentation;
317
+
318
+ //# sourceMappingURL=fetch.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.cjs","names":["InstrumentationBase","VERSION","web","trace","context","ATTR_HTTP_RESPONSE_STATUS_CODE","ATTR_SERVER_ADDRESS","serverPortFromUrl","ATTR_SERVER_PORT","core","normalizeHttpRequestMethod","ATTR_HTTP_REQUEST_METHOD","ATTR_HTTP_REQUEST_METHOD_ORIGINAL","ATTR_URL_FULL","SpanKind","SpanStatusCode","ATTR_ERROR_TYPE","ATTR_HTTP_REQUEST_BODY_SIZE"],"sources":["../src/fetch.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n context,\n propagation,\n SpanKind,\n SpanStatusCode,\n trace,\n} from '@opentelemetry/api';\nimport type { Attributes, HrTime, Span } from '@opentelemetry/api';\nimport type { InstrumentationConfig } from '@opentelemetry/instrumentation';\nimport {\n InstrumentationBase,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport * as core from '@opentelemetry/core';\nimport * as web from '@opentelemetry/web-common';\nimport { ATTR_HTTP_REQUEST_BODY_SIZE } from './semconv';\nimport {\n ATTR_ERROR_TYPE,\n ATTR_HTTP_REQUEST_METHOD,\n ATTR_HTTP_REQUEST_METHOD_ORIGINAL,\n ATTR_HTTP_RESPONSE_STATUS_CODE,\n ATTR_SERVER_ADDRESS,\n ATTR_SERVER_PORT,\n ATTR_URL_FULL,\n} from '@opentelemetry/semantic-conventions';\nimport type { FetchError, FetchResponse, SpanData } from './types';\nimport {\n getFetchBodyLength,\n normalizeHttpRequestMethod,\n serverPortFromUrl,\n} from './utils';\nimport { VERSION } from './version';\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\nconst hasBrowserPerformanceAPI = typeof PerformanceObserver !== 'undefined';\n\nexport interface FetchCustomAttributeFunction {\n (\n span: Span,\n request: Request | RequestInit,\n result: Response | FetchError\n ): void;\n}\n\nexport interface FetchRequestHookFunction {\n (span: Span, request: Request | RequestInit): void;\n}\n\n/**\n * FetchPlugin Config\n */\nexport interface FetchInstrumentationConfig extends InstrumentationConfig {\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 clearTimingResources?: boolean;\n // urls which should include trace headers when origin doesn't match\n propagateTraceHeaderCorsUrls?: web.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?: FetchCustomAttributeFunction;\n /** Function for adding custom attributes or headers before the request is handled */\n requestHook?: FetchRequestHookFunction;\n // Ignore adding network events as span events\n ignoreNetworkEvents?: boolean;\n /** Measure outgoing request size */\n measureRequestSize?: boolean;\n}\n\n/**\n * This class represents a fetch plugin for auto instrumentation\n * @deprecated See https://github.com/open-telemetry/opentelemetry-browser/tree/main/packages/instrumentation#fetch\n */\nexport class FetchInstrumentation extends InstrumentationBase<FetchInstrumentationConfig> {\n readonly component: string = 'fetch';\n readonly version: string = VERSION;\n moduleName = this.component;\n private _usedResources = new WeakSet<PerformanceResourceTiming>();\n private _tasksCount = 0;\n\n // Note: Intentionally *not* using `_enabled` as the field name to avoid\n // any possible confusion with the `_enabled` field used on the *Node.js*\n // InstrumentationBase class.\n // Also not initializing the fields to `false` because the base class\n // constructor already call `enable` modifying their values and it will\n // set the instrumentaitons in a bas state (enabled, patched but with flags set to false)\n declare private _isEnabled: boolean;\n declare private _isFetchPatched: boolean;\n\n constructor(config: FetchInstrumentationConfig = {}) {\n super('@opentelemetry/instrumentation-fetch', VERSION, config);\n }\n\n init(): void {}\n\n /**\n * Add cors pre flight child span\n * @param span\n * @param corsPreFlightRequest\n */\n private _addChildSpan(\n span: Span,\n corsPreFlightRequest: PerformanceResourceTiming\n ): void {\n const childSpan = this.tracer.startSpan(\n 'CORS Preflight',\n {\n startTime: corsPreFlightRequest[web.PerformanceTimingNames.FETCH_START],\n },\n trace.setSpan(context.active(), span)\n );\n web.addSpanNetworkEvents(\n childSpan,\n corsPreFlightRequest,\n this.getConfig().ignoreNetworkEvents,\n undefined\n );\n childSpan.end(\n corsPreFlightRequest[web.PerformanceTimingNames.RESPONSE_END]\n );\n }\n\n /**\n * Adds more attributes to span just before ending it\n * @param span\n * @param response\n */\n private _addFinalSpanAttributes(span: Span, response: FetchResponse): void {\n const parsedUrl = web.parseUrl(response.url);\n span.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, response.status);\n // TODO: Set server.{address,port} at span creation for sampling decisions\n // (a \"SHOULD\" requirement in semconv).\n span.setAttribute(ATTR_SERVER_ADDRESS, parsedUrl.hostname);\n const serverPort = serverPortFromUrl(parsedUrl);\n if (serverPort) {\n span.setAttribute(ATTR_SERVER_PORT, serverPort);\n }\n }\n\n /**\n * Add headers\n * @param options\n * @param spanUrl\n */\n private _addHeaders(options: Request | RequestInit, spanUrl: string): void {\n if (\n !web.shouldPropagateTraceHeaders(\n spanUrl,\n this.getConfig().propagateTraceHeaderCorsUrls\n )\n ) {\n const headers: Partial<Record<string, unknown>> = {};\n propagation.inject(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\n if (options instanceof Request) {\n // This mutates `Request.headers` in-place, because it is read-only\n // (per https://developer.mozilla.org/en-US/docs/Web/API/Request/headers),\n // so we cannot (easily) replace it.\n propagation.inject(context.active(), options.headers, {\n set: (h, k, v) => h.set(k, typeof v === 'string' ? v : String(v)),\n });\n } else {\n // Otherwise, create a new Headers to avoid mutating the caller's\n // possibly re-used headers.\n const headers = new Headers(options.headers);\n propagation.inject(context.active(), headers, {\n set: (h, k, v) => h.set(k, typeof v === 'string' ? v : String(v)),\n });\n options.headers = headers;\n }\n }\n\n /**\n * Clears the resource timings and all resources assigned with spans\n * when {@link FetchPluginConfig.clearTimingResources} is\n * set to true (default false)\n * @private\n */\n private _clearResources() {\n if (this._tasksCount === 0 && this.getConfig().clearTimingResources) {\n performance.clearResourceTimings();\n this._usedResources = new WeakSet<PerformanceResourceTiming>();\n }\n }\n\n /**\n * Creates a new span\n * @param url\n * @param options\n */\n private _createSpan(\n url: string,\n options: Partial<Request | RequestInit> = {}\n ): Span | undefined {\n if (core.isUrlIgnored(url, this.getConfig().ignoreUrls)) {\n this._diag.debug('ignoring span as url matches ignored url');\n return;\n }\n\n const attributes = {} as Attributes;\n const origMethod = options.method;\n const normMethod = normalizeHttpRequestMethod(options.method || 'GET');\n const name = normMethod;\n\n attributes[ATTR_HTTP_REQUEST_METHOD] = normMethod;\n if (normMethod !== origMethod) {\n attributes[ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = origMethod;\n }\n attributes[ATTR_URL_FULL] = url;\n\n return this.tracer.startSpan(name, {\n kind: SpanKind.CLIENT,\n attributes,\n });\n }\n\n /**\n * Finds appropriate resource and add network events to the span\n * @param span\n * @param resourcesObserver\n * @param endTime\n */\n private _findResourceAndAddNetworkEvents(\n span: Span,\n resourcesObserver: SpanData,\n endTime: HrTime\n ): void {\n let resources: PerformanceResourceTiming[] = resourcesObserver.entries;\n if (!resources.length) {\n if (!performance.getEntriesByType) {\n return;\n }\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 resources = performance.getEntriesByType(\n 'resource'\n ) as PerformanceResourceTiming[];\n }\n const resource = web.getResource(\n resourcesObserver.spanUrl,\n resourcesObserver.startTime,\n endTime,\n resources,\n this._usedResources,\n 'fetch'\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 web.addSpanNetworkEvents(\n span,\n mainRequest,\n this.getConfig().ignoreNetworkEvents,\n undefined\n );\n }\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 */\n private _markResourceAsUsed(resource: PerformanceResourceTiming): void {\n this._usedResources.add(resource);\n }\n\n /**\n * Finish span, add attributes, network events etc.\n * @param span\n * @param spanData\n * @param response\n */\n private _endSpan(span: Span, spanData: SpanData, response: FetchResponse) {\n const endTime = core.millisToHrTime(Date.now());\n const performanceEndTime = core.hrTime();\n this._addFinalSpanAttributes(span, response);\n\n // https://github.com/open-telemetry/semantic-conventions/blob/main/docs/http/http-spans.md#status\n if (response.status >= 400) {\n span.setStatus({ code: SpanStatusCode.ERROR });\n span.setAttribute(ATTR_ERROR_TYPE, String(response.status));\n }\n\n setTimeout(() => {\n spanData.observer?.disconnect();\n this._findResourceAndAddNetworkEvents(span, spanData, performanceEndTime);\n this._tasksCount--;\n this._clearResources();\n span.end(endTime);\n }, OBSERVER_WAIT_TIME_MS);\n }\n\n /**\n * Patches the constructor of fetch\n */\n private _patchConstructor(): (original: typeof fetch) => typeof fetch {\n return original => {\n const plugin = this;\n\n return function patchConstructor(\n this: typeof globalThis,\n ...args: Parameters<typeof fetch>\n ): Promise<Response> {\n if (!plugin._isEnabled) {\n return original.apply(this, args);\n }\n const self = this;\n const url = web.parseUrl(\n args[0] instanceof Request ? args[0].url : String(args[0])\n ).href;\n\n // Per the Fetch spec, when fetch() is called with a Request object\n // and a separate init object, the init properties override the\n // Request's properties. Merge them into a new Request so that\n // downstream consumers (hooks, header injection, the actual fetch\n // call) see the correct final values.\n // See: https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#parameters\n let options: Request | RequestInit;\n if (args[0] instanceof Request) {\n options = args[1] != null ? new Request(args[0], args[1]) : args[0];\n } else {\n options = args[1] || {};\n }\n const createdSpan = plugin._createSpan(url, options);\n if (!createdSpan) {\n return original.apply(this, args);\n }\n const spanData = plugin._prepareSpanData(url);\n\n if (plugin.getConfig().measureRequestSize) {\n getFetchBodyLength(...args)\n .then(bodyLength => {\n if (!bodyLength) return;\n createdSpan.setAttribute(ATTR_HTTP_REQUEST_BODY_SIZE, bodyLength);\n })\n .catch(error => {\n plugin._diag.warn('getFetchBodyLength', error);\n });\n }\n\n function endSpanOnError(span: Span, error: FetchError) {\n plugin._applyAttributesAfterFetch(span, options, error);\n plugin._endSpan(span, spanData, {\n status: error.status || 0,\n statusText: error.message,\n url,\n });\n }\n\n function endSpanOnSuccess(span: Span, response: Response) {\n plugin._applyAttributesAfterFetch(span, options, response);\n if (response.status >= 200 && response.status < 400) {\n plugin._endSpan(span, spanData, response);\n } else {\n plugin._endSpan(span, spanData, {\n status: response.status,\n statusText: response.statusText,\n url,\n });\n }\n }\n\n function onSuccess(span: Span, response: Response): Response {\n try {\n // Clone the response and eagerly consume the clone to detect\n // when the body transfer completes. The original response is\n // returned to the caller untouched so that it passes internal\n // brand-checks required by APIs such as\n // WebAssembly.compileStreaming.\n // TODO: Switch to a consumer-driven model and drop `resClone`.\n // Keeping eager consumption here to preserve current behavior and avoid breaking existing tests.\n // Context: discussion in PR #5894 → https://github.com/open-telemetry/opentelemetry-js/pull/5894\n const resClone = response.clone();\n const body = resClone.body;\n if (body) {\n const reader = body.getReader();\n\n const read = (): void => {\n reader.read().then(\n ({ done }) => {\n if (done) {\n endSpanOnSuccess(span, response);\n } else {\n read();\n }\n },\n error => {\n endSpanOnError(span, error);\n }\n );\n };\n read();\n } else {\n // some older browsers don't have .body implemented\n endSpanOnSuccess(span, response);\n }\n } catch (error) {\n // Setup failed (e.g. clone() or getReader() threw).\n // End the span and clean up so _tasksCount doesn't leak.\n plugin._diag.error('Failed to read fetch response body', error);\n plugin._endSpan(span, spanData, {\n status: 0,\n url,\n });\n }\n return response;\n }\n\n function onError(span: Span, error: FetchError): never {\n try {\n endSpanOnError(span, error);\n } catch (e: unknown) {\n // endSpanOnError failed — fall back to ending the span\n // directly so _tasksCount doesn't leak.\n plugin._diag.error('Failed to end span on fetch error', e);\n plugin._endSpan(span, spanData, {\n status: error.status || 0,\n url,\n });\n }\n\n throw error;\n }\n\n return context.with(\n trace.setSpan(context.active(), createdSpan),\n () => {\n // Call request hook before injection so hooks cannot tamper with propagation headers.\n // Also, this means the hook will see `options.headers` in the same type as passed in,\n // rather than as a `Headers` instance set by `_addHeaders()`.\n plugin._callRequestHook(createdSpan, options);\n plugin._addHeaders(options, url);\n plugin._tasksCount++;\n\n return original\n .apply(\n self,\n options instanceof Request ? [options] : [url, options]\n )\n .then(\n onSuccess.bind(self, createdSpan),\n onError.bind(self, createdSpan)\n );\n }\n );\n };\n };\n }\n\n private _applyAttributesAfterFetch(\n span: Span,\n request: Request | RequestInit,\n result: Response | FetchError\n ) {\n const applyCustomAttributesOnSpan =\n this.getConfig().applyCustomAttributesOnSpan;\n if (applyCustomAttributesOnSpan) {\n safeExecuteInTheMiddle(\n () => applyCustomAttributesOnSpan(span, request, result),\n error => {\n if (!error) {\n return;\n }\n\n this._diag.error('applyCustomAttributesOnSpan', error);\n },\n true\n );\n }\n }\n\n private _callRequestHook(span: Span, request: Request | RequestInit) {\n const requestHook = this.getConfig().requestHook;\n if (requestHook) {\n safeExecuteInTheMiddle(\n () => requestHook(span, request),\n error => {\n if (!error) {\n return;\n }\n\n this._diag.error('requestHook', error);\n },\n true\n );\n }\n }\n\n /**\n * Prepares a span data - needed later for matching appropriate network\n * resources\n * @param spanUrl\n */\n private _prepareSpanData(spanUrl: string): SpanData {\n const startTime = core.hrTime();\n const entries: PerformanceResourceTiming[] = [];\n if (typeof PerformanceObserver !== 'function') {\n return { entries, startTime, spanUrl };\n }\n\n const observer = new PerformanceObserver(list => {\n const perfObsEntries = list.getEntries() as PerformanceResourceTiming[];\n perfObsEntries.forEach(entry => {\n if (entry.initiatorType === 'fetch' && entry.name === spanUrl) {\n entries.push(entry);\n }\n });\n });\n observer.observe({\n entryTypes: ['resource'],\n });\n return { entries, observer, startTime, spanUrl };\n }\n\n /**\n * implements enable function\n */\n override enable(): void {\n if (!hasBrowserPerformanceAPI) {\n this._diag.warn(\n 'this instrumentation is intended for web usage only, it does not instrument server-side fetch()'\n );\n return;\n }\n\n if (this._isEnabled) {\n return;\n }\n\n if (this._isFetchPatched) {\n this._diag.debug('fetch constructor already patched');\n this._isEnabled = true;\n return;\n }\n\n try {\n // `_wrap` throws if a third-party script has locked globalThis.fetch via\n // Object.defineProperty(window, 'fetch', { writable: false, ... }).\n this._wrap(globalThis, 'fetch', this._patchConstructor());\n this._isFetchPatched = true;\n this._isEnabled = true;\n } catch (err) {\n this._diag.warn(\n 'Failed to patch globalThis.fetch; instrumentation will not be enabled. ' +\n 'Another script may have locked globalThis.fetch via Object.defineProperty.',\n err\n );\n }\n }\n\n /**\n * deactivates fetch instrumentation\n */\n override disable(): void {\n if (!hasBrowserPerformanceAPI) {\n return;\n }\n if (!this._isEnabled) {\n return;\n }\n this._isEnabled = false;\n this._usedResources = new WeakSet<PerformanceResourceTiming>();\n }\n}\n"],"mappings":";;;;;;;;;;;;AA0CA,MAAM,wBAAwB;AAE9B,MAAM,2BAA2B,OAAO,wBAAwB;;;;;AA8ChE,IAAa,uBAAb,cAA0CA,+BAAAA,oBAAgD;CACxF,YAA6B;CAC7B,UAA2BC,gBAAAA;CAC3B,aAAa,KAAK;CAClB,iCAAyB,IAAI,QAAmC;CAChE,cAAsB;CAWtB,YAAY,SAAqC,CAAC,GAAG;EACnD,MAAM,wCAAwCA,gBAAAA,SAAS,MAAM;CAC/D;CAEA,OAAa,CAAC;;;;;;CAOd,cACE,MACA,sBACM;EACN,MAAM,YAAY,KAAK,OAAO,UAC5B,kBACA,EACE,WAAW,qBAAqBC,0BAAI,uBAAuB,aAC7D,GACAC,mBAAAA,MAAM,QAAQC,mBAAAA,QAAQ,OAAO,GAAG,IAAI,CACtC;EACA,0BAAI,qBACF,WACA,sBACA,KAAK,UAAU,CAAC,CAAC,qBACjB,KAAA,CACF;EACA,UAAU,IACR,qBAAqBF,0BAAI,uBAA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,kBAAkB;GACvB,KAAK,aAAa;EACpB,SAAS,KAAK;GACZ,KAAK,MAAM,KACT,qJAEA,GACF;EACF;CACF;;;;CAKA,UAAyB;EACvB,IAAI,CAAC,0BACH;EAEF,IAAI,CAAC,KAAK,YACR;EAEF,KAAK,aAAa;EAClB,KAAK,iCAAiB,IAAI,QAAmC;CAC/D;AACF"}
@@ -0,0 +1,121 @@
1
+ import { FetchError } from "./types.cjs";
2
+ import { Span } from "@opentelemetry/api";
3
+ import { InstrumentationBase, InstrumentationConfig } from "@opentelemetry/instrumentation";
4
+ import * as web from "@opentelemetry/web-common";
5
+ //#region src/fetch.d.ts
6
+ interface FetchCustomAttributeFunction {
7
+ (span: Span, request: Request | RequestInit, result: Response | FetchError): void;
8
+ }
9
+ interface FetchRequestHookFunction {
10
+ (span: Span, request: Request | RequestInit): void;
11
+ }
12
+ /**
13
+ * FetchPlugin Config
14
+ */
15
+ interface FetchInstrumentationConfig extends InstrumentationConfig {
16
+ clearTimingResources?: boolean;
17
+ propagateTraceHeaderCorsUrls?: web.PropagateTraceHeaderCorsUrls;
18
+ /**
19
+ * URLs that partially match any regex in ignoreUrls will not be traced.
20
+ * In addition, URLs that are _exact matches_ of strings in ignoreUrls will
21
+ * also not be traced.
22
+ */
23
+ ignoreUrls?: Array<string | RegExp>;
24
+ /** Function for adding custom attributes on the span */
25
+ applyCustomAttributesOnSpan?: FetchCustomAttributeFunction;
26
+ /** Function for adding custom attributes or headers before the request is handled */
27
+ requestHook?: FetchRequestHookFunction;
28
+ ignoreNetworkEvents?: boolean;
29
+ /** Measure outgoing request size */
30
+ measureRequestSize?: boolean;
31
+ }
32
+ /**
33
+ * This class represents a fetch plugin for auto instrumentation
34
+ * @deprecated See https://github.com/open-telemetry/opentelemetry-browser/tree/main/packages/instrumentation#fetch
35
+ */
36
+ declare class FetchInstrumentation extends InstrumentationBase<FetchInstrumentationConfig> {
37
+ readonly component: string;
38
+ readonly version: string;
39
+ moduleName: string;
40
+ private _usedResources;
41
+ private _tasksCount;
42
+ private _isEnabled;
43
+ private _isFetchPatched;
44
+ constructor(config?: FetchInstrumentationConfig);
45
+ init(): void;
46
+ /**
47
+ * Add cors pre flight child span
48
+ * @param span
49
+ * @param corsPreFlightRequest
50
+ */
51
+ private _addChildSpan;
52
+ /**
53
+ * Adds more attributes to span just before ending it
54
+ * @param span
55
+ * @param response
56
+ */
57
+ private _addFinalSpanAttributes;
58
+ /**
59
+ * Add headers
60
+ * @param options
61
+ * @param spanUrl
62
+ */
63
+ private _addHeaders;
64
+ /**
65
+ * Clears the resource timings and all resources assigned with spans
66
+ * when {@link FetchPluginConfig.clearTimingResources} is
67
+ * set to true (default false)
68
+ * @private
69
+ */
70
+ private _clearResources;
71
+ /**
72
+ * Creates a new span
73
+ * @param url
74
+ * @param options
75
+ */
76
+ private _createSpan;
77
+ /**
78
+ * Finds appropriate resource and add network events to the span
79
+ * @param span
80
+ * @param resourcesObserver
81
+ * @param endTime
82
+ */
83
+ private _findResourceAndAddNetworkEvents;
84
+ /**
85
+ * Marks certain [resource]{@link PerformanceResourceTiming} when information
86
+ * from this is used to add events to span.
87
+ * This is done to avoid reusing the same resource again for next span
88
+ * @param resource
89
+ */
90
+ private _markResourceAsUsed;
91
+ /**
92
+ * Finish span, add attributes, network events etc.
93
+ * @param span
94
+ * @param spanData
95
+ * @param response
96
+ */
97
+ private _endSpan;
98
+ /**
99
+ * Patches the constructor of fetch
100
+ */
101
+ private _patchConstructor;
102
+ private _applyAttributesAfterFetch;
103
+ private _callRequestHook;
104
+ /**
105
+ * Prepares a span data - needed later for matching appropriate network
106
+ * resources
107
+ * @param spanUrl
108
+ */
109
+ private _prepareSpanData;
110
+ /**
111
+ * implements enable function
112
+ */
113
+ enable(): void;
114
+ /**
115
+ * deactivates fetch instrumentation
116
+ */
117
+ disable(): void;
118
+ }
119
+ //#endregion
120
+ export { FetchCustomAttributeFunction, FetchInstrumentation, FetchInstrumentationConfig, FetchRequestHookFunction };
121
+ //# sourceMappingURL=fetch.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.d.cts","names":[],"sources":["../src/fetch.d.ts"],"mappings":";;;;;UAKiB;GACZ,MAAM,MAAM,SAAS,UAAU,aAAa,QAAQ,WAAW;;UAEnD;GACZ,MAAM,MAAM,SAAS,UAAU;;;;;UAKnB,mCAAmC;EAChD;EACA,+BAA+B,IAAI;;;;;;EAMnC,aAAa,eAAe;;EAE5B,8BAA8B;;EAE9B,cAAc;EACd;;EAEA;;;;;;cAMiB,6BAA6B,oBAAoB;WACzD;WACA;EACT;UACQ;UACA;UACA;UACA;EACR,YAAY,SAAS;EACrB;;;;;;UAMQ;;;;;;UAMA;;;;;;UAMA;;;;;;;UAOA;;;;;;UAMA;;;;;;;UAOA;;;;;;;UAOA;;;;;;;UAOA;;;;UAIA;UACA;UACA;;;;;;UAMA;;;;EAIR;;;;EAIA"}