@amplitude/analytics-core 2.22.0 → 2.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/lib/cjs/network-observer.d.ts +18 -2
  2. package/lib/cjs/network-observer.d.ts.map +1 -1
  3. package/lib/cjs/network-observer.js +60 -6
  4. package/lib/cjs/network-observer.js.map +1 -1
  5. package/lib/cjs/network-request-event.d.ts +2 -4
  6. package/lib/cjs/network-request-event.d.ts.map +1 -1
  7. package/lib/cjs/network-request-event.js +11 -20
  8. package/lib/cjs/network-request-event.js.map +1 -1
  9. package/lib/cjs/types/element-interactions.d.ts +9 -0
  10. package/lib/cjs/types/element-interactions.d.ts.map +1 -1
  11. package/lib/cjs/types/element-interactions.js.map +1 -1
  12. package/lib/cjs/types/frustration-interactions.d.ts +7 -0
  13. package/lib/cjs/types/frustration-interactions.d.ts.map +1 -1
  14. package/lib/cjs/types/frustration-interactions.js.map +1 -1
  15. package/lib/esm/network-observer.d.ts +18 -2
  16. package/lib/esm/network-observer.d.ts.map +1 -1
  17. package/lib/esm/network-observer.js +60 -6
  18. package/lib/esm/network-observer.js.map +1 -1
  19. package/lib/esm/network-request-event.d.ts +2 -4
  20. package/lib/esm/network-request-event.d.ts.map +1 -1
  21. package/lib/esm/network-request-event.js +11 -20
  22. package/lib/esm/network-request-event.js.map +1 -1
  23. package/lib/esm/types/element-interactions.d.ts +9 -0
  24. package/lib/esm/types/element-interactions.d.ts.map +1 -1
  25. package/lib/esm/types/element-interactions.js.map +1 -1
  26. package/lib/esm/types/frustration-interactions.d.ts +7 -0
  27. package/lib/esm/types/frustration-interactions.d.ts.map +1 -1
  28. package/lib/esm/types/frustration-interactions.js.map +1 -1
  29. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"frustration-interactions.d.ts","sourceRoot":"","sources":["../../../src/types/frustration-interactions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM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eAAO,MAAM,0CAA0C,KAAK,CAAC;AAK7D,KAAK,UAAU,GAAG,OAAO,UAAU,SAAS;IAC1C,OAAO,EAAE,KAAK,GAAG,IAAI,EAAE,GAAG,KAAK,MAAM,CAAC,CAAC;CACxC,GACG,CAAC,GACD,KAAK,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"frustration-interactions.js","sourceRoot":"","sources":["../../../src/types/frustration-interactions.ts"],"names":[],"mappings":";;;;AAoEA,IAAM,2BAA2B,GAAG;IAClC,GAAG;IACH,QAAQ;IACR,iBAAiB;IACjB,eAAe;IACf,mBAAmB;IACnB,2BAA2B;IAC3B,wBAAwB;IACxB,iBAAiB;IACjB,cAAc;IACd,mBAAmB;IACnB,4BAA4B;CAC7B,CAAC;AAEF;;GAEG;AACU,QAAA,4BAA4B;IACvC,sBAAsB;IACtB,sBAAsB;IACtB,qBAAqB;IACrB,qBAAqB;IACrB,oBAAoB;kBACjB,2BAA2B,UAC9B;AAEF;;GAEG;AACU,QAAA,4BAA4B,GAAG,CAAC,GAAG,CAAC,CAAC;AAElD;;GAEG;AACU,QAAA,4BAA4B,GAAG,IAAK,CAAC;AAElD;;GAEG;AACU,QAAA,4BAA4B,GAAG,IAAK,CAAC;AAElD;;GAEG;AACU,QAAA,4BAA4B,GAAG,CAAC,CAAC;AAE9C;;GAEG;AACU,QAAA,0CAA0C,GAAG,EAAE,CAAC,CAAC,SAAS","sourcesContent":["import { ActionType } from './element-interactions';\n\n/**\n * Configuration options for dead clicks tracking\n */\nexport interface DeadClickOptions {\n /**\n * CSS selectors to define which elements on the page to track for dead clicks.\n * A dead click is a click that doesn't result in any visible change or navigation.\n */\n cssSelectorAllowlist?: string[];\n}\n\n/**\n * Configuration options for rage clicks tracking\n */\nexport interface RageClickOptions {\n /**\n * CSS selectors to define which elements on the page to track for rage clicks.\n * A rage click is multiple rapid clicks on the same element within a 3s time window.\n */\n cssSelectorAllowlist?: string[];\n}\n\n/**\n * Configuration options for frustration interactions tracking.\n * This includes dead clicks and rage clicks tracking.\n */\nexport interface FrustrationInteractionsOptions {\n /**\n * List of page URLs to allow auto tracking on.\n * When provided, only allow tracking on these URLs.\n * Both full URLs and regex are supported.\n */\n pageUrlAllowlist?: (string | RegExp)[];\n\n /**\n * Function to determine whether an event should be tracked.\n * When provided, this function overwrites all other allowlists and configurations.\n * If the function returns true, the event will be tracked.\n * If the function returns false, the event will not be tracked.\n * @param actionType - The type of action that triggered the event.\n * @param element - The [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) that triggered the event.\n */\n shouldTrackEventResolver?: (actionType: ActionType, element: DomElement) => boolean;\n\n /**\n * Prefix for data attributes to allow auto collecting.\n * Default is 'data-amp-track-'.\n */\n dataAttributePrefix?: string;\n\n /**\n * Configuration for dead clicks tracking\n */\n deadClicks?: DeadClickOptions;\n\n /**\n * Configuration for rage clicks tracking\n */\n rageClicks?: RageClickOptions;\n\n /**\n * RegExp pattern list to allow custom patterns for text masking\n */\n maskTextRegex?: (RegExp | { pattern: string; description: string })[];\n}\n\nconst CLICKABLE_ELEMENT_SELECTORS = [\n 'a',\n 'button',\n '[role=\"button\"]',\n '[role=\"link\"]',\n '[role=\"menuitem\"]',\n '[role=\"menuitemcheckbox\"]',\n '[role=\"menuitemradio\"]',\n '[role=\"option\"]',\n '[role=\"tab\"]',\n '[role=\"treeitem\"]',\n '[contenteditable=\"true\" i]',\n];\n\n/**\n * Default CSS selectors for dead clicks tracking\n */\nexport const DEFAULT_DEAD_CLICK_ALLOWLIST = [\n 'input[type=\"button\"]',\n 'input[type=\"submit\"]',\n 'input[type=\"reset\"]',\n 'input[type=\"image\"]',\n 'input[type=\"file\"]',\n ...CLICKABLE_ELEMENT_SELECTORS,\n];\n\n/**\n * Default CSS selectors for rage clicks tracking\n */\nexport const DEFAULT_RAGE_CLICK_ALLOWLIST = ['*'];\n\n/**\n * Default time window for dead clicks (3 seconds)\n */\nexport const DEFAULT_DEAD_CLICK_WINDOW_MS = 3_000;\n\n/**\n * Default time window for rage clicks (1 second)\n */\nexport const DEFAULT_RAGE_CLICK_WINDOW_MS = 1_000;\n\n/**\n * Default threshold for rage clicks (4 clicks)\n */\nexport const DEFAULT_RAGE_CLICK_THRESHOLD = 4;\n\n/**\n * Default threshold for rage clicks to be considered out of bounds (50 pixels)\n */\nexport const DEFAULT_RAGE_CLICK_OUT_OF_BOUNDS_THRESHOLD = 50; // pixels\n\n// DomElement is [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) if the dom library is included in tsconfig.json\n// and never if it is not included\n// eslint-disable-next-line no-restricted-globals\ntype DomElement = typeof globalThis extends {\n Element: new (...args: any) => infer T;\n}\n ? T\n : never;\n"]}
1
+ {"version":3,"file":"frustration-interactions.js","sourceRoot":"","sources":["../../../src/types/frustration-interactions.ts"],"names":[],"mappings":";;;;AA4EA,IAAM,2BAA2B,GAAG;IAClC,GAAG;IACH,QAAQ;IACR,iBAAiB;IACjB,eAAe;IACf,mBAAmB;IACnB,2BAA2B;IAC3B,wBAAwB;IACxB,iBAAiB;IACjB,cAAc;IACd,mBAAmB;IACnB,4BAA4B;CAC7B,CAAC;AAEF;;GAEG;AACU,QAAA,4BAA4B;IACvC,sBAAsB;IACtB,sBAAsB;IACtB,qBAAqB;IACrB,qBAAqB;IACrB,oBAAoB;kBACjB,2BAA2B,UAC9B;AAEF;;GAEG;AACU,QAAA,4BAA4B,GAAG,CAAC,GAAG,CAAC,CAAC;AAElD;;GAEG;AACU,QAAA,4BAA4B,GAAG,IAAK,CAAC;AAElD;;GAEG;AACU,QAAA,4BAA4B,GAAG,IAAK,CAAC;AAElD;;GAEG;AACU,QAAA,4BAA4B,GAAG,CAAC,CAAC;AAE9C;;GAEG;AACU,QAAA,0CAA0C,GAAG,EAAE,CAAC,CAAC,SAAS","sourcesContent":["import { ActionType } from './element-interactions';\n\n/**\n * Configuration options for dead clicks tracking\n */\nexport interface DeadClickOptions {\n /**\n * CSS selectors to define which elements on the page to track for dead clicks.\n * A dead click is a click that doesn't result in any visible change or navigation.\n */\n cssSelectorAllowlist?: string[];\n}\n\n/**\n * Configuration options for rage clicks tracking\n */\nexport interface RageClickOptions {\n /**\n * CSS selectors to define which elements on the page to track for rage clicks.\n * A rage click is multiple rapid clicks on the same element within a 3s time window.\n */\n cssSelectorAllowlist?: string[];\n}\n\n/**\n * Configuration options for frustration interactions tracking.\n * This includes dead clicks and rage clicks tracking.\n */\nexport interface FrustrationInteractionsOptions {\n /**\n * List of page URLs to allow auto tracking on.\n * When provided, only allow tracking on these URLs.\n * Both full URLs and regex are supported.\n */\n pageUrlAllowlist?: (string | RegExp)[];\n\n /**\n * List of page URLs to exclude from auto tracking.\n * When provided, tracking will be blocked on these URLs.\n * Both full URLs and regex are supported.\n * This takes precedence over pageUrlAllowlist.\n */\n pageUrlExcludelist?: (string | RegExp)[];\n\n /**\n * Function to determine whether an event should be tracked.\n * When provided, this function overwrites all other allowlists and configurations.\n * If the function returns true, the event will be tracked.\n * If the function returns false, the event will not be tracked.\n * @param actionType - The type of action that triggered the event.\n * @param element - The [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) that triggered the event.\n */\n shouldTrackEventResolver?: (actionType: ActionType, element: DomElement) => boolean;\n\n /**\n * Prefix for data attributes to allow auto collecting.\n * Default is 'data-amp-track-'.\n */\n dataAttributePrefix?: string;\n\n /**\n * Configuration for dead clicks tracking\n */\n deadClicks?: DeadClickOptions;\n\n /**\n * Configuration for rage clicks tracking\n */\n rageClicks?: RageClickOptions;\n\n /**\n * RegExp pattern list to allow custom patterns for text masking\n */\n maskTextRegex?: (RegExp | { pattern: string; description: string })[];\n}\n\nconst CLICKABLE_ELEMENT_SELECTORS = [\n 'a',\n 'button',\n '[role=\"button\"]',\n '[role=\"link\"]',\n '[role=\"menuitem\"]',\n '[role=\"menuitemcheckbox\"]',\n '[role=\"menuitemradio\"]',\n '[role=\"option\"]',\n '[role=\"tab\"]',\n '[role=\"treeitem\"]',\n '[contenteditable=\"true\" i]',\n];\n\n/**\n * Default CSS selectors for dead clicks tracking\n */\nexport const DEFAULT_DEAD_CLICK_ALLOWLIST = [\n 'input[type=\"button\"]',\n 'input[type=\"submit\"]',\n 'input[type=\"reset\"]',\n 'input[type=\"image\"]',\n 'input[type=\"file\"]',\n ...CLICKABLE_ELEMENT_SELECTORS,\n];\n\n/**\n * Default CSS selectors for rage clicks tracking\n */\nexport const DEFAULT_RAGE_CLICK_ALLOWLIST = ['*'];\n\n/**\n * Default time window for dead clicks (3 seconds)\n */\nexport const DEFAULT_DEAD_CLICK_WINDOW_MS = 3_000;\n\n/**\n * Default time window for rage clicks (1 second)\n */\nexport const DEFAULT_RAGE_CLICK_WINDOW_MS = 1_000;\n\n/**\n * Default threshold for rage clicks (4 clicks)\n */\nexport const DEFAULT_RAGE_CLICK_THRESHOLD = 4;\n\n/**\n * Default threshold for rage clicks to be considered out of bounds (50 pixels)\n */\nexport const DEFAULT_RAGE_CLICK_OUT_OF_BOUNDS_THRESHOLD = 50; // pixels\n\n// DomElement is [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) if the dom library is included in tsconfig.json\n// and never if it is not included\n// eslint-disable-next-line no-restricted-globals\ntype DomElement = typeof globalThis extends {\n Element: new (...args: any) => infer T;\n}\n ? T\n : never;\n"]}
@@ -1,11 +1,15 @@
1
1
  import { ILogger } from './logger';
2
- import { NetworkRequestEvent } from './network-request-event';
2
+ import { IRequestWrapper, NetworkRequestEvent, IResponseWrapper } from './network-request-event';
3
3
  export type NetworkEventCallbackFn = (event: NetworkRequestEvent) => void;
4
4
  export declare class NetworkEventCallback {
5
5
  readonly callback: (event: NetworkRequestEvent) => void;
6
6
  readonly id: string;
7
7
  constructor(callback: (event: NetworkRequestEvent) => void, id?: string);
8
8
  }
9
+ type RequestUrlAndMethod = {
10
+ url: string | URL | undefined;
11
+ method: string | undefined;
12
+ };
9
13
  export declare class NetworkObserver {
10
14
  private eventCallbacks;
11
15
  private globalScope?;
@@ -16,10 +20,22 @@ export declare class NetworkObserver {
16
20
  subscribe(eventCallback: NetworkEventCallback, logger?: ILogger): void;
17
21
  unsubscribe(eventCallback: NetworkEventCallback): void;
18
22
  protected triggerEventCallbacks(event: NetworkRequestEvent): void;
19
- private handleNetworkRequestEvent;
23
+ handleNetworkRequestEvent(requestType: 'fetch' | 'xhr', requestInfo: RequestInfo | URL | RequestUrlAndMethod | undefined, requestWrapper: IRequestWrapper | undefined, responseWrapper: IResponseWrapper | undefined, typedError: Error | undefined, startTime?: number, durationStart?: number): void;
20
24
  private getTimestamps;
21
25
  private observeFetch;
26
+ /**
27
+ * Creates a function that parses the response of an XMLHttpRequest as JSON.
28
+ *
29
+ * Returns function instead of JSON object to avoid unnecessary parsing if the
30
+ * body is not being captured.
31
+ *
32
+ * @param xhrSafe - The XMLHttpRequest object.
33
+ * @param context - The NetworkObserver instance.
34
+ * @returns A function that parses the response of an XMLHttpRequest as JSON.
35
+ */
36
+ static createXhrJsonParser(xhrUnsafe: XMLHttpRequest, context: NetworkObserver): () => any;
22
37
  private observeXhr;
23
38
  }
24
39
  export declare const networkObserver: NetworkObserver;
40
+ export {};
25
41
  //# sourceMappingURL=network-observer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"network-observer.d.ts","sourceRoot":"","sources":["../../src/network-observer.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AACnC,OAAO,EAEL,mBAAmB,EAQpB,MAAM,yBAAyB,CAAC;AAoBjC,MAAM,MAAM,sBAAsB,GAAG,CAAC,KAAK,EAAE,mBAAmB,KAAK,IAAI,CAAC;AAE1E,qBAAa,oBAAoB;aACH,QAAQ,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,IAAI;aAAkB,EAAE,EAAE,MAAM;gBAA1E,QAAQ,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,IAAI,EAAkB,EAAE,GAAE,MAAe;CAChH;AAoBD,qBAAa,eAAe;IAC1B,OAAO,CAAC,cAAc,CAAgD;IAEtE,OAAO,CAAC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,WAAW,CAAS;gBAChB,MAAM,CAAC,EAAE,OAAO;IAU5B,MAAM,CAAC,WAAW,IAAI,OAAO;IAK7B,SAAS,CAAC,aAAa,EAAE,oBAAoB,EAAE,MAAM,CAAC,EAAE,OAAO;IA+B/D,WAAW,CAAC,aAAa,EAAE,oBAAoB;IAI/C,SAAS,CAAC,qBAAqB,CAAC,KAAK,EAAE,mBAAmB;IAa1D,yBAAyB,CACvB,WAAW,EAAE,OAAO,GAAG,KAAK,EAC5B,WAAW,EAAE,WAAW,GAAG,GAAG,GAAG,mBAAmB,GAAG,SAAS,EAChE,cAAc,EAAE,eAAe,GAAG,SAAS,EAC3C,eAAe,EAAE,gBAAgB,GAAG,SAAS,EAC7C,UAAU,EAAE,KAAK,GAAG,SAAS,EAC7B,SAAS,CAAC,EAAE,MAAM,EAClB,aAAa,CAAC,EAAE,MAAM;IAiExB,OAAO,CAAC,aAAa;IAQrB,OAAO,CAAC,YAAY;IA8DpB;;;;;;;;;OASG;IACH,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,cAAc,EAAE,OAAO,EAAE,eAAe;IA8B9E,OAAO,CAAC,UAAU;CAqHnB;AAGD,eAAO,MAAM,eAAe,iBAAwB,CAAC"}
@@ -81,7 +81,7 @@ var NetworkObserver = /** @class */ (function () {
81
81
  });
82
82
  };
83
83
  NetworkObserver.prototype.handleNetworkRequestEvent = function (requestType, requestInfo, requestWrapper, responseWrapper, typedError, startTime, durationStart) {
84
- var _a;
84
+ var _a, _b;
85
85
  /* istanbul ignore next */
86
86
  if (startTime === undefined || durationStart === undefined) {
87
87
  // if we reach this point, it means that the performance API is not supported
@@ -98,6 +98,18 @@ var NetworkObserver = /** @class */ (function () {
98
98
  else {
99
99
  url = (_a = requestInfo === null || requestInfo === void 0 ? void 0 : requestInfo.toString) === null || _a === void 0 ? void 0 : _a.call(requestInfo);
100
100
  }
101
+ // strip basic auth from the URL
102
+ if (url) {
103
+ try {
104
+ var parsedUrl = new URL(url);
105
+ // reconstruct the URL without the basic auth
106
+ url = "".concat(parsedUrl.protocol, "//").concat(parsedUrl.host).concat(parsedUrl.pathname).concat(parsedUrl.search).concat(parsedUrl.hash);
107
+ }
108
+ catch (err) {
109
+ /* istanbul ignore next */
110
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.error('an unexpected error occurred while parsing the URL', err);
111
+ }
112
+ }
101
113
  method = (requestWrapper === null || requestWrapper === void 0 ? void 0 : requestWrapper.method) || method;
102
114
  var status, error;
103
115
  if (responseWrapper) {
@@ -189,6 +201,46 @@ var NetworkObserver = /** @class */ (function () {
189
201
  });
190
202
  }); };
191
203
  };
204
+ /**
205
+ * Creates a function that parses the response of an XMLHttpRequest as JSON.
206
+ *
207
+ * Returns function instead of JSON object to avoid unnecessary parsing if the
208
+ * body is not being captured.
209
+ *
210
+ * @param xhrSafe - The XMLHttpRequest object.
211
+ * @param context - The NetworkObserver instance.
212
+ * @returns A function that parses the response of an XMLHttpRequest as JSON.
213
+ */
214
+ NetworkObserver.createXhrJsonParser = function (xhrUnsafe, context) {
215
+ return function () {
216
+ var _a, _b;
217
+ try {
218
+ if (xhrUnsafe.responseType === 'json') {
219
+ // if response is a JS object, clone it so that subscribers can't mutate it
220
+ if ((_a = context.globalScope) === null || _a === void 0 ? void 0 : _a.structuredClone) {
221
+ /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */
222
+ return context.globalScope.structuredClone(xhrUnsafe.response);
223
+ }
224
+ }
225
+ else if (['text', ''].includes(xhrUnsafe.responseType)) {
226
+ // if response is a string, parse it as JSON
227
+ /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */
228
+ return JSON.parse(xhrUnsafe.responseText);
229
+ }
230
+ }
231
+ catch (err) {
232
+ /* istanbul ignore if */
233
+ if (err instanceof Error && err.name === 'InvalidStateError') {
234
+ // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText#exceptions
235
+ // if we reach here, it means we don't handle responseType correctly
236
+ (_b = context.logger) === null || _b === void 0 ? void 0 : _b.error("unexpected error when retrieving responseText. responseType='".concat(xhrUnsafe.responseType, "'"));
237
+ }
238
+ // the other possible error is Json Parse error which we fail silently
239
+ return null;
240
+ }
241
+ return null;
242
+ };
243
+ };
192
244
  NetworkObserver.prototype.observeXhr = function (originalXhrOpen, originalXhrSend, originalXhrSetRequestHeader) {
193
245
  /* istanbul ignore next */
194
246
  if (!this.globalScope || !originalXhrOpen || !originalXhrSend) {
@@ -216,7 +268,7 @@ var NetworkObserver = /** @class */ (function () {
216
268
  }
217
269
  catch (err) {
218
270
  /* istanbul ignore next */
219
- (_b = networkObserverContext.logger) === null || _b === void 0 ? void 0 : _b.debug('an unexpected error occurred while calling xhr open', err);
271
+ (_b = networkObserverContext.logger) === null || _b === void 0 ? void 0 : _b.error('an unexpected error occurred while calling xhr open', err);
220
272
  }
221
273
  // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
222
274
  return originalXhrOpen.apply(xhrSafe, args);
@@ -235,7 +287,9 @@ var NetworkObserver = /** @class */ (function () {
235
287
  args[_i] = arguments[_i];
236
288
  }
237
289
  // eslint-disable-next-line @typescript-eslint/no-this-alias
238
- var xhrSafe = this;
290
+ var xhrUnsafe = this;
291
+ var xhrSafe = xhrUnsafe;
292
+ var getJson = NetworkObserver.createXhrJsonParser(xhrUnsafe, networkObserverContext);
239
293
  var body = args[0];
240
294
  var requestEvent = xhrSafe.$$AmplitudeAnalyticsEvent;
241
295
  xhrSafe.addEventListener('loadend', function () {
@@ -245,7 +299,7 @@ var NetworkObserver = /** @class */ (function () {
245
299
  var responseBodySize = xhrSafe.getResponseHeader('content-length');
246
300
  var responseWrapper = new ResponseWrapperXhr(xhrSafe.status, responseHeaders,
247
301
  /* istanbul ignore next */
248
- responseBodySize ? parseInt(responseBodySize, 10) : undefined, xhrSafe.responseText);
302
+ responseBodySize ? parseInt(responseBodySize, 10) : undefined, getJson);
249
303
  var requestHeaders = xhrSafe.$$AmplitudeAnalyticsEvent.headers;
250
304
  var requestWrapper = new RequestWrapperXhr(body, requestHeaders);
251
305
  requestEvent.status = xhrSafe.status;
@@ -253,7 +307,7 @@ var NetworkObserver = /** @class */ (function () {
253
307
  }
254
308
  catch (err) {
255
309
  /* istanbul ignore next */
256
- (_a = networkObserverContext.logger) === null || _a === void 0 ? void 0 : _a.debug('an unexpected error occurred while handling xhr send', err);
310
+ (_a = networkObserverContext.logger) === null || _a === void 0 ? void 0 : _a.error('an unexpected error occurred while handling xhr send', err);
257
311
  }
258
312
  });
259
313
  /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */
@@ -276,7 +330,7 @@ var NetworkObserver = /** @class */ (function () {
276
330
  }
277
331
  catch (err) {
278
332
  /* istanbul ignore next */
279
- (_a = networkObserverContext.logger) === null || _a === void 0 ? void 0 : _a.debug('an unexpected error occurred while calling xhr setRequestHeader', err);
333
+ (_a = networkObserverContext.logger) === null || _a === void 0 ? void 0 : _a.error('an unexpected error occurred while calling xhr setRequestHeader', err);
280
334
  }
281
335
  /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */
282
336
  originalXhrSetRequestHeader.apply(xhrSafe, [headerName, headerValue]);
@@ -1 +1 @@
1
- {"version":3,"file":"network-observer.js","sourceRoot":"","sources":["../../src/network-observer.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,IAAI,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAEpC,OAAO,EAEL,mBAAmB,EACnB,mBAAmB,EACnB,oBAAoB,EACpB,iBAAiB,EACjB,kBAAkB,GAInB,MAAM,yBAAyB,CAAC;AAajC;;GAEG;AACH,SAAS,SAAS,CAAC,WAAgB;IACjC,OAAO,OAAO,WAAW,KAAK,QAAQ,IAAI,WAAW,KAAK,IAAI,IAAI,KAAK,IAAI,WAAW,IAAI,QAAQ,IAAI,WAAW,CAAC;AACpH,CAAC;AAID;IACE,8BAA4B,QAA8C,EAAkB,EAAmB;QAAnB,mBAAA,EAAA,KAAa,IAAI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W,CAAC,CAAC;QACrD,CAAC,CAAC;QAEF;;;;;WAKG;QACH,oEAAoE;QACpE,oEAAoE;QACpE,QAAQ,CAAC,gBAAgB,GAAG,UAAU,UAAe,EAAE,WAAgB;;YACrE,IAAM,OAAO,GAAG,IAA8C,CAAC;YAC/D,IAAI;gBACF,sEAAsE;gBACtE,OAAO,CAAC,yBAAyB,CAAC,OAAO,CAAC,UAAoB,CAAC,GAAG,WAAqB,CAAC;aACzF;YAAC,OAAO,GAAG,EAAE;gBACZ,0BAA0B;gBAC1B,MAAA,sBAAsB,CAAC,MAAM,0CAAE,KAAK,CAAC,iEAAiE,EAAE,GAAG,CAAC,CAAC;aAC9G;YACD,oEAAoE;YACpE,2BAA2B,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC,CAAC;QACxE,CAAC,CAAC;IACJ,CAAC;IACH,sBAAC;AAAD,CAAC,AAzTD,IAyTC;;AAED,wCAAwC;AACxC,MAAM,CAAC,IAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC","sourcesContent":["import { getGlobalScope } from './';\nimport { UUID } from './utils/uuid';\nimport { ILogger } from './logger';\nimport {\n IRequestWrapper,\n NetworkRequestEvent,\n RequestWrapperFetch,\n ResponseWrapperFetch,\n RequestWrapperXhr,\n ResponseWrapperXhr,\n IResponseWrapper,\n RequestInitSafe,\n XMLHttpRequestBodyInitSafe,\n} from './network-request-event';\n\n// object that is added to each XHR instance so\n// that info can be set in xhr.open and retrieved in xhr.send\ntype AmplitudeAnalyticsEvent = {\n method: string;\n url: string | URL;\n startTime: number;\n durationStart: number;\n status?: number;\n headers: Record<string, string>;\n};\n\n/**\n * Typeguard function checks if an input is a Request object.\n */\nfunction isRequest(requestInfo: any): requestInfo is Request {\n return typeof requestInfo === 'object' && requestInfo !== null && 'url' in requestInfo && 'method' in requestInfo;\n}\n\nexport type NetworkEventCallbackFn = (event: NetworkRequestEvent) => void;\n\nexport class NetworkEventCallback {\n constructor(public readonly callback: (event: NetworkRequestEvent) => void, public readonly id: string = UUID()) {}\n}\n\ntype RequestUrlAndMethod = {\n url: string | URL | undefined;\n method: string | undefined;\n};\n\n// A narrowed down [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) type\n// that only includes the properties we need to access and adds the $$AmplitudeAnalyticsEvent property\n// Use great care when modifying this type, make sure you only use read-only properties and only add\n// what you need to access, nothing more.\ntype AmplitudeXMLHttpRequestSafe = {\n $$AmplitudeAnalyticsEvent: AmplitudeAnalyticsEvent;\n status: number;\n responseText: string;\n getAllResponseHeaders: typeof XMLHttpRequest.prototype.getAllResponseHeaders;\n getResponseHeader: typeof XMLHttpRequest.prototype.getResponseHeader;\n addEventListener: (type: 'loadend', listener: () => void) => void;\n};\n\nexport class NetworkObserver {\n private eventCallbacks: Map<string, NetworkEventCallback> = new Map();\n // eslint-disable-next-line no-restricted-globals\n private globalScope?: typeof globalThis;\n private logger?: ILogger;\n private isObserving = false;\n constructor(logger?: ILogger) {\n this.logger = logger;\n const globalScope = getGlobalScope();\n if (!NetworkObserver.isSupported()) {\n /* istanbul ignore next */\n return;\n }\n this.globalScope = globalScope;\n }\n\n static isSupported(): boolean {\n const globalScope = getGlobalScope();\n return !!globalScope && !!globalScope.fetch;\n }\n\n subscribe(eventCallback: NetworkEventCallback, logger?: ILogger) {\n if (!this.logger) {\n this.logger = logger;\n }\n this.eventCallbacks.set(eventCallback.id, eventCallback);\n if (!this.isObserving) {\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrOpen = this.globalScope?.XMLHttpRequest?.prototype?.open;\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrSend = this.globalScope?.XMLHttpRequest?.prototype?.send;\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrSetRequestHeader = this.globalScope?.XMLHttpRequest?.prototype?.setRequestHeader;\n if (originalXhrOpen && originalXhrSend && originalXhrSetRequestHeader) {\n this.observeXhr(originalXhrOpen, originalXhrSend, originalXhrSetRequestHeader);\n }\n\n /* istanbul ignore next */\n const originalFetch = this.globalScope?.fetch;\n /* istanbul ignore next */\n if (originalFetch) {\n this.observeFetch(originalFetch);\n }\n\n /* istanbul ignore next */\n this.isObserving = true;\n }\n }\n\n unsubscribe(eventCallback: NetworkEventCallback) {\n this.eventCallbacks.delete(eventCallback.id);\n }\n\n protected triggerEventCallbacks(event: NetworkRequestEvent) {\n this.eventCallbacks.forEach((callback) => {\n try {\n callback.callback(event);\n } catch (err) {\n // if the callback throws an error, we should catch it\n // to avoid breaking the fetch promise chain\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while triggering event callbacks', err);\n }\n });\n }\n\n private handleNetworkRequestEvent(\n requestType: 'fetch' | 'xhr',\n requestInfo: RequestInfo | URL | RequestUrlAndMethod | undefined,\n requestWrapper: IRequestWrapper | undefined,\n responseWrapper: IResponseWrapper | undefined,\n typedError: Error | undefined,\n startTime?: number,\n durationStart?: number,\n ) {\n /* istanbul ignore next */\n if (startTime === undefined || durationStart === undefined) {\n // if we reach this point, it means that the performance API is not supported\n // so we can't construct a NetworkRequestEvent\n return;\n }\n\n // parse the URL and Method\n let url: string | undefined;\n let method = 'GET';\n if (isRequest(requestInfo)) {\n url = requestInfo['url'];\n method = requestInfo['method'];\n } else {\n url = requestInfo?.toString?.();\n }\n method = requestWrapper?.method || method;\n\n let status, error;\n if (responseWrapper) {\n status = responseWrapper.status;\n }\n\n if (typedError) {\n error = {\n name: typedError.name || 'UnknownError',\n message: typedError.message || 'An unknown error occurred',\n };\n status = 0;\n }\n\n const duration = Math.floor(performance.now() - durationStart);\n const endTime = Math.floor(startTime + duration);\n\n const requestEvent = new NetworkRequestEvent(\n requestType,\n method,\n startTime, // timestamp and startTime are aliases\n startTime,\n url,\n requestWrapper,\n status,\n duration,\n responseWrapper,\n error,\n endTime,\n );\n\n this.triggerEventCallbacks(requestEvent);\n }\n\n private getTimestamps() {\n /* istanbul ignore next */\n return {\n startTime: Date.now?.(),\n durationStart: performance?.now?.(),\n };\n }\n\n private observeFetch(\n originalFetch: (requestInfo: RequestInfo | URL, requestInit?: RequestInit) => Promise<Response>,\n ) {\n /* istanbul ignore next */\n if (!this.globalScope || !originalFetch) {\n return;\n }\n /**\n * IMPORTANT: This overrides window.fetch in browsers.\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of fetch\n * and make sure another developer who is an expert reviews this change throughly\n */\n this.globalScope.fetch = async (requestInfo?: RequestInfo | URL, requestInit?: RequestInit) => {\n // 1: capture the start time and duration start time before the fetch call\n let timestamps;\n try {\n timestamps = this.getTimestamps();\n } catch (error) {\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while retrieving timestamps', error);\n }\n\n // 2. make the call to the original fetch and preserve the response or error\n let originalResponse, originalError;\n try {\n originalResponse = await originalFetch(requestInfo as RequestInfo | URL, requestInit);\n } catch (err) {\n // Capture error information\n originalError = err;\n }\n\n // 3. call the handler after the fetch call is done\n try {\n this.handleNetworkRequestEvent(\n 'fetch',\n requestInfo,\n requestInit ? new RequestWrapperFetch(requestInit as RequestInitSafe) : undefined,\n originalResponse ? new ResponseWrapperFetch(originalResponse) : undefined,\n originalError as Error,\n /* istanbul ignore next */\n timestamps?.startTime,\n /* istanbul ignore next */\n timestamps?.durationStart,\n );\n } catch (err) {\n // this catch shouldn't be reachable, but keep it here for safety\n // because we're overriding the fetch function and better to be safe than sorry\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while handling fetch', err);\n }\n\n // 4. return the original response or throw the original error\n if (originalResponse) {\n // if the response is not undefined, return it\n return originalResponse;\n } else {\n throw originalError;\n }\n };\n }\n\n private observeXhr(\n originalXhrOpen:\n | ((\n method: string,\n url: string | URL,\n async?: boolean,\n username?: string | null,\n password?: string | null,\n ) => void)\n | undefined,\n originalXhrSend: ((body?: Document | XMLHttpRequestBodyInit | null) => void) | undefined,\n originalXhrSetRequestHeader: (headerName: string, headerValue: string) => void,\n ) {\n /* istanbul ignore next */\n if (!this.globalScope || !originalXhrOpen || !originalXhrSend) {\n return;\n }\n\n const xhrProto = this.globalScope.XMLHttpRequest.prototype;\n\n const networkObserverContext = this as NetworkObserver;\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.open\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.open\n * and make sure another developer who is an expert reviews this change throughly\n */\n xhrProto.open = function (...args: any[]) {\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n const [method, url] = args as [string, string | URL];\n try {\n /* istanbul ignore next */\n xhrSafe.$$AmplitudeAnalyticsEvent = {\n method,\n url: url?.toString?.(),\n headers: {},\n ...networkObserverContext.getTimestamps(),\n } as AmplitudeAnalyticsEvent;\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.debug('an unexpected error occurred while calling xhr open', err);\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return originalXhrOpen.apply(xhrSafe, args as any);\n };\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.send\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.send\n * and make sure another developer who is an expert reviews this change throughly\n */\n // allow \"any\" type for args to reflect how it's used in the browser\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n xhrProto.send = function (...args: any[]) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n const body = args[0] as XMLHttpRequestBodyInitSafe;\n const requestEvent = xhrSafe.$$AmplitudeAnalyticsEvent;\n\n xhrSafe.addEventListener('loadend', function () {\n try {\n const responseHeaders = xhrSafe.getAllResponseHeaders();\n const responseBodySize = xhrSafe.getResponseHeader('content-length');\n const responseWrapper = new ResponseWrapperXhr(\n xhrSafe.status,\n responseHeaders,\n /* istanbul ignore next */\n responseBodySize ? parseInt(responseBodySize, 10) : undefined,\n xhrSafe.responseText,\n );\n const requestHeaders = xhrSafe.$$AmplitudeAnalyticsEvent.headers;\n const requestWrapper = new RequestWrapperXhr(body, requestHeaders);\n requestEvent.status = xhrSafe.status;\n networkObserverContext.handleNetworkRequestEvent(\n 'xhr',\n { url: requestEvent.url, method: requestEvent.method },\n requestWrapper,\n responseWrapper,\n undefined,\n requestEvent.startTime,\n requestEvent.durationStart,\n );\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.debug('an unexpected error occurred while handling xhr send', err);\n }\n });\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n return originalXhrSend.apply(xhrSafe, args as any);\n };\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.setRequestHeader\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.setRequestHeader\n * and make sure another developer who is an expert reviews this change throughly\n */\n // allow \"any\" type for args to reflect how it's used in the browser\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n xhrProto.setRequestHeader = function (headerName: any, headerValue: any) {\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n try {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-assignment */\n xhrSafe.$$AmplitudeAnalyticsEvent.headers[headerName as string] = headerValue as string;\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.debug('an unexpected error occurred while calling xhr setRequestHeader', err);\n }\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n originalXhrSetRequestHeader.apply(xhrSafe, [headerName, headerValue]);\n };\n }\n}\n\n// singleton instance of NetworkObserver\nexport const networkObserver = new NetworkObserver();\n"]}
1
+ {"version":3,"file":"network-observer.js","sourceRoot":"","sources":["../../src/network-observer.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,IAAI,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAEpC,OAAO,EAEL,mBAAmB,EACnB,mBAAmB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,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;oBACrC,sBAAsB,CAAC,yBAAyB,CAC9C,KAAK,EACL,EAAE,GAAG,EAAE,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,YAAY,CAAC,MAAM,EAAE,EACtD,cAAc,EACd,eAAe,EACf,SAAS,EACT,YAAY,CAAC,SAAS,EACtB,YAAY,CAAC,aAAa,CAC3B,CAAC;iBACH;gBAAC,OAAO,GAAG,EAAE;oBACZ,0BAA0B;oBAC1B,MAAA,sBAAsB,CAAC,MAAM,0CAAE,KAAK,CAAC,sDAAsD,EAAE,GAAG,CAAC,CAAC;iBACnG;YACH,CAAC,CAAC,CAAC;YACH,oEAAoE;YACpE,OAAO,eAAe,CAAC,KAAK,CAAC,OAAO,EAAE,IAAW,CAAC,CAAC;QACrD,CAAC,CAAC;QAEF;;;;;WAKG;QACH,oEAAoE;QACpE,oEAAoE;QACpE,QAAQ,CAAC,gBAAgB,GAAG,UAAU,UAAe,EAAE,WAAgB;;YACrE,IAAM,OAAO,GAAG,IAA8C,CAAC;YAC/D,IAAI;gBACF,sEAAsE;gBACtE,OAAO,CAAC,yBAAyB,CAAC,OAAO,CAAC,UAAoB,CAAC,GAAG,WAAqB,CAAC;aACzF;YAAC,OAAO,GAAG,EAAE;gBACZ,0BAA0B;gBAC1B,MAAA,sBAAsB,CAAC,MAAM,0CAAE,KAAK,CAAC,iEAAiE,EAAE,GAAG,CAAC,CAAC;aAC9G;YACD,oEAAoE;YACpE,2BAA2B,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC,CAAC;QACxE,CAAC,CAAC;IACJ,CAAC;IACH,sBAAC;AAAD,CAAC,AAhXD,IAgXC;;AAED,wCAAwC;AACxC,MAAM,CAAC,IAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC","sourcesContent":["import { getGlobalScope } from './';\nimport { UUID } from './utils/uuid';\nimport { ILogger } from './logger';\nimport {\n IRequestWrapper,\n NetworkRequestEvent,\n RequestWrapperFetch,\n ResponseWrapperFetch,\n RequestWrapperXhr,\n ResponseWrapperXhr,\n IResponseWrapper,\n RequestInitSafe,\n XMLHttpRequestBodyInitSafe,\n} from './network-request-event';\n\n// object that is added to each XHR instance so\n// that info can be set in xhr.open and retrieved in xhr.send\ntype AmplitudeAnalyticsEvent = {\n method: string;\n url: string | URL;\n startTime: number;\n durationStart: number;\n status?: number;\n headers: Record<string, string>;\n};\n\n/**\n * Typeguard function checks if an input is a Request object.\n */\nfunction isRequest(requestInfo: any): requestInfo is Request {\n return typeof requestInfo === 'object' && requestInfo !== null && 'url' in requestInfo && 'method' in requestInfo;\n}\n\nexport type NetworkEventCallbackFn = (event: NetworkRequestEvent) => void;\n\nexport class NetworkEventCallback {\n constructor(public readonly callback: (event: NetworkRequestEvent) => void, public readonly id: string = UUID()) {}\n}\n\ntype RequestUrlAndMethod = {\n url: string | URL | undefined;\n method: string | undefined;\n};\n\n// A narrowed down [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) type\n// that only includes the properties we need to access and adds the $$AmplitudeAnalyticsEvent property\n// Use great care when modifying this type, make sure you only use read-only properties and only add\n// what you need to access, nothing more.\ntype AmplitudeXMLHttpRequestSafe = {\n $$AmplitudeAnalyticsEvent: AmplitudeAnalyticsEvent;\n status: number;\n responseText: string;\n responseType: XMLHttpRequestResponseType;\n getAllResponseHeaders: typeof XMLHttpRequest.prototype.getAllResponseHeaders;\n getResponseHeader: typeof XMLHttpRequest.prototype.getResponseHeader;\n addEventListener: (type: 'loadend', listener: () => void) => void;\n};\n\nexport class NetworkObserver {\n private eventCallbacks: Map<string, NetworkEventCallback> = new Map();\n // eslint-disable-next-line no-restricted-globals\n private globalScope?: typeof globalThis;\n private logger?: ILogger;\n private isObserving = false;\n constructor(logger?: ILogger) {\n this.logger = logger;\n const globalScope = getGlobalScope();\n if (!NetworkObserver.isSupported()) {\n /* istanbul ignore next */\n return;\n }\n this.globalScope = globalScope;\n }\n\n static isSupported(): boolean {\n const globalScope = getGlobalScope();\n return !!globalScope && !!globalScope.fetch;\n }\n\n subscribe(eventCallback: NetworkEventCallback, logger?: ILogger) {\n if (!this.logger) {\n this.logger = logger;\n }\n this.eventCallbacks.set(eventCallback.id, eventCallback);\n if (!this.isObserving) {\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrOpen = this.globalScope?.XMLHttpRequest?.prototype?.open;\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrSend = this.globalScope?.XMLHttpRequest?.prototype?.send;\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrSetRequestHeader = this.globalScope?.XMLHttpRequest?.prototype?.setRequestHeader;\n if (originalXhrOpen && originalXhrSend && originalXhrSetRequestHeader) {\n this.observeXhr(originalXhrOpen, originalXhrSend, originalXhrSetRequestHeader);\n }\n\n /* istanbul ignore next */\n const originalFetch = this.globalScope?.fetch;\n /* istanbul ignore next */\n if (originalFetch) {\n this.observeFetch(originalFetch);\n }\n\n /* istanbul ignore next */\n this.isObserving = true;\n }\n }\n\n unsubscribe(eventCallback: NetworkEventCallback) {\n this.eventCallbacks.delete(eventCallback.id);\n }\n\n protected triggerEventCallbacks(event: NetworkRequestEvent) {\n this.eventCallbacks.forEach((callback) => {\n try {\n callback.callback(event);\n } catch (err) {\n // if the callback throws an error, we should catch it\n // to avoid breaking the fetch promise chain\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while triggering event callbacks', err);\n }\n });\n }\n\n handleNetworkRequestEvent(\n requestType: 'fetch' | 'xhr',\n requestInfo: RequestInfo | URL | RequestUrlAndMethod | undefined,\n requestWrapper: IRequestWrapper | undefined,\n responseWrapper: IResponseWrapper | undefined,\n typedError: Error | undefined,\n startTime?: number,\n durationStart?: number,\n ) {\n /* istanbul ignore next */\n if (startTime === undefined || durationStart === undefined) {\n // if we reach this point, it means that the performance API is not supported\n // so we can't construct a NetworkRequestEvent\n return;\n }\n\n // parse the URL and Method\n let url: string | undefined;\n let method = 'GET';\n if (isRequest(requestInfo)) {\n url = requestInfo['url'];\n method = requestInfo['method'];\n } else {\n url = requestInfo?.toString?.();\n }\n\n // strip basic auth from the URL\n if (url) {\n try {\n const parsedUrl = new URL(url);\n // reconstruct the URL without the basic auth\n url = `${parsedUrl.protocol}//${parsedUrl.host}${parsedUrl.pathname}${parsedUrl.search}${parsedUrl.hash}`;\n } catch (err) {\n /* istanbul ignore next */\n this.logger?.error('an unexpected error occurred while parsing the URL', err);\n }\n }\n method = requestWrapper?.method || method;\n\n let status, error;\n if (responseWrapper) {\n status = responseWrapper.status;\n }\n\n if (typedError) {\n error = {\n name: typedError.name || 'UnknownError',\n message: typedError.message || 'An unknown error occurred',\n };\n status = 0;\n }\n\n const duration = Math.floor(performance.now() - durationStart);\n const endTime = Math.floor(startTime + duration);\n\n const requestEvent = new NetworkRequestEvent(\n requestType,\n method,\n startTime, // timestamp and startTime are aliases\n startTime,\n url,\n requestWrapper,\n status,\n duration,\n responseWrapper,\n error,\n endTime,\n );\n\n this.triggerEventCallbacks(requestEvent);\n }\n\n private getTimestamps() {\n /* istanbul ignore next */\n return {\n startTime: Date.now?.(),\n durationStart: performance?.now?.(),\n };\n }\n\n private observeFetch(\n originalFetch: (requestInfo: RequestInfo | URL, requestInit?: RequestInit) => Promise<Response>,\n ) {\n /* istanbul ignore next */\n if (!this.globalScope || !originalFetch) {\n return;\n }\n /**\n * IMPORTANT: This overrides window.fetch in browsers.\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of fetch\n * and make sure another developer who is an expert reviews this change throughly\n */\n this.globalScope.fetch = async (requestInfo?: RequestInfo | URL, requestInit?: RequestInit) => {\n // 1: capture the start time and duration start time before the fetch call\n let timestamps;\n try {\n timestamps = this.getTimestamps();\n } catch (error) {\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while retrieving timestamps', error);\n }\n\n // 2. make the call to the original fetch and preserve the response or error\n let originalResponse, originalError;\n try {\n originalResponse = await originalFetch(requestInfo as RequestInfo | URL, requestInit);\n } catch (err) {\n // Capture error information\n originalError = err;\n }\n\n // 3. call the handler after the fetch call is done\n try {\n this.handleNetworkRequestEvent(\n 'fetch',\n requestInfo,\n requestInit ? new RequestWrapperFetch(requestInit as RequestInitSafe) : undefined,\n originalResponse ? new ResponseWrapperFetch(originalResponse) : undefined,\n originalError as Error,\n /* istanbul ignore next */\n timestamps?.startTime,\n /* istanbul ignore next */\n timestamps?.durationStart,\n );\n } catch (err) {\n // this catch shouldn't be reachable, but keep it here for safety\n // because we're overriding the fetch function and better to be safe than sorry\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while handling fetch', err);\n }\n\n // 4. return the original response or throw the original error\n if (originalResponse) {\n // if the response is not undefined, return it\n return originalResponse;\n } else {\n throw originalError;\n }\n };\n }\n\n /**\n * Creates a function that parses the response of an XMLHttpRequest as JSON.\n *\n * Returns function instead of JSON object to avoid unnecessary parsing if the\n * body is not being captured.\n *\n * @param xhrSafe - The XMLHttpRequest object.\n * @param context - The NetworkObserver instance.\n * @returns A function that parses the response of an XMLHttpRequest as JSON.\n */\n static createXhrJsonParser(xhrUnsafe: XMLHttpRequest, context: NetworkObserver) {\n return () => {\n try {\n if (xhrUnsafe.responseType === 'json') {\n // if response is a JS object, clone it so that subscribers can't mutate it\n if (context.globalScope?.structuredClone) {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */\n return context.globalScope.structuredClone(xhrUnsafe.response);\n }\n } else if (['text', ''].includes(xhrUnsafe.responseType)) {\n // if response is a string, parse it as JSON\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */\n return JSON.parse(xhrUnsafe.responseText);\n }\n } catch (err) {\n /* istanbul ignore if */\n if (err instanceof Error && err.name === 'InvalidStateError') {\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText#exceptions\n // if we reach here, it means we don't handle responseType correctly\n context.logger?.error(\n `unexpected error when retrieving responseText. responseType='${xhrUnsafe.responseType}'`,\n );\n }\n // the other possible error is Json Parse error which we fail silently\n return null;\n }\n return null;\n };\n }\n\n private observeXhr(\n originalXhrOpen:\n | ((\n method: string,\n url: string | URL,\n async?: boolean,\n username?: string | null,\n password?: string | null,\n ) => void)\n | undefined,\n originalXhrSend: ((body?: Document | XMLHttpRequestBodyInit | null) => void) | undefined,\n originalXhrSetRequestHeader: (headerName: string, headerValue: string) => void,\n ) {\n /* istanbul ignore next */\n if (!this.globalScope || !originalXhrOpen || !originalXhrSend) {\n return;\n }\n\n const xhrProto = this.globalScope.XMLHttpRequest.prototype;\n\n const networkObserverContext = this as NetworkObserver;\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.open\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.open\n * and make sure another developer who is an expert reviews this change throughly\n */\n xhrProto.open = function (...args: any[]) {\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n const [method, url] = args as [string, string | URL];\n try {\n /* istanbul ignore next */\n xhrSafe.$$AmplitudeAnalyticsEvent = {\n method,\n url: url?.toString?.(),\n headers: {},\n ...networkObserverContext.getTimestamps(),\n } as AmplitudeAnalyticsEvent;\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.error('an unexpected error occurred while calling xhr open', err);\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return originalXhrOpen.apply(xhrSafe, args as any);\n };\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.send\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.send\n * and make sure another developer who is an expert reviews this change throughly\n */\n // allow \"any\" type for args to reflect how it's used in the browser\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n xhrProto.send = function (...args: any[]) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhrUnsafe = this;\n const xhrSafe = xhrUnsafe as unknown as AmplitudeXMLHttpRequestSafe;\n const getJson = NetworkObserver.createXhrJsonParser(xhrUnsafe, networkObserverContext);\n const body = args[0] as XMLHttpRequestBodyInitSafe;\n const requestEvent = xhrSafe.$$AmplitudeAnalyticsEvent;\n\n xhrSafe.addEventListener('loadend', function () {\n try {\n const responseHeaders = xhrSafe.getAllResponseHeaders();\n const responseBodySize = xhrSafe.getResponseHeader('content-length');\n\n const responseWrapper = new ResponseWrapperXhr(\n xhrSafe.status,\n responseHeaders,\n /* istanbul ignore next */\n responseBodySize ? parseInt(responseBodySize, 10) : undefined,\n getJson,\n );\n const requestHeaders = xhrSafe.$$AmplitudeAnalyticsEvent.headers;\n const requestWrapper = new RequestWrapperXhr(body, requestHeaders);\n requestEvent.status = xhrSafe.status;\n networkObserverContext.handleNetworkRequestEvent(\n 'xhr',\n { url: requestEvent.url, method: requestEvent.method },\n requestWrapper,\n responseWrapper,\n undefined,\n requestEvent.startTime,\n requestEvent.durationStart,\n );\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.error('an unexpected error occurred while handling xhr send', err);\n }\n });\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n return originalXhrSend.apply(xhrSafe, args as any);\n };\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.setRequestHeader\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.setRequestHeader\n * and make sure another developer who is an expert reviews this change throughly\n */\n // allow \"any\" type for args to reflect how it's used in the browser\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n xhrProto.setRequestHeader = function (headerName: any, headerValue: any) {\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n try {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-assignment */\n xhrSafe.$$AmplitudeAnalyticsEvent.headers[headerName as string] = headerValue as string;\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.error('an unexpected error occurred while calling xhr setRequestHeader', err);\n }\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n originalXhrSetRequestHeader.apply(xhrSafe, [headerName, headerValue]);\n };\n }\n}\n\n// singleton instance of NetworkObserver\nexport const networkObserver = new NetworkObserver();\n"]}
@@ -104,7 +104,6 @@ export interface IResponseWrapper {
104
104
  bodySize?: number;
105
105
  status?: number;
106
106
  body?: string | Blob | ReadableStream | ArrayBuffer | FormDataSafe | URLSearchParams | ArrayBufferView | null;
107
- text: () => Promise<string | null>;
108
107
  json: (allow?: string[], exclude?: string[]) => Promise<JsonObject | null>;
109
108
  }
110
109
  /**
@@ -141,11 +140,10 @@ export declare class ResponseWrapperXhr implements IResponseWrapper {
141
140
  readonly statusCode: number;
142
141
  readonly headersString: string;
143
142
  readonly size: number | undefined;
144
- readonly responseText: string;
145
- constructor(statusCode: number, headersString: string, size: number | undefined, responseText: string);
143
+ readonly getJson: () => any | null;
144
+ constructor(statusCode: number, headersString: string, size: number | undefined, getJson: () => any | null);
146
145
  get bodySize(): number | undefined;
147
146
  get status(): number;
148
- text(): Promise<string | null>;
149
147
  headers(allow?: string[]): Record<string, string> | undefined;
150
148
  json(allow?: string[], exclude?: string[]): Promise<JsonObject | null>;
151
149
  }
@@ -1 +1 @@
1
- {"version":3,"file":"network-request-event.d.ts","sourceRoot":"","sources":["../../src/network-request-event.ts"],"names":[],"mappings":"AAQA,KAAK,QAAQ,GAAG;IACd,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,KAAK,eAAe,GAAG;IACrB,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,KAAK,mBAAmB,GAAG;IACzB,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,KAAK,mBAAmB,GAAG;IACzB,QAAQ,IAAI,MAAM,CAAC;CACpB,CAAC;AAKF,KAAK,sBAAsB,GAAG,MAAM,GAAG,QAAQ,GAAG,IAAI,CAAC;AAEvD,KAAK,YAAY,GACb,MAAM,GACN,IAAI,GACJ,eAAe,GACf,YAAY,GACZ,mBAAm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jB,MAAM,WAAW;CAClB;AAID;;;;;;;GAOG;AACH,eAAO,MAAM,YAAY,YACd,OAAO,MAAM,EAAE,MAAM,CAAC;;;MAK9B,OAAO,MAAM,EAAE,MAAM,CAqBvB,CAAC;AACF,qBAAa,mBAAmB;aAMZ,IAAI,EAAE,KAAK,GAAG,OAAO;aACrB,MAAM,EAAE,MAAM;aACd,SAAS,EAAE,MAAM;aACjB,SAAS,EAAE,MAAM;aACjB,GAAG,CAAC;aACJ,cAAc,CAAC;aACf,MAAM,EAAE,MAAM;aACd,QAAQ,CAAC;aACT,eAAe,CAAC;aAChB,KAAK,CAAC;cACd,MAAM;iBACH,MAAM;;aAED,OAAO,CAAC;IAlBnB,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACxC,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACzC,eAAe,CAAC,EAAE,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAAC;IAC7C,gBAAgB,CAAC,EAAE,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAAC;gBAEnC,IAAI,EAAE,KAAK,GAAG,OAAO,EACrB,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EACjB,GAAG,CAAC,oBAAQ,EACZ,cAAc,CAAC,6BAAiB,EAChC,MAAM,GAAE,MAAU,EAClB,QAAQ,CAAC,oBAAQ,EACjB,eAAe,CAAC,8BAAkB,EAClC,KAAK,CAAC;cACd,MAAM;iBACH,MAAM;iBAChB,EACe,OAAO,CAAC,oBAAQ;IAGlC,cAAc,IAAI,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;CAmBtC"}
1
+ {"version":3,"file":"network-request-event.d.ts","sourceRoot":"","sources":["../../src/network-request-event.ts"],"names":[],"mappings":"AAQA,KAAK,QAAQ,GAAG;IACd,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,KAAK,e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ACe,OAAO,CAAC,oBAAQ;IAGlC,cAAc,IAAI,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;CAmBtC"}
@@ -343,11 +343,11 @@ var ResponseWrapperFetch = /** @class */ (function () {
343
343
  }());
344
344
  export { ResponseWrapperFetch };
345
345
  var ResponseWrapperXhr = /** @class */ (function () {
346
- function ResponseWrapperXhr(statusCode, headersString, size, responseText) {
346
+ function ResponseWrapperXhr(statusCode, headersString, size, getJson) {
347
347
  this.statusCode = statusCode;
348
348
  this.headersString = headersString;
349
349
  this.size = size;
350
- this.responseText = responseText;
350
+ this.getJson = getJson;
351
351
  }
352
352
  Object.defineProperty(ResponseWrapperXhr.prototype, "bodySize", {
353
353
  get: function () {
@@ -363,14 +363,6 @@ var ResponseWrapperXhr = /** @class */ (function () {
363
363
  enumerable: false,
364
364
  configurable: true
365
365
  });
366
- ResponseWrapperXhr.prototype.text = function () {
367
- return __awaiter(this, void 0, void 0, function () {
368
- return __generator(this, function (_a) {
369
- // reject if body has already been consumed
370
- return [2 /*return*/, this.responseText];
371
- });
372
- });
373
- };
374
366
  ResponseWrapperXhr.prototype.headers = function (allow) {
375
367
  var e_3, _a;
376
368
  if (allow === void 0) { allow = []; }
@@ -401,18 +393,17 @@ var ResponseWrapperXhr = /** @class */ (function () {
401
393
  if (allow === void 0) { allow = []; }
402
394
  if (exclude === void 0) { exclude = []; }
403
395
  return __awaiter(this, void 0, void 0, function () {
404
- var text;
396
+ var jsonBody;
405
397
  return __generator(this, function (_a) {
406
- switch (_a.label) {
407
- case 0:
408
- if (allow.length === 0) {
409
- return [2 /*return*/, null];
410
- }
411
- return [4 /*yield*/, this.text()];
412
- case 1:
413
- text = _a.sent();
414
- return [2 /*return*/, safeParseAndPruneBody(text, allow, exclude)];
398
+ if (allow.length === 0) {
399
+ return [2 /*return*/, null];
400
+ }
401
+ jsonBody = this.getJson();
402
+ if (jsonBody) {
403
+ pruneJson(jsonBody, allow, exclude);
404
+ return [2 /*return*/, jsonBody];
415
405
  }
406
+ return [2 /*return*/, null];
416
407
  });
417
408
  });
418
409
  };
@@ -1 +1 @@
1
- {"version":3,"file":"network-request-event.js","sourceRoot":"","sources":["../../src/network-request-event.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,IAAI,CAAC;AA2DrD,IAAM,iBAAiB,GAAG,GAAG,CAAC;AAmC9B,MAAM,CAAC,IAAM,eAAe,GAAG,GAAG,CAAC;AAEnC;;;;;;;;;;;;;;;;;GAiBG;AACH;IAEE,6BAAoB,OAAwB;QAAxB,YAAO,GAAP,OAAO,CAAiB;IAAG,CAAC;IAEhD,qCAAO,GAAP,UAAQ,KAAoB;;QAApB,sBAAA,EAAA,UAAoB;QAC1B,IAAM,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;QAE3C,qCAAqC;QACrC,IAAM,eAAe,GAA2B,EAAE,CAAC;QACnD,IAAI,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE;YAChC,aAAa,CAAC,OAAO,CAAC,UAAC,EAAyB;oBAAzB,KAAA,aAAyB,EAAxB,UAAU,QAAA,EAAE,WAAW,QAAA;gBAC7C,eAAe,CAAC,UAAU,CAAC,GAAG,WAAW,CAAC;YAC5C,CAAC,CAAC,CAAC;SACJ;aAAM,IAAI,aAAa,YAAY,OAAO,EAAE;YAC3C,aAAa,CAAC,OAAO,CAAC,UAAC,KAAa,EAAE,GAAW;gBAC/C,eAAe,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;YAC/B,CAAC,CAAC,CAAC;SACJ;aAAM,IAAI,OAAO,aAAa,KAAK,QAAQ,IAAI,aAAa,KAAK,IAAI,EAAE;;gBACtE,KAA2B,IAAA,KAAA,SAAA,MAAM,CAAC,OAAO,CAAC,aAAuC,CAAC,CAAA,g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Ae,GAAf,eAAe,CAAmB;QAClC,UAAK,GAAL,KAAK,CAGpB;QACe,YAAO,GAAP,OAAO,CAAS;IAC/B,CAAC;IAEJ,4CAAc,GAAd;;QACE,IAAM,UAAU,GAAwB;YACtC,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,GAAG,EAAE,IAAI,CAAC,GAAG;YACb,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,cAAc,EAAE,MAAA,IAAI,CAAC,cAAc,0CAAE,OAAO,0BAAK,YAAY,UAAE;YAC/D,eAAe,EAAE,MAAA,IAAI,CAAC,cAAc,0CAAE,QAAQ;YAC9C,eAAe,EAAE,MAAA,IAAI,CAAC,eAAe,0CAAE,OAAO,0BAAK,YAAY,UAAE;YACjE,gBAAgB,EAAE,MAAA,IAAI,CAAC,eAAe,0CAAE,QAAQ;SACjD,CAAC;QAEF,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,UAAC,EAAM;gBAAN,KAAA,aAAM,EAAL,CAAC,QAAA,EAAE,CAAC,QAAA;YAAM,OAAA,CAAC,KAAK,SAAS;QAAf,CAAe,CAAC,CAAC,CAAC;IAC5F,CAAC;IACH,0BAAC;AAAD,CAAC,AAzCD,IAyCC","sourcesContent":["import { getGlobalScope } from './global-scope';\nimport { pruneJson } from './utils/json-query';\nimport { SAFE_HEADERS, FORBIDDEN_HEADERS } from './';\n\n/* SAFE TYPE DEFINITIONS\n These type definitions expose limited properties of the original types\n to prevent the consumer from mutating them or consuming them.\n*/\ntype BlobSafe = {\n size: number;\n};\n\ntype ArrayBufferSafe = {\n byteLength: number;\n};\n\ntype ArrayBufferViewSafe = {\n byteLength: number;\n};\n\ntype URLSearchParamsSafe = {\n toString(): string;\n};\n\n// no method on readablestream is safe to call\ntype ReadableStreamSafe = Record<string, never>;\n\ntype FormDataEntryValueSafe = string | BlobSafe | null;\n\ntype BodyInitSafe =\n | string\n | Blob\n | ArrayBufferSafe\n | FormDataSafe\n | URLSearchParamsSafe\n | ArrayBufferViewSafe\n | null\n | undefined;\n\ntype HeadersRequestSafe = {\n entries(): IterableIterator<[string, string]>;\n forEach(callbackfn: (value: string, key: string) => void): void;\n};\n\ntype HeadersResponseSafe = {\n get(name: string): string | null;\n forEach(callbackfn: (value: string, key: string) => void): void;\n};\n\ntype HeadersInitSafe = HeadersRequestSafe | Record<string, string> | string[][];\n\ntype ResponseSafe = {\n status: number;\n headers: HeadersResponseSafe | undefined;\n clone(): ResponseCloneSafe;\n};\n\ntype ResponseCloneSafe = {\n text(): Promise<string>;\n};\n\nconst TEXT_READ_TIMEOUT = 500;\n\nexport type RequestInitSafe = {\n method?: string;\n headers?: HeadersInitSafe;\n body?: BodyInitSafe;\n};\nexport interface FormDataSafe {\n entries(): IterableIterator<[string, FormDataEntryValueSafe]>;\n}\nexport type XMLHttpRequestBodyInitSafe = BlobSafe | FormDataSafe | URLSearchParamsSafe | string;\n\nexport type FetchRequestBody =\n | string\n | BlobSafe\n | ArrayBufferSafe\n | FormDataSafe\n | URLSearchParamsSafe\n | ArrayBufferViewSafe\n | null\n | undefined;\n\nexport interface IRequestWrapper {\n /**\n * Get the headers of the request.\n * @param allow - The headers to allow.\n * @returns The pruned headers\n */\n headers(allow?: string[]): Record<string, string> | undefined;\n bodySize?: number;\n method?: string;\n body?: FetchRequestBody | XMLHttpRequestBodyInitSafe | null;\n json: (allow?: string[], exclude?: string[]) => Promise<JsonObject | null>;\n}\n\nexport const MAXIMUM_ENTRIES = 100;\n\n/**\n * This class encapsulates the RequestInit (https://developer.mozilla.org/en-US/docs/Web/API/RequestInit)\n * object so that the consumer can only get access to the headers, method and body size.\n *\n * This is to prevent consumers from directly accessing the Request object\n * and mutating it or running costly operations on it.\n *\n * IMPORTANT:\n * * Do not make changes to this class without careful consideration\n * of performance implications, memory usage and potential to mutate the customer's\n * request.\n * * NEVER .clone() the RequestInit object. This will 2x's the memory overhead of the request\n * * NEVER: call .arrayBuffer(), text(), json() or any other method on the body that\n * consumes the body's stream. This will cause the response to be consumed\n * meaning the body will be empty when the customer tries to access it.\n * (ie: if the body is an instanceof https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream\n * never call any of the methods on it)\n */\nexport class RequestWrapperFetch implements IRequestWrapper {\n private _bodySize: number | undefined;\n constructor(private request: RequestInitSafe) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n const headersUnsafe = this.request.headers;\n\n // copy the headers into a new object\n const headersSafeCopy: Record<string, string> = {};\n if (Array.isArray(headersUnsafe)) {\n headersUnsafe.forEach(([headerName, headerValue]) => {\n headersSafeCopy[headerName] = headerValue;\n });\n } else if (headersUnsafe instanceof Headers) {\n headersUnsafe.forEach((value: string, key: string) => {\n headersSafeCopy[key] = value;\n });\n } else if (typeof headersUnsafe === 'object' && headersUnsafe !== null) {\n for (const [key, value] of Object.entries(headersUnsafe as Record<string, string>)) {\n headersSafeCopy[key] = value;\n }\n }\n\n return pruneHeaders(headersSafeCopy, { allow });\n }\n\n get bodySize(): number | undefined {\n if (typeof this._bodySize === 'number') return this._bodySize;\n const global = getGlobalScope();\n\n /* istanbul ignore if */\n if (!global?.TextEncoder) {\n return;\n }\n const body = this.request.body as FetchRequestBody;\n this._bodySize = getBodySize(body, MAXIMUM_ENTRIES);\n return this._bodySize;\n }\n\n get method(): string | undefined {\n return this.request.method;\n }\n\n get body(): string | null {\n if (typeof this.request.body === 'string') {\n return this.request.body;\n }\n return null;\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = this.body;\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nexport class RequestWrapperXhr implements IRequestWrapper {\n constructor(readonly bodyRaw: XMLHttpRequestBodyInitSafe | null, readonly requestHeaders: Record<string, string>) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n return pruneHeaders(this.requestHeaders, { allow });\n }\n\n get bodySize(): number | undefined {\n return getBodySize(this.bodyRaw as FetchRequestBody, MAXIMUM_ENTRIES);\n }\n\n get body(): string | null {\n if (typeof this.bodyRaw === 'string') {\n return this.bodyRaw;\n }\n return null;\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = this.body;\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nfunction getBodySize(bodyUnsafe: FetchRequestBody, maxEntries: number): number | undefined {\n let bodySize: number | undefined;\n const global = getGlobalScope();\n /* istanbul ignore next */\n const TextEncoder = global?.TextEncoder;\n /* istanbul ignore next */\n if (!TextEncoder) {\n return;\n }\n let bodySafe;\n if (typeof bodyUnsafe === 'string') {\n bodySafe = bodyUnsafe;\n bodySize = new TextEncoder().encode(bodySafe).length;\n } else if (bodyUnsafe instanceof Blob) {\n bodySafe = bodyUnsafe as BlobSafe;\n bodySize = bodySafe.size;\n } else if (bodyUnsafe instanceof URLSearchParams) {\n bodySafe = bodyUnsafe as URLSearchParamsSafe;\n bodySize = new TextEncoder().encode(bodySafe.toString()).length;\n } else if (ArrayBuffer.isView(bodyUnsafe)) {\n bodySafe = bodyUnsafe as ArrayBufferViewSafe;\n bodySize = bodySafe.byteLength;\n } else if (bodyUnsafe instanceof ArrayBuffer) {\n bodySafe = bodyUnsafe as ArrayBufferSafe;\n bodySize = bodySafe.byteLength;\n } else if (bodyUnsafe instanceof FormData) {\n // Estimating only for text parts; not accurate for files\n const formData = bodyUnsafe as unknown as FormDataSafe;\n\n let total = 0;\n let count = 0;\n for (const [key, value] of formData.entries()) {\n total += key.length;\n if (typeof value === 'string') {\n total += new TextEncoder().encode(value).length;\n } else if (value instanceof Blob) {\n total += value.size;\n } else {\n // encountered an unknown type\n // we can't estimate the size of this entry\n return;\n }\n // terminate if we reach the maximum number of entries\n // to avoid performance issues in case of very large FormData\n if (++count >= maxEntries) {\n return;\n }\n }\n bodySize = total;\n } else if (bodyUnsafe instanceof ReadableStream) {\n // If bodyUnsafe is an instanceof ReadableStream, we can't determine the size,\n // without consuming it, so we return undefined.\n // Never ever consume ReadableStream! DO NOT DO IT!!!\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n bodySafe = bodyUnsafe as unknown as ReadableStreamSafe;\n return;\n }\n return bodySize;\n}\n\nexport type JsonObject = {\n [key: string]: JsonValue;\n};\n\nexport type JsonValue = string | number | boolean | null | JsonObject | JsonArray;\n\nexport type JsonArray = Array<JsonValue>;\n\nexport interface IResponseWrapper {\n /**\n * Get the headers of the response.\n * @param allow - The headers to allow.\n * @returns The pruned headers\n */\n headers(allow?: string[]): Record<string, string> | undefined;\n bodySize?: number;\n status?: number;\n body?: string | Blob | ReadableStream | ArrayBuffer | FormDataSafe | URLSearchParams | ArrayBufferView | null;\n text: () => Promise<string | null>;\n json: (allow?: string[], exclude?: string[]) => Promise<JsonObject | null>;\n}\n\n/**\n * This class encapsulates the Fetch API Response object\n * (https://developer.mozilla.org/en-US/docs/Web/API/Response) so that the consumer can\n * only get access to the headers and body size.\n *\n * This is to prevent consumers from directly accessing the Response object\n * and mutating it or running costly operations on it.\n *\n * IMPORTANT:\n * * Do not make changes to this class without careful consideration\n * of performance implications, memory usage and potential to mutate the customer's\n * response.\n * * Do not .clone() the Response object unless you need to access the body.\n * Cloning will 2x the memory overhead of the response.\n * * NEVER consume the body's stream. This will cause the response to be consumed\n * meaning the body will be empty when the customer tries to access it.\n * (ie: if the body is an instanceof https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream\n * never call any of the methods on it)\n */\nexport class ResponseWrapperFetch implements IResponseWrapper {\n private _bodySize: number | undefined;\n private clonedResponse?: ResponseCloneSafe;\n constructor(private response: ResponseSafe) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n if (this.response.headers instanceof Headers) {\n const headersSafe = this.response.headers as HeadersResponseSafe;\n const headersOut: Record<string, string> = {};\n /* istanbul ignore next */\n headersSafe?.forEach?.((value, key) => {\n headersOut[key] = value;\n });\n return pruneHeaders(headersOut, { allow });\n }\n\n return;\n }\n\n get bodySize(): number | undefined {\n if (this._bodySize !== undefined) return this._bodySize;\n /* istanbul ignore next */\n const contentLength = this.response.headers?.get?.('content-length');\n const bodySize = contentLength ? parseInt(contentLength, 10) : undefined;\n this._bodySize = bodySize;\n return bodySize;\n }\n\n get status(): number {\n return this.response.status;\n }\n\n async text(): Promise<string | null> {\n // !!!IMPORTANT: we clone the response to avoid mutating the original response\n // never call .text(), .json(), etc.. on the original response always clone it first\n if (!this.clonedResponse) {\n this.clonedResponse = this.response.clone();\n }\n try {\n const textPromise = this.clonedResponse.text();\n const timer = new Promise<null>((resolve) =>\n setTimeout(\n /* istanbul ignore next */\n () => resolve(null),\n TEXT_READ_TIMEOUT,\n ),\n );\n const text = await Promise.race<string | null>([textPromise, timer]);\n return text;\n } catch (error) {\n return null;\n }\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = await this.text();\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nexport class ResponseWrapperXhr implements IResponseWrapper {\n constructor(\n readonly statusCode: number,\n readonly headersString: string,\n readonly size: number | undefined,\n readonly responseText: string,\n ) {}\n\n get bodySize(): number | undefined {\n return this.size;\n }\n\n get status(): number {\n return this.statusCode;\n }\n\n async text(): Promise<string | null> {\n // reject if body has already been consumed\n return this.responseText;\n }\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n if (!this.headersString) {\n return {};\n }\n const headers: Record<string, string> = {};\n const headerLines = this.headersString.split('\\r\\n');\n for (const line of headerLines) {\n const [key, value] = line.split(': ');\n if (key && value) {\n headers[key] = value;\n }\n }\n return pruneHeaders(headers, { allow });\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = await this.text();\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nfunction safeParseAndPruneBody(text: string | null, allow: string[], exclude: string[]): JsonObject | null {\n if (!text) return null;\n try {\n const json = JSON.parse(text) as JsonObject;\n pruneJson(json, allow, exclude);\n return json;\n } catch (error) {\n return null;\n }\n}\n\nexport enum PRUNE_STRATEGY {\n REDACT = 'redact',\n REMOVE = 'remove',\n}\n\nconst REDACTED_VALUE = '[REDACTED]';\n\n/**\n * Prune headers from a headers record object.\n * @param headers - The headers to prune.\n * @param options - The options to prune the headers.\n * @param options.exclude - List of headers to delete from headers\n * @param options.include - List of headers to keep in headers, if not provided, all headers are kept by default\n * @returns The pruned headers.\n */\nexport const pruneHeaders = (\n headers: Record<string, string>,\n options: {\n allow?: string[];\n strategy?: PRUNE_STRATEGY;\n },\n): Record<string, string> => {\n const { allow = [], strategy = PRUNE_STRATEGY.REMOVE } = options;\n const exclude = [...FORBIDDEN_HEADERS];\n const headersPruned: Record<string, string> = {};\n\n for (const key of Object.keys(headers)) {\n const lowerKey = key.toLowerCase();\n\n if (exclude.find((e) => e.toLowerCase() === lowerKey)) {\n if (strategy === PRUNE_STRATEGY.REDACT) {\n headersPruned[key] = REDACTED_VALUE;\n }\n } else if (!allow.find((i) => i.toLowerCase() === lowerKey)) {\n if (strategy === PRUNE_STRATEGY.REDACT) {\n headersPruned[key] = REDACTED_VALUE;\n }\n } else {\n headersPruned[key] = headers[key];\n }\n }\n return headersPruned;\n};\nexport class NetworkRequestEvent {\n public requestHeaders?: Record<string, string>;\n public responseHeaders?: Record<string, string>;\n public requestBodyJson?: Promise<JsonObject | null>;\n public responseBodyJson?: Promise<JsonObject | null>;\n constructor(\n public readonly type: 'xhr' | 'fetch',\n public readonly method: string,\n public readonly timestamp: number,\n public readonly startTime: number,\n public readonly url?: string,\n public readonly requestWrapper?: IRequestWrapper,\n public readonly status: number = 0,\n public readonly duration?: number,\n public readonly responseWrapper?: IResponseWrapper,\n public readonly error?: {\n name: string;\n message: string;\n },\n public readonly endTime?: number,\n ) {}\n\n toSerializable(): Record<string, any> {\n const serialized: Record<string, any> = {\n type: this.type,\n method: this.method,\n url: this.url,\n timestamp: this.timestamp,\n status: this.status,\n duration: this.duration,\n error: this.error,\n startTime: this.startTime,\n endTime: this.endTime,\n requestHeaders: this.requestWrapper?.headers([...SAFE_HEADERS]),\n requestBodySize: this.requestWrapper?.bodySize,\n responseHeaders: this.responseWrapper?.headers([...SAFE_HEADERS]),\n responseBodySize: this.responseWrapper?.bodySize,\n };\n\n return Object.fromEntries(Object.entries(serialized).filter(([_, v]) => v !== undefined));\n }\n}\n"]}
1
+ {"version":3,"file":"network-request-event.js","sourceRoot":"","sources":["../../src/network-request-event.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,IAAI,CAAC;AA2DrD,IAAM,iBAAiB,GAAG,GAAG,CAAC;AAmC9B,MAAM,CAAC,IAAM,eAAe,GAAG,GAAG,CAAC;AAEnC;;;;;;;;;;;;;;;;;GAiBG;AACH;IAEE,6BAAoB,OAAwB;QAAxB,YAAO,GAAP,OAAO,CAAiB;IAAG,CAAC;IAEhD,qCAAO,GAAP,UAAQ,KAAoB;;QAApB,sBAAA,EAAA,UAAoB;QAC1B,IAAM,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;QAE3C,qCAAqC;QACrC,IAAM,eAAe,GAA2B,EAAE,CAAC;QACnD,IAAI,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE;YAChC,aAAa,CAAC,OAAO,CAAC,UAAC,EAAyB;oBAAzB,KAAA,aAAyB,EAAxB,UAAU,QA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gBAAN,KAAA,aAAM,EAAL,CAAC,QAAA,EAAE,CAAC,QAAA;YAAM,OAAA,CAAC,KAAK,SAAS;QAAf,CAAe,CAAC,CAAC,CAAC;IAC5F,CAAC;IACH,0BAAC;AAAD,CAAC,AAzCD,IAyCC","sourcesContent":["import { getGlobalScope } from './global-scope';\nimport { pruneJson } from './utils/json-query';\nimport { SAFE_HEADERS, FORBIDDEN_HEADERS } from './';\n\n/* SAFE TYPE DEFINITIONS\n These type definitions expose limited properties of the original types\n to prevent the consumer from mutating them or consuming them.\n*/\ntype BlobSafe = {\n size: number;\n};\n\ntype ArrayBufferSafe = {\n byteLength: number;\n};\n\ntype ArrayBufferViewSafe = {\n byteLength: number;\n};\n\ntype URLSearchParamsSafe = {\n toString(): string;\n};\n\n// no method on readablestream is safe to call\ntype ReadableStreamSafe = Record<string, never>;\n\ntype FormDataEntryValueSafe = string | BlobSafe | null;\n\ntype BodyInitSafe =\n | string\n | Blob\n | ArrayBufferSafe\n | FormDataSafe\n | URLSearchParamsSafe\n | ArrayBufferViewSafe\n | null\n | undefined;\n\ntype HeadersRequestSafe = {\n entries(): IterableIterator<[string, string]>;\n forEach(callbackfn: (value: string, key: string) => void): void;\n};\n\ntype HeadersResponseSafe = {\n get(name: string): string | null;\n forEach(callbackfn: (value: string, key: string) => void): void;\n};\n\ntype HeadersInitSafe = HeadersRequestSafe | Record<string, string> | string[][];\n\ntype ResponseSafe = {\n status: number;\n headers: HeadersResponseSafe | undefined;\n clone(): ResponseCloneSafe;\n};\n\ntype ResponseCloneSafe = {\n text(): Promise<string>;\n};\n\nconst TEXT_READ_TIMEOUT = 500;\n\nexport type RequestInitSafe = {\n method?: string;\n headers?: HeadersInitSafe;\n body?: BodyInitSafe;\n};\nexport interface FormDataSafe {\n entries(): IterableIterator<[string, FormDataEntryValueSafe]>;\n}\nexport type XMLHttpRequestBodyInitSafe = BlobSafe | FormDataSafe | URLSearchParamsSafe | string;\n\nexport type FetchRequestBody =\n | string\n | BlobSafe\n | ArrayBufferSafe\n | FormDataSafe\n | URLSearchParamsSafe\n | ArrayBufferViewSafe\n | null\n | undefined;\n\nexport interface IRequestWrapper {\n /**\n * Get the headers of the request.\n * @param allow - The headers to allow.\n * @returns The pruned headers\n */\n headers(allow?: string[]): Record<string, string> | undefined;\n bodySize?: number;\n method?: string;\n body?: FetchRequestBody | XMLHttpRequestBodyInitSafe | null;\n json: (allow?: string[], exclude?: string[]) => Promise<JsonObject | null>;\n}\n\nexport const MAXIMUM_ENTRIES = 100;\n\n/**\n * This class encapsulates the RequestInit (https://developer.mozilla.org/en-US/docs/Web/API/RequestInit)\n * object so that the consumer can only get access to the headers, method and body size.\n *\n * This is to prevent consumers from directly accessing the Request object\n * and mutating it or running costly operations on it.\n *\n * IMPORTANT:\n * * Do not make changes to this class without careful consideration\n * of performance implications, memory usage and potential to mutate the customer's\n * request.\n * * NEVER .clone() the RequestInit object. This will 2x's the memory overhead of the request\n * * NEVER: call .arrayBuffer(), text(), json() or any other method on the body that\n * consumes the body's stream. This will cause the response to be consumed\n * meaning the body will be empty when the customer tries to access it.\n * (ie: if the body is an instanceof https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream\n * never call any of the methods on it)\n */\nexport class RequestWrapperFetch implements IRequestWrapper {\n private _bodySize: number | undefined;\n constructor(private request: RequestInitSafe) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n const headersUnsafe = this.request.headers;\n\n // copy the headers into a new object\n const headersSafeCopy: Record<string, string> = {};\n if (Array.isArray(headersUnsafe)) {\n headersUnsafe.forEach(([headerName, headerValue]) => {\n headersSafeCopy[headerName] = headerValue;\n });\n } else if (headersUnsafe instanceof Headers) {\n headersUnsafe.forEach((value: string, key: string) => {\n headersSafeCopy[key] = value;\n });\n } else if (typeof headersUnsafe === 'object' && headersUnsafe !== null) {\n for (const [key, value] of Object.entries(headersUnsafe as Record<string, string>)) {\n headersSafeCopy[key] = value;\n }\n }\n\n return pruneHeaders(headersSafeCopy, { allow });\n }\n\n get bodySize(): number | undefined {\n if (typeof this._bodySize === 'number') return this._bodySize;\n const global = getGlobalScope();\n\n /* istanbul ignore if */\n if (!global?.TextEncoder) {\n return;\n }\n const body = this.request.body as FetchRequestBody;\n this._bodySize = getBodySize(body, MAXIMUM_ENTRIES);\n return this._bodySize;\n }\n\n get method(): string | undefined {\n return this.request.method;\n }\n\n get body(): string | null {\n if (typeof this.request.body === 'string') {\n return this.request.body;\n }\n return null;\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = this.body;\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nexport class RequestWrapperXhr implements IRequestWrapper {\n constructor(readonly bodyRaw: XMLHttpRequestBodyInitSafe | null, readonly requestHeaders: Record<string, string>) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n return pruneHeaders(this.requestHeaders, { allow });\n }\n\n get bodySize(): number | undefined {\n return getBodySize(this.bodyRaw as FetchRequestBody, MAXIMUM_ENTRIES);\n }\n\n get body(): string | null {\n if (typeof this.bodyRaw === 'string') {\n return this.bodyRaw;\n }\n return null;\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = this.body;\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nfunction getBodySize(bodyUnsafe: FetchRequestBody, maxEntries: number): number | undefined {\n let bodySize: number | undefined;\n const global = getGlobalScope();\n /* istanbul ignore next */\n const TextEncoder = global?.TextEncoder;\n /* istanbul ignore next */\n if (!TextEncoder) {\n return;\n }\n let bodySafe;\n if (typeof bodyUnsafe === 'string') {\n bodySafe = bodyUnsafe;\n bodySize = new TextEncoder().encode(bodySafe).length;\n } else if (bodyUnsafe instanceof Blob) {\n bodySafe = bodyUnsafe as BlobSafe;\n bodySize = bodySafe.size;\n } else if (bodyUnsafe instanceof URLSearchParams) {\n bodySafe = bodyUnsafe as URLSearchParamsSafe;\n bodySize = new TextEncoder().encode(bodySafe.toString()).length;\n } else if (ArrayBuffer.isView(bodyUnsafe)) {\n bodySafe = bodyUnsafe as ArrayBufferViewSafe;\n bodySize = bodySafe.byteLength;\n } else if (bodyUnsafe instanceof ArrayBuffer) {\n bodySafe = bodyUnsafe as ArrayBufferSafe;\n bodySize = bodySafe.byteLength;\n } else if (bodyUnsafe instanceof FormData) {\n // Estimating only for text parts; not accurate for files\n const formData = bodyUnsafe as unknown as FormDataSafe;\n\n let total = 0;\n let count = 0;\n for (const [key, value] of formData.entries()) {\n total += key.length;\n if (typeof value === 'string') {\n total += new TextEncoder().encode(value).length;\n } else if (value instanceof Blob) {\n total += value.size;\n } else {\n // encountered an unknown type\n // we can't estimate the size of this entry\n return;\n }\n // terminate if we reach the maximum number of entries\n // to avoid performance issues in case of very large FormData\n if (++count >= maxEntries) {\n return;\n }\n }\n bodySize = total;\n } else if (bodyUnsafe instanceof ReadableStream) {\n // If bodyUnsafe is an instanceof ReadableStream, we can't determine the size,\n // without consuming it, so we return undefined.\n // Never ever consume ReadableStream! DO NOT DO IT!!!\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n bodySafe = bodyUnsafe as unknown as ReadableStreamSafe;\n return;\n }\n return bodySize;\n}\n\nexport type JsonObject = {\n [key: string]: JsonValue;\n};\n\nexport type JsonValue = string | number | boolean | null | JsonObject | JsonArray;\n\nexport type JsonArray = Array<JsonValue>;\n\nexport interface IResponseWrapper {\n /**\n * Get the headers of the response.\n * @param allow - The headers to allow.\n * @returns The pruned headers\n */\n headers(allow?: string[]): Record<string, string> | undefined;\n bodySize?: number;\n status?: number;\n body?: string | Blob | ReadableStream | ArrayBuffer | FormDataSafe | URLSearchParams | ArrayBufferView | null;\n json: (allow?: string[], exclude?: string[]) => Promise<JsonObject | null>;\n}\n\n/**\n * This class encapsulates the Fetch API Response object\n * (https://developer.mozilla.org/en-US/docs/Web/API/Response) so that the consumer can\n * only get access to the headers and body size.\n *\n * This is to prevent consumers from directly accessing the Response object\n * and mutating it or running costly operations on it.\n *\n * IMPORTANT:\n * * Do not make changes to this class without careful consideration\n * of performance implications, memory usage and potential to mutate the customer's\n * response.\n * * Do not .clone() the Response object unless you need to access the body.\n * Cloning will 2x the memory overhead of the response.\n * * NEVER consume the body's stream. This will cause the response to be consumed\n * meaning the body will be empty when the customer tries to access it.\n * (ie: if the body is an instanceof https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream\n * never call any of the methods on it)\n */\nexport class ResponseWrapperFetch implements IResponseWrapper {\n private _bodySize: number | undefined;\n private clonedResponse?: ResponseCloneSafe;\n constructor(private response: ResponseSafe) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n if (this.response.headers instanceof Headers) {\n const headersSafe = this.response.headers as HeadersResponseSafe;\n const headersOut: Record<string, string> = {};\n /* istanbul ignore next */\n headersSafe?.forEach?.((value, key) => {\n headersOut[key] = value;\n });\n return pruneHeaders(headersOut, { allow });\n }\n\n return;\n }\n\n get bodySize(): number | undefined {\n if (this._bodySize !== undefined) return this._bodySize;\n /* istanbul ignore next */\n const contentLength = this.response.headers?.get?.('content-length');\n const bodySize = contentLength ? parseInt(contentLength, 10) : undefined;\n this._bodySize = bodySize;\n return bodySize;\n }\n\n get status(): number {\n return this.response.status;\n }\n\n async text(): Promise<string | null> {\n // !!!IMPORTANT: we clone the response to avoid mutating the original response\n // never call .text(), .json(), etc.. on the original response always clone it first\n if (!this.clonedResponse) {\n this.clonedResponse = this.response.clone();\n }\n try {\n const textPromise = this.clonedResponse.text();\n const timer = new Promise<null>((resolve) =>\n setTimeout(\n /* istanbul ignore next */\n () => resolve(null),\n TEXT_READ_TIMEOUT,\n ),\n );\n const text = await Promise.race<string | null>([textPromise, timer]);\n return text;\n } catch (error) {\n return null;\n }\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = await this.text();\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nexport class ResponseWrapperXhr implements IResponseWrapper {\n constructor(\n readonly statusCode: number,\n readonly headersString: string,\n readonly size: number | undefined,\n readonly getJson: () => any | null,\n ) {}\n\n get bodySize(): number | undefined {\n return this.size;\n }\n\n get status(): number {\n return this.statusCode;\n }\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n if (!this.headersString) {\n return {};\n }\n const headers: Record<string, string> = {};\n const headerLines = this.headersString.split('\\r\\n');\n for (const line of headerLines) {\n const [key, value] = line.split(': ');\n if (key && value) {\n headers[key] = value;\n }\n }\n return pruneHeaders(headers, { allow });\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const jsonBody = this.getJson() as JsonObject | null;\n if (jsonBody) {\n pruneJson(jsonBody, allow, exclude);\n return jsonBody;\n }\n return null;\n }\n}\n\nfunction safeParseAndPruneBody(text: string | null, allow: string[], exclude: string[]): JsonObject | null {\n if (!text) return null;\n try {\n const json = JSON.parse(text) as JsonObject;\n pruneJson(json, allow, exclude);\n return json;\n } catch (error) {\n return null;\n }\n}\n\nexport enum PRUNE_STRATEGY {\n REDACT = 'redact',\n REMOVE = 'remove',\n}\n\nconst REDACTED_VALUE = '[REDACTED]';\n\n/**\n * Prune headers from a headers record object.\n * @param headers - The headers to prune.\n * @param options - The options to prune the headers.\n * @param options.exclude - List of headers to delete from headers\n * @param options.include - List of headers to keep in headers, if not provided, all headers are kept by default\n * @returns The pruned headers.\n */\nexport const pruneHeaders = (\n headers: Record<string, string>,\n options: {\n allow?: string[];\n strategy?: PRUNE_STRATEGY;\n },\n): Record<string, string> => {\n const { allow = [], strategy = PRUNE_STRATEGY.REMOVE } = options;\n const exclude = [...FORBIDDEN_HEADERS];\n const headersPruned: Record<string, string> = {};\n\n for (const key of Object.keys(headers)) {\n const lowerKey = key.toLowerCase();\n\n if (exclude.find((e) => e.toLowerCase() === lowerKey)) {\n if (strategy === PRUNE_STRATEGY.REDACT) {\n headersPruned[key] = REDACTED_VALUE;\n }\n } else if (!allow.find((i) => i.toLowerCase() === lowerKey)) {\n if (strategy === PRUNE_STRATEGY.REDACT) {\n headersPruned[key] = REDACTED_VALUE;\n }\n } else {\n headersPruned[key] = headers[key];\n }\n }\n return headersPruned;\n};\nexport class NetworkRequestEvent {\n public requestHeaders?: Record<string, string>;\n public responseHeaders?: Record<string, string>;\n public requestBodyJson?: Promise<JsonObject | null>;\n public responseBodyJson?: Promise<JsonObject | null>;\n constructor(\n public readonly type: 'xhr' | 'fetch',\n public readonly method: string,\n public readonly timestamp: number,\n public readonly startTime: number,\n public readonly url?: string,\n public readonly requestWrapper?: IRequestWrapper,\n public readonly status: number = 0,\n public readonly duration?: number,\n public readonly responseWrapper?: IResponseWrapper,\n public readonly error?: {\n name: string;\n message: string;\n },\n public readonly endTime?: number,\n ) {}\n\n toSerializable(): Record<string, any> {\n const serialized: Record<string, any> = {\n type: this.type,\n method: this.method,\n url: this.url,\n timestamp: this.timestamp,\n status: this.status,\n duration: this.duration,\n error: this.error,\n startTime: this.startTime,\n endTime: this.endTime,\n requestHeaders: this.requestWrapper?.headers([...SAFE_HEADERS]),\n requestBodySize: this.requestWrapper?.bodySize,\n responseHeaders: this.responseWrapper?.headers([...SAFE_HEADERS]),\n responseBodySize: this.responseWrapper?.bodySize,\n };\n\n return Object.fromEntries(Object.entries(serialized).filter(([_, v]) => v !== undefined));\n }\n}\n"]}
@@ -31,6 +31,15 @@ export interface ElementInteractionsOptions {
31
31
  * Both full URLs and regex are supported.
32
32
  */
33
33
  pageUrlAllowlist?: (string | RegExp)[];
34
+ /**
35
+ * List of page URLs to exclude from auto tracking.
36
+ * When provided, tracking will be blocked on these URLs.
37
+ * Both full URLs and regex are supported.
38
+ * This takes precedence over pageUrlAllowlist.
39
+ */
40
+ pageUrlExcludelist?: (RegExp | string | {
41
+ pattern: string;
42
+ })[];
34
43
  /**
35
44
  * Function to determine whether an event should be tracked.
36
45
  * When provided, this function overwrites all other allowlists and configurations.
@@ -1 +1 @@
1
- {"version":3,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