@amplitude/analytics-core 2.21.2 → 2.22.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.
- package/lib/cjs/network-observer.d.ts +11 -0
- package/lib/cjs/network-observer.d.ts.map +1 -1
- package/lib/cjs/network-observer.js +47 -5
- package/lib/cjs/network-observer.js.map +1 -1
- package/lib/cjs/network-request-event.d.ts +3 -8
- package/lib/cjs/network-request-event.d.ts.map +1 -1
- package/lib/cjs/network-request-event.js +18 -52
- package/lib/cjs/network-request-event.js.map +1 -1
- package/lib/cjs/types/element-interactions.d.ts +7 -0
- package/lib/cjs/types/element-interactions.d.ts.map +1 -1
- package/lib/cjs/types/element-interactions.js.map +1 -1
- package/lib/cjs/types/frustration-interactions.d.ts +7 -0
- package/lib/cjs/types/frustration-interactions.d.ts.map +1 -1
- package/lib/cjs/types/frustration-interactions.js.map +1 -1
- package/lib/esm/network-observer.d.ts +11 -0
- package/lib/esm/network-observer.d.ts.map +1 -1
- package/lib/esm/network-observer.js +47 -5
- package/lib/esm/network-observer.js.map +1 -1
- package/lib/esm/network-request-event.d.ts +3 -8
- package/lib/esm/network-request-event.d.ts.map +1 -1
- package/lib/esm/network-request-event.js +18 -52
- package/lib/esm/network-request-event.js.map +1 -1
- package/lib/esm/types/element-interactions.d.ts +7 -0
- package/lib/esm/types/element-interactions.d.ts.map +1 -1
- package/lib/esm/types/element-interactions.js.map +1 -1
- package/lib/esm/types/frustration-interactions.d.ts +7 -0
- package/lib/esm/types/frustration-interactions.d.ts.map +1 -1
- package/lib/esm/types/frustration-interactions.js.map +1 -1
- package/package.json +2 -2
|
@@ -19,6 +19,17 @@ export declare class NetworkObserver {
|
|
|
19
19
|
private handleNetworkRequestEvent;
|
|
20
20
|
private getTimestamps;
|
|
21
21
|
private observeFetch;
|
|
22
|
+
/**
|
|
23
|
+
* Creates a function that parses the response of an XMLHttpRequest as JSON.
|
|
24
|
+
*
|
|
25
|
+
* Returns function instead of JSON object to avoid unnecessary parsing if the
|
|
26
|
+
* body is not being captured.
|
|
27
|
+
*
|
|
28
|
+
* @param xhrSafe - The XMLHttpRequest object.
|
|
29
|
+
* @param context - The NetworkObserver instance.
|
|
30
|
+
* @returns A function that parses the response of an XMLHttpRequest as JSON.
|
|
31
|
+
*/
|
|
32
|
+
static createXhrJsonParser(xhrUnsafe: XMLHttpRequest, context: NetworkObserver): () => any;
|
|
22
33
|
private observeXhr;
|
|
23
34
|
}
|
|
24
35
|
export declare const networkObserver: NetworkObserver;
|
|
@@ -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;
|
|
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;AAqBD,qBAAa,eAAe;IAC1B,OAAO,CAAC,cAAc,CAAgD;IAEtE,OAAO,CAAC,WAAW,CAAC,CAAoB;IACxC,OAAO,CAAC,MAAM,CAAC,CAAU;IACzB,OAAO,CAAC,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,OAAO,CAAC,yBAAyB;IA4DjC,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"}
|
|
@@ -192,6 +192,46 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
192
192
|
});
|
|
193
193
|
}); };
|
|
194
194
|
};
|
|
195
|
+
/**
|
|
196
|
+
* Creates a function that parses the response of an XMLHttpRequest as JSON.
|
|
197
|
+
*
|
|
198
|
+
* Returns function instead of JSON object to avoid unnecessary parsing if the
|
|
199
|
+
* body is not being captured.
|
|
200
|
+
*
|
|
201
|
+
* @param xhrSafe - The XMLHttpRequest object.
|
|
202
|
+
* @param context - The NetworkObserver instance.
|
|
203
|
+
* @returns A function that parses the response of an XMLHttpRequest as JSON.
|
|
204
|
+
*/
|
|
205
|
+
NetworkObserver.createXhrJsonParser = function (xhrUnsafe, context) {
|
|
206
|
+
return function () {
|
|
207
|
+
var _a, _b;
|
|
208
|
+
try {
|
|
209
|
+
if (xhrUnsafe.responseType === 'json') {
|
|
210
|
+
// if response is a JS object, clone it so that subscribers can't mutate it
|
|
211
|
+
if ((_a = context.globalScope) === null || _a === void 0 ? void 0 : _a.structuredClone) {
|
|
212
|
+
/* eslint-disable-next-line @typescript-eslint/no-unsafe-return */
|
|
213
|
+
return context.globalScope.structuredClone(xhrUnsafe.response);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
else if (['text', ''].includes(xhrUnsafe.responseType)) {
|
|
217
|
+
// if response is a string, parse it as JSON
|
|
218
|
+
/* eslint-disable-next-line @typescript-eslint/no-unsafe-return */
|
|
219
|
+
return JSON.parse(xhrUnsafe.responseText);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
catch (err) {
|
|
223
|
+
/* istanbul ignore if */
|
|
224
|
+
if (err instanceof Error && err.name === 'InvalidStateError') {
|
|
225
|
+
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText#exceptions
|
|
226
|
+
// if we reach here, it means we don't handle responseType correctly
|
|
227
|
+
(_b = context.logger) === null || _b === void 0 ? void 0 : _b.error("unexpected error when retrieving responseText. responseType='".concat(xhrUnsafe.responseType, "'"));
|
|
228
|
+
}
|
|
229
|
+
// the other possible error is Json Parse error which we fail silently
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
return null;
|
|
233
|
+
};
|
|
234
|
+
};
|
|
195
235
|
NetworkObserver.prototype.observeXhr = function (originalXhrOpen, originalXhrSend, originalXhrSetRequestHeader) {
|
|
196
236
|
/* istanbul ignore next */
|
|
197
237
|
if (!this.globalScope || !originalXhrOpen || !originalXhrSend) {
|
|
@@ -219,7 +259,7 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
219
259
|
}
|
|
220
260
|
catch (err) {
|
|
221
261
|
/* istanbul ignore next */
|
|
222
|
-
(_b = networkObserverContext.logger) === null || _b === void 0 ? void 0 : _b.
|
|
262
|
+
(_b = networkObserverContext.logger) === null || _b === void 0 ? void 0 : _b.error('an unexpected error occurred while calling xhr open', err);
|
|
223
263
|
}
|
|
224
264
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
|
225
265
|
return originalXhrOpen.apply(xhrSafe, args);
|
|
@@ -238,7 +278,9 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
238
278
|
args[_i] = arguments[_i];
|
|
239
279
|
}
|
|
240
280
|
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
241
|
-
var
|
|
281
|
+
var xhrUnsafe = this;
|
|
282
|
+
var xhrSafe = xhrUnsafe;
|
|
283
|
+
var getJson = NetworkObserver.createXhrJsonParser(xhrUnsafe, networkObserverContext);
|
|
242
284
|
var body = args[0];
|
|
243
285
|
var requestEvent = xhrSafe.$$AmplitudeAnalyticsEvent;
|
|
244
286
|
xhrSafe.addEventListener('loadend', function () {
|
|
@@ -248,7 +290,7 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
248
290
|
var responseBodySize = xhrSafe.getResponseHeader('content-length');
|
|
249
291
|
var responseWrapper = new network_request_event_1.ResponseWrapperXhr(xhrSafe.status, responseHeaders,
|
|
250
292
|
/* istanbul ignore next */
|
|
251
|
-
responseBodySize ? parseInt(responseBodySize, 10) : undefined,
|
|
293
|
+
responseBodySize ? parseInt(responseBodySize, 10) : undefined, getJson);
|
|
252
294
|
var requestHeaders = xhrSafe.$$AmplitudeAnalyticsEvent.headers;
|
|
253
295
|
var requestWrapper = new network_request_event_1.RequestWrapperXhr(body, requestHeaders);
|
|
254
296
|
requestEvent.status = xhrSafe.status;
|
|
@@ -256,7 +298,7 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
256
298
|
}
|
|
257
299
|
catch (err) {
|
|
258
300
|
/* istanbul ignore next */
|
|
259
|
-
(_a = networkObserverContext.logger) === null || _a === void 0 ? void 0 : _a.
|
|
301
|
+
(_a = networkObserverContext.logger) === null || _a === void 0 ? void 0 : _a.error('an unexpected error occurred while handling xhr send', err);
|
|
260
302
|
}
|
|
261
303
|
});
|
|
262
304
|
/* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */
|
|
@@ -279,7 +321,7 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
279
321
|
}
|
|
280
322
|
catch (err) {
|
|
281
323
|
/* istanbul ignore next */
|
|
282
|
-
(_a = networkObserverContext.logger) === null || _a === void 0 ? void 0 : _a.
|
|
324
|
+
(_a = networkObserverContext.logger) === null || _a === void 0 ? void 0 : _a.error('an unexpected error occurred while calling xhr setRequestHeader', err);
|
|
283
325
|
}
|
|
284
326
|
/* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */
|
|
285
327
|
originalXhrSetRequestHeader.apply(xhrSafe, [headerName, headerValue]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-observer.js","sourceRoot":"","sources":["../../src/network-observer.ts"],"names":[],"mappings":";;;;AAAA,uBAAoC;AACpC,qCAAoC;AAEpC,iEAUiC;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,SAAa,WAAI,GAAE;QAAnF,aAAQ,GAAR,QAAQ,CAAsC;QAAkB,OAAE,GAAF,EAAE,CAAiB;IAAG,CAAC;IACrH,2BAAC;AAAD,CAAC,AAFD,IAEC;AAFY,oDAAoB;AAsBjC;IAME,yBAAY,MAAgB;QALpB,mBAAc,GAAsC,IAAI,GAAG,EAAE,CAAC;QAI9D,gBAAW,GAAG,KAAK,CAAC;QAE1B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAM,WAAW,GAAG,IAAA,iBAAc,GAAE,CAAC;QACrC,IAAI,CAAC,eAAe,CAAC,WAAW,EAAE,EAAE;YAClC,0BAA0B;YAC1B,OAAO;SACR;QACD,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAA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E,2BAA2B,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC,CAAC;QACxE,CAAC,CAAC;IACJ,CAAC;IACH,sBAAC;AAAD,CAAC,AAzTD,IAyTC;AAzTY,0CAAe;AA2T5B,wCAAwC;AAC3B,QAAA,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,uBAAoC;AACpC,qCAAoC;AAEpC,iEAUiC;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,SAAa,WAAI,GAAE;QAAnF,aAAQ,GAAR,QAAQ,CAAsC;QAAkB,OAAE,GAAF,EAAE,CAAiB;IAAG,CAAC;IACrH,2BAAC;AAAD,CAAC,AAFD,IAEC;AAFY,oDAAoB;AAuBjC;IAME,yBAAY,MAAgB;QALpB,mBAAc,GAAsC,IAAI,GAAG,EAAE,CAAC;QAI9D,gBAAW,GAAG,KAAK,CAAC;QAE1B,IAAI,CAAC,MAAM,G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EAAE,WAAW,CAAC,CAAC,CAAC;QACxE,CAAC,CAAC;IACJ,CAAC;IACH,sBAAC;AAAD,CAAC,AApWD,IAoWC;AApWY,0CAAe;AAsW5B,wCAAwC;AAC3B,QAAA,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 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 /**\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"]}
|
|
@@ -73,7 +73,6 @@ export declare const MAXIMUM_ENTRIES = 100;
|
|
|
73
73
|
export declare class RequestWrapperFetch implements IRequestWrapper {
|
|
74
74
|
private request;
|
|
75
75
|
private _bodySize;
|
|
76
|
-
private consumptionCheck;
|
|
77
76
|
constructor(request: RequestInitSafe);
|
|
78
77
|
headers(allow?: string[]): Record<string, string> | undefined;
|
|
79
78
|
get bodySize(): number | undefined;
|
|
@@ -84,7 +83,6 @@ export declare class RequestWrapperFetch implements IRequestWrapper {
|
|
|
84
83
|
export declare class RequestWrapperXhr implements IRequestWrapper {
|
|
85
84
|
readonly bodyRaw: XMLHttpRequestBodyInitSafe | null;
|
|
86
85
|
readonly requestHeaders: Record<string, string>;
|
|
87
|
-
private consumptionCheck;
|
|
88
86
|
constructor(bodyRaw: XMLHttpRequestBodyInitSafe | null, requestHeaders: Record<string, string>);
|
|
89
87
|
headers(allow?: string[]): Record<string, string> | undefined;
|
|
90
88
|
get bodySize(): number | undefined;
|
|
@@ -106,7 +104,6 @@ export interface IResponseWrapper {
|
|
|
106
104
|
bodySize?: number;
|
|
107
105
|
status?: number;
|
|
108
106
|
body?: string | Blob | ReadableStream | ArrayBuffer | FormDataSafe | URLSearchParams | ArrayBufferView | null;
|
|
109
|
-
text: () => Promise<string | null>;
|
|
110
107
|
json: (allow?: string[], exclude?: string[]) => Promise<JsonObject | null>;
|
|
111
108
|
}
|
|
112
109
|
/**
|
|
@@ -131,7 +128,7 @@ export interface IResponseWrapper {
|
|
|
131
128
|
export declare class ResponseWrapperFetch implements IResponseWrapper {
|
|
132
129
|
private response;
|
|
133
130
|
private _bodySize;
|
|
134
|
-
private
|
|
131
|
+
private clonedResponse?;
|
|
135
132
|
constructor(response: ResponseSafe);
|
|
136
133
|
headers(allow?: string[]): Record<string, string> | undefined;
|
|
137
134
|
get bodySize(): number | undefined;
|
|
@@ -143,12 +140,10 @@ export declare class ResponseWrapperXhr implements IResponseWrapper {
|
|
|
143
140
|
readonly statusCode: number;
|
|
144
141
|
readonly headersString: string;
|
|
145
142
|
readonly size: number | undefined;
|
|
146
|
-
readonly
|
|
147
|
-
|
|
148
|
-
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);
|
|
149
145
|
get bodySize(): number | undefined;
|
|
150
146
|
get status(): number;
|
|
151
|
-
text(): Promise<string | null>;
|
|
152
147
|
headers(allow?: string[]): Record<string, string> | undefined;
|
|
153
148
|
json(allow?: string[], exclude?: string[]): Promise<JsonObject | null>;
|
|
154
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,mBAAmB,GACnB,mBAAmB,GACnB,IAAI,GACJ,SAAS,CAAC;AAEd,KAAK,kBAAkB,GAAG;IACxB,OAAO,IAAI,gBAAgB,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC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,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"}
|
|
@@ -7,23 +7,6 @@ var json_query_1 = require("./utils/json-query");
|
|
|
7
7
|
var _1 = require("./");
|
|
8
8
|
var TEXT_READ_TIMEOUT = 500;
|
|
9
9
|
exports.MAXIMUM_ENTRIES = 100;
|
|
10
|
-
/**
|
|
11
|
-
* This class is used to enforce the consumption of headers and body
|
|
12
|
-
* so that 'headers' and 'body' can only be accessed once.
|
|
13
|
-
*/
|
|
14
|
-
var ConsumptionCheck = /** @class */ (function () {
|
|
15
|
-
function ConsumptionCheck() {
|
|
16
|
-
this.headers = false;
|
|
17
|
-
this.body = false;
|
|
18
|
-
}
|
|
19
|
-
ConsumptionCheck.prototype.consume = function (objType) {
|
|
20
|
-
if (this[objType]) {
|
|
21
|
-
throw new TypeError("".concat(objType, " has already been consumed"));
|
|
22
|
-
}
|
|
23
|
-
this[objType] = true;
|
|
24
|
-
};
|
|
25
|
-
return ConsumptionCheck;
|
|
26
|
-
}());
|
|
27
10
|
/**
|
|
28
11
|
* This class encapsulates the RequestInit (https://developer.mozilla.org/en-US/docs/Web/API/RequestInit)
|
|
29
12
|
* object so that the consumer can only get access to the headers, method and body size.
|
|
@@ -45,12 +28,10 @@ var ConsumptionCheck = /** @class */ (function () {
|
|
|
45
28
|
var RequestWrapperFetch = /** @class */ (function () {
|
|
46
29
|
function RequestWrapperFetch(request) {
|
|
47
30
|
this.request = request;
|
|
48
|
-
this.consumptionCheck = new ConsumptionCheck();
|
|
49
31
|
}
|
|
50
32
|
RequestWrapperFetch.prototype.headers = function (allow) {
|
|
51
33
|
var e_1, _a;
|
|
52
34
|
if (allow === void 0) { allow = []; }
|
|
53
|
-
this.consumptionCheck.consume('headers');
|
|
54
35
|
var headersUnsafe = this.request.headers;
|
|
55
36
|
// copy the headers into a new object
|
|
56
37
|
var headersSafeCopy = {};
|
|
@@ -107,7 +88,6 @@ var RequestWrapperFetch = /** @class */ (function () {
|
|
|
107
88
|
});
|
|
108
89
|
Object.defineProperty(RequestWrapperFetch.prototype, "body", {
|
|
109
90
|
get: function () {
|
|
110
|
-
this.consumptionCheck.consume('body');
|
|
111
91
|
if (typeof this.request.body === 'string') {
|
|
112
92
|
return this.request.body;
|
|
113
93
|
}
|
|
@@ -137,11 +117,9 @@ var RequestWrapperXhr = /** @class */ (function () {
|
|
|
137
117
|
function RequestWrapperXhr(bodyRaw, requestHeaders) {
|
|
138
118
|
this.bodyRaw = bodyRaw;
|
|
139
119
|
this.requestHeaders = requestHeaders;
|
|
140
|
-
this.consumptionCheck = new ConsumptionCheck();
|
|
141
120
|
}
|
|
142
121
|
RequestWrapperXhr.prototype.headers = function (allow) {
|
|
143
122
|
if (allow === void 0) { allow = []; }
|
|
144
|
-
this.consumptionCheck.consume('headers');
|
|
145
123
|
return (0, exports.pruneHeaders)(this.requestHeaders, { allow: allow });
|
|
146
124
|
};
|
|
147
125
|
Object.defineProperty(RequestWrapperXhr.prototype, "bodySize", {
|
|
@@ -153,7 +131,6 @@ var RequestWrapperXhr = /** @class */ (function () {
|
|
|
153
131
|
});
|
|
154
132
|
Object.defineProperty(RequestWrapperXhr.prototype, "body", {
|
|
155
133
|
get: function () {
|
|
156
|
-
this.consumptionCheck.consume('body');
|
|
157
134
|
if (typeof this.bodyRaw === 'string') {
|
|
158
135
|
return this.bodyRaw;
|
|
159
136
|
}
|
|
@@ -278,12 +255,10 @@ function getBodySize(bodyUnsafe, maxEntries) {
|
|
|
278
255
|
var ResponseWrapperFetch = /** @class */ (function () {
|
|
279
256
|
function ResponseWrapperFetch(response) {
|
|
280
257
|
this.response = response;
|
|
281
|
-
this.consumptionCheck = new ConsumptionCheck();
|
|
282
258
|
}
|
|
283
259
|
ResponseWrapperFetch.prototype.headers = function (allow) {
|
|
284
260
|
var _a;
|
|
285
261
|
if (allow === void 0) { allow = []; }
|
|
286
|
-
this.consumptionCheck.consume('headers');
|
|
287
262
|
if (this.response.headers instanceof Headers) {
|
|
288
263
|
var headersSafe = this.response.headers;
|
|
289
264
|
var headersOut_1 = {};
|
|
@@ -318,16 +293,19 @@ var ResponseWrapperFetch = /** @class */ (function () {
|
|
|
318
293
|
});
|
|
319
294
|
ResponseWrapperFetch.prototype.text = function () {
|
|
320
295
|
return tslib_1.__awaiter(this, void 0, void 0, function () {
|
|
321
|
-
var
|
|
296
|
+
var textPromise, timer, text, error_1;
|
|
322
297
|
return tslib_1.__generator(this, function (_a) {
|
|
323
298
|
switch (_a.label) {
|
|
324
299
|
case 0:
|
|
325
|
-
|
|
326
|
-
|
|
300
|
+
// !!!IMPORTANT: we clone the response to avoid mutating the original response
|
|
301
|
+
// never call .text(), .json(), etc.. on the original response always clone it first
|
|
302
|
+
if (!this.clonedResponse) {
|
|
303
|
+
this.clonedResponse = this.response.clone();
|
|
304
|
+
}
|
|
327
305
|
_a.label = 1;
|
|
328
306
|
case 1:
|
|
329
307
|
_a.trys.push([1, 3, , 4]);
|
|
330
|
-
textPromise = clonedResponse.text();
|
|
308
|
+
textPromise = this.clonedResponse.text();
|
|
331
309
|
timer = new Promise(function (resolve) {
|
|
332
310
|
return setTimeout(
|
|
333
311
|
/* istanbul ignore next */
|
|
@@ -368,12 +346,11 @@ var ResponseWrapperFetch = /** @class */ (function () {
|
|
|
368
346
|
}());
|
|
369
347
|
exports.ResponseWrapperFetch = ResponseWrapperFetch;
|
|
370
348
|
var ResponseWrapperXhr = /** @class */ (function () {
|
|
371
|
-
function ResponseWrapperXhr(statusCode, headersString, size,
|
|
349
|
+
function ResponseWrapperXhr(statusCode, headersString, size, getJson) {
|
|
372
350
|
this.statusCode = statusCode;
|
|
373
351
|
this.headersString = headersString;
|
|
374
352
|
this.size = size;
|
|
375
|
-
this.
|
|
376
|
-
this.consumptionCheck = new ConsumptionCheck();
|
|
353
|
+
this.getJson = getJson;
|
|
377
354
|
}
|
|
378
355
|
Object.defineProperty(ResponseWrapperXhr.prototype, "bodySize", {
|
|
379
356
|
get: function () {
|
|
@@ -389,19 +366,9 @@ var ResponseWrapperXhr = /** @class */ (function () {
|
|
|
389
366
|
enumerable: false,
|
|
390
367
|
configurable: true
|
|
391
368
|
});
|
|
392
|
-
ResponseWrapperXhr.prototype.text = function () {
|
|
393
|
-
return tslib_1.__awaiter(this, void 0, void 0, function () {
|
|
394
|
-
return tslib_1.__generator(this, function (_a) {
|
|
395
|
-
// reject if body has already been consumed
|
|
396
|
-
this.consumptionCheck.consume('body');
|
|
397
|
-
return [2 /*return*/, this.responseText];
|
|
398
|
-
});
|
|
399
|
-
});
|
|
400
|
-
};
|
|
401
369
|
ResponseWrapperXhr.prototype.headers = function (allow) {
|
|
402
370
|
var e_3, _a;
|
|
403
371
|
if (allow === void 0) { allow = []; }
|
|
404
|
-
this.consumptionCheck.consume('headers');
|
|
405
372
|
if (!this.headersString) {
|
|
406
373
|
return {};
|
|
407
374
|
}
|
|
@@ -429,18 +396,17 @@ var ResponseWrapperXhr = /** @class */ (function () {
|
|
|
429
396
|
if (allow === void 0) { allow = []; }
|
|
430
397
|
if (exclude === void 0) { exclude = []; }
|
|
431
398
|
return tslib_1.__awaiter(this, void 0, void 0, function () {
|
|
432
|
-
var
|
|
399
|
+
var jsonBody;
|
|
433
400
|
return tslib_1.__generator(this, function (_a) {
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
text = _a.sent();
|
|
442
|
-
return [2 /*return*/, safeParseAndPruneBody(text, allow, exclude)];
|
|
401
|
+
if (allow.length === 0) {
|
|
402
|
+
return [2 /*return*/, null];
|
|
403
|
+
}
|
|
404
|
+
jsonBody = this.getJson();
|
|
405
|
+
if (jsonBody) {
|
|
406
|
+
(0, json_query_1.pruneJson)(jsonBody, allow, exclude);
|
|
407
|
+
return [2 /*return*/, jsonBody];
|
|
443
408
|
}
|
|
409
|
+
return [2 /*return*/, null];
|
|
444
410
|
});
|
|
445
411
|
});
|
|
446
412
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-request-event.js","sourceRoot":"","sources":["../../src/network-request-event.ts"],"names":[],"mappings":";;;;AAAA,+CAAgD;AAChD,iDAA+C;AAC/C,uBAAqD;AA2DrD,IAAM,iBAAiB,GAAG,GAAG,CAAC;AAmCjB,QAAA,eAAe,GAAG,GAAG,CAAC;AAEnC;;;GAGG;AACH;IAAA;QACU,YAAO,GAAG,KAAK,CAAC;QAChB,SAAI,GAAG,KAAK,CAAC;IAQvB,CAAC;IANC,kCAAO,GAAP,UAAQ,OAA2B;QACjC,IAAI,IAAI,CAAC,OAAO,CAAC,EAAE;YACjB,MAAM,IAAI,SAAS,CAAC,UAAG,OAAO,+BAA4B,CAAC,CAAC;SAC7D;QACD,IAAI,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;IACvB,CAAC;IACH,uBAAC;AAAD,CAAC,AAVD,IAUC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH;IAGE,6BAAoB,OAAwB;QAAxB,YAAO,GAAP,OAAO,CAAiB;QADpC,qBAAg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C;AAAD,CAAC,AAzCD,IAyCC;AAzCY,kDAAmB","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 is used to enforce the consumption of headers and body\n * so that 'headers' and 'body' can only be accessed once.\n */\nclass ConsumptionCheck {\n private headers = false;\n private body = false;\n\n consume(objType: 'headers' | 'body') {\n if (this[objType]) {\n throw new TypeError(`${objType} has already been consumed`);\n }\n this[objType] = true;\n }\n}\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 private consumptionCheck: ConsumptionCheck = new ConsumptionCheck();\n constructor(private request: RequestInitSafe) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n this.consumptionCheck.consume('headers');\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 this.consumptionCheck.consume('body');\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 private consumptionCheck: ConsumptionCheck = new ConsumptionCheck();\n constructor(readonly bodyRaw: XMLHttpRequestBodyInitSafe | null, readonly requestHeaders: Record<string, string>) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n this.consumptionCheck.consume('headers');\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 this.consumptionCheck.consume('body');\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 consumptionCheck: ConsumptionCheck = new ConsumptionCheck();\n constructor(private response: ResponseSafe) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n this.consumptionCheck.consume('headers');\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 this.consumptionCheck.consume('body');\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 const clonedResponse = this.response.clone();\n try {\n const textPromise = 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 private consumptionCheck: ConsumptionCheck = new ConsumptionCheck();\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 this.consumptionCheck.consume('body');\n return this.responseText;\n }\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n this.consumptionCheck.consume('headers');\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-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C;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,0CAAK,eAAY,UAAE;YAC/D,eAAe,EAAE,MAAA,IAAI,CAAC,cAAc,0CAAE,QAAQ;YAC9C,eAAe,EAAE,MAAA,IAAI,CAAC,eAAe,0CAAE,OAAO,0CAAK,eAAY,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,qBAAM,EAAL,CAAC,QAAA,EAAE,CAAC,QAAA;YAAM,OAAA,CAAC,KAAK,SAAS;QAAf,CAAe,CAAC,CAAC,CAAC;IAC5F,CAAC;IACH,0BAAC;AAAD,CAAC,AAzCD,IAyCC;AAzCY,kDAAmB","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"]}
|
|
@@ -68,6 +68,13 @@ export interface ElementInteractionsOptions {
|
|
|
68
68
|
triggers: Trigger[];
|
|
69
69
|
labeledEvents: Record<string, LabeledEvent>;
|
|
70
70
|
};
|
|
71
|
+
/**
|
|
72
|
+
* RegExp pattern list to allow custom patterns for text masking
|
|
73
|
+
*/
|
|
74
|
+
maskTextRegex?: (RegExp | {
|
|
75
|
+
pattern: string;
|
|
76
|
+
description: string;
|
|
77
|
+
})[];
|
|
71
78
|
}
|
|
72
79
|
type MatchingCondition = {
|
|
73
80
|
type: 'LABELED_EVENT';
|