@amplitude/analytics-core 2.12.1-networktrackingprereleasemay.0 → 2.12.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/lib/cjs/network-observer.d.ts +1 -1
- package/lib/cjs/network-observer.d.ts.map +1 -1
- package/lib/cjs/network-observer.js +3 -3
- package/lib/cjs/network-observer.js.map +1 -1
- package/lib/cjs/network-request-event.d.ts +2 -2
- package/lib/cjs/network-request-event.d.ts.map +1 -1
- package/lib/cjs/network-request-event.js +1 -0
- package/lib/cjs/network-request-event.js.map +1 -1
- package/lib/cjs/storage/cookie.js +5 -5
- package/lib/cjs/storage/cookie.js.map +1 -1
- package/lib/esm/network-observer.d.ts +1 -1
- package/lib/esm/network-observer.d.ts.map +1 -1
- package/lib/esm/network-observer.js +1 -1
- package/lib/esm/network-observer.js.map +1 -1
- package/lib/esm/network-request-event.d.ts +2 -2
- package/lib/esm/network-request-event.d.ts.map +1 -1
- package/lib/esm/network-request-event.js +1 -0
- package/lib/esm/network-request-event.js.map +1 -1
- package/lib/esm/storage/cookie.js +5 -5
- package/lib/esm/storage/cookie.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-observer.d.ts","sourceRoot":"","sources":["../../src/network-observer.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,MAAM,
|
|
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;AAmBjC,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;AAmBD,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;IA4B/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,OAAO,CAAC,UAAU;CAyFnB;AAGD,eAAO,MAAM,eAAe,iBAAwB,CAAC"}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.networkObserver = exports.NetworkObserver = exports.NetworkEventCallback = void 0;
|
|
4
4
|
var tslib_1 = require("tslib");
|
|
5
|
-
var
|
|
5
|
+
var global_scope_1 = require("./global-scope");
|
|
6
6
|
var uuid_1 = require("./utils/uuid");
|
|
7
7
|
var network_request_event_1 = require("./network-request-event");
|
|
8
8
|
/**
|
|
@@ -25,7 +25,7 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
25
25
|
this.eventCallbacks = new Map();
|
|
26
26
|
this.isObserving = false;
|
|
27
27
|
this.logger = logger;
|
|
28
|
-
var globalScope = (0,
|
|
28
|
+
var globalScope = (0, global_scope_1.getGlobalScope)();
|
|
29
29
|
if (!NetworkObserver.isSupported()) {
|
|
30
30
|
/* istanbul ignore next */
|
|
31
31
|
return;
|
|
@@ -33,7 +33,7 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
33
33
|
this.globalScope = globalScope;
|
|
34
34
|
}
|
|
35
35
|
NetworkObserver.isSupported = function () {
|
|
36
|
-
var globalScope = (0,
|
|
36
|
+
var globalScope = (0, global_scope_1.getGlobalScope)();
|
|
37
37
|
return !!globalScope && !!globalScope.fetch;
|
|
38
38
|
};
|
|
39
39
|
NetworkObserver.prototype.subscribe = function (eventCallback, logger) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-observer.js","sourceRoot":"","sources":["../../src/network-observer.ts"],"names":[],"mappings":";;;;AAAA,uBAAoC;AACpC,qCAAoC;AAEpC,iEAUiC;AAYjC;;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;AAqBjC;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,CAAC;IAEM,2BAAW,GAAlB;QACE,IAAM,WAAW,GAAG,IAAA,iBAAc,GAAE,CAAC;QACrC,OA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,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;IACJ,CAAC;IACH,sBAAC;AAAD,CAAC,AA7RD,IA6RC;AA7RY,0CAAe;AA+R5B,wCAAwC;AAC3B,QAAA,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC","sourcesContent":["import { getGlobalScope } from './';\nimport { UUID } from './utils/uuid';\nimport { ILogger } from '.';\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};\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 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 if (originalXhrOpen && originalXhrSend) {\n this.observeXhr(originalXhrOpen, originalXhrSend);\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 ) {\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 ...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 );\n const requestWrapper = new RequestWrapperXhr(body);\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\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,+CAAgD;AAChD,qCAAoC;AAEpC,iEAUiC;AAYjC;;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;AAqBjC;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,6BAAc,GAAE,CAAC;QACrC,IAAI,CAAC,eAAe,CAAC,WAAW,EAAE,EAAE;YAClC,0BAA0B;YAC1B,OAAO;SACR;QACD,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;IAEM,2BAAW,GAAlB;QACE,IAAM,WAAW,GAAG,IAAA,6BAAc,GAAE,CAAC;QACrC,OAAO,CAAC,CAAC,WAAW,IAAI,CAAC,CAAC,WAAW,CAAC,KAAK,CAAC;IAC9C,CAAC;IAED,mCAAS,GAAT,UAAU,aAAmC,EAAE,MAAgB;;QAC7D,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;YAChB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;SACtB;QACD,IAAI,CAA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C1B,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;IACJ,CAAC;IACH,sBAAC;AAAD,CAAC,AA7RD,IA6RC;AA7RY,0CAAe;AA+R5B,wCAAwC;AAC3B,QAAA,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC","sourcesContent":["import { getGlobalScope } from './global-scope';\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};\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 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 if (originalXhrOpen && originalXhrSend) {\n this.observeXhr(originalXhrOpen, originalXhrSend);\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 ) {\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 ...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 );\n const requestWrapper = new RequestWrapperXhr(body);\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\n// singleton instance of NetworkObserver\nexport const networkObserver = new NetworkObserver();\n"]}
|
|
@@ -123,7 +123,7 @@ export declare class NetworkRequestEvent {
|
|
|
123
123
|
readonly startTime: number;
|
|
124
124
|
readonly url?: string | undefined;
|
|
125
125
|
readonly requestWrapper?: IRequestWrapper | undefined;
|
|
126
|
-
readonly status
|
|
126
|
+
readonly status: number;
|
|
127
127
|
readonly duration?: number | undefined;
|
|
128
128
|
readonly responseWrapper?: IResponseWrapper | undefined;
|
|
129
129
|
readonly error?: {
|
|
@@ -131,7 +131,7 @@ export declare class NetworkRequestEvent {
|
|
|
131
131
|
message: string;
|
|
132
132
|
} | undefined;
|
|
133
133
|
readonly endTime?: number | undefined;
|
|
134
|
-
constructor(type: 'xhr' | 'fetch', method: string, timestamp: number, startTime: number, url?: string | undefined, requestWrapper?: IRequestWrapper | undefined, status?: number
|
|
134
|
+
constructor(type: 'xhr' | 'fetch', method: string, timestamp: number, startTime: number, url?: string | undefined, requestWrapper?: IRequestWrapper | undefined, status?: number, duration?: number | undefined, responseWrapper?: IResponseWrapper | undefined, error?: {
|
|
135
135
|
name: string;
|
|
136
136
|
message: string;
|
|
137
137
|
} | undefined, endTime?: number | undefined);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-request-event.d.ts","sourceRoot":"","sources":["../../src/network-request-event.ts"],"names":[],"mappings":"AAMA,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;IAC9C,OAA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
|
|
293
293
|
var NetworkRequestEvent = /** @class */ (function () {
|
|
294
294
|
function NetworkRequestEvent(type, method, timestamp, startTime, url, requestWrapper, status, duration, responseWrapper, error, endTime) {
|
|
295
|
+
if (status === void 0) { status = 0; }
|
|
295
296
|
this.type = type;
|
|
296
297
|
this.method = method;
|
|
297
298
|
this.timestamp = timestamp;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-request-event.js","sourceRoot":"","sources":["../../src/network-request-event.ts"],"names":[],"mappings":";;;;AAAA,+CAAgD;AAiFnC,QAAA,eAAe,GAAG,GAAG,CAAC;AAEnC;;;;;;;;;;;;;;;;;GAiBG;AACH;IAGE,6BAAoB,OAAwB;QAAxB,YAAO,GAAP,OAAO,CAAiB;IAAG,CAAC;IAEhD,sBAAI,wCAAO;aAAX;YACE,IAAI,IAAI,CAAC,QAAQ;gBAAE,OAAO,IAAI,CAAC,QAAQ,CAAC;YAExC,IAAM,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;YAC3C,IAAI,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE;gBAChC,IAAM,OAAO,GAAG,aAAa,CAAC;gBAC9B,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,MAAM,CAAC,UAAC,GAAG,EAAE,EAAY;wBAAZ,KAAA,qBAAY,EAAX,GAAG,QAAA,EAAE,KAAK,QAAA;oBAC9C,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;oBACjB,OAAO,GAAG,CAAC;gBACb,CAAC,EAAE,EAA4B,CAAC,CAAC;aAClC;iBAAM,IAAI,aAAa,YAAY,OAAO,EAAE;gBAC3C,IAAM,WAAW,GAAG,aAAmC,CAAC;gBACxD,IAAM,YAAU,GAA2B,EAAE,CAAC;gBAC9C,WAAW,CAAC,OAAO,CAAC,UAAC,KAAK,EAAE,GAAG;oBAC7B,YAAU,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;gBAC1B,CAAC,CAAC,C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;YAC5C,eAAe,EAAE,MAAA,IAAI,CAAC,cAAc,0CAAE,QAAQ;YAC9C,eAAe,EAAE,MAAA,IAAI,CAAC,eAAe,0CAAE,OAAO;YAC9C,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,AArCD,IAqCC;AArCY,kDAAmB","sourcesContent":["import { getGlobalScope } from './global-scope';\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};\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 headers?: Record<string, string>;\n bodySize?: number;\n method?: string;\n body?: FetchRequestBody | XMLHttpRequestBodyInitSafe | 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 _headers: Record<string, string> | undefined;\n private _bodySize: number | undefined;\n constructor(private request: RequestInitSafe) {}\n\n get headers(): Record<string, string> | undefined {\n if (this._headers) return this._headers;\n\n const headersUnsafe = this.request.headers;\n if (Array.isArray(headersUnsafe)) {\n const headers = headersUnsafe;\n this._headers = headers.reduce((acc, [key, value]) => {\n acc[key] = value;\n return acc;\n }, {} as Record<string, string>);\n } else if (headersUnsafe instanceof Headers) {\n const headersSafe = headersUnsafe as HeadersRequestSafe;\n const headersObj: Record<string, string> = {};\n headersSafe.forEach((value, key) => {\n headersObj[key] = value;\n });\n this._headers = headersObj;\n } else if (typeof headersUnsafe === 'object') {\n this._headers = headersUnsafe as Record<string, string>;\n }\n\n return this._headers;\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\nexport class RequestWrapperXhr implements IRequestWrapper {\n constructor(readonly body: XMLHttpRequestBodyInitSafe | null) {}\n\n get bodySize(): number | undefined {\n return getBodySize(this.body as FetchRequestBody, MAXIMUM_ENTRIES);\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 interface IResponseWrapper {\n headers?: Record<string, string>;\n bodySize?: number;\n status?: number;\n body?: string | Blob | ReadableStream | ArrayBuffer | FormDataSafe | URLSearchParams | ArrayBufferView | 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 * * NEVER .clone() the Response object. This will 2x's 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 _headers: Record<string, string> | undefined;\n private _bodySize: number | undefined;\n constructor(private response: ResponseSafe) {}\n\n get headers(): Record<string, string> | undefined {\n if (this._headers) return this._headers;\n\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 this._headers = headersOut;\n return headersOut;\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\nexport class ResponseWrapperXhr implements IResponseWrapper {\n constructor(readonly statusCode: number, readonly headersString: string, readonly size: number | undefined) {}\n\n get bodySize(): number | undefined {\n return this.size;\n }\n\n get status(): number {\n return this.statusCode;\n }\n\n get headers(): 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 headers;\n }\n}\n\nexport class NetworkRequestEvent {\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,\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,\n requestBodySize: this.requestWrapper?.bodySize,\n responseHeaders: this.responseWrapper?.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,+CAAgD;AAiFnC,QAAA,eAAe,GAAG,GAAG,CAAC;AAEnC;;;;;;;;;;;;;;;;;GAiBG;AACH;IAGE,6BAAoB,OAAwB;QAAxB,YAAO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C;IACH,0BAAC;AAAD,CAAC,AArCD,IAqCC;AArCY,kDAAmB","sourcesContent":["import { getGlobalScope } from './global-scope';\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};\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 headers?: Record<string, string>;\n bodySize?: number;\n method?: string;\n body?: FetchRequestBody | XMLHttpRequestBodyInitSafe | 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 _headers: Record<string, string> | undefined;\n private _bodySize: number | undefined;\n constructor(private request: RequestInitSafe) {}\n\n get headers(): Record<string, string> | undefined {\n if (this._headers) return this._headers;\n\n const headersUnsafe = this.request.headers;\n if (Array.isArray(headersUnsafe)) {\n const headers = headersUnsafe;\n this._headers = headers.reduce((acc, [key, value]) => {\n acc[key] = value;\n return acc;\n }, {} as Record<string, string>);\n } else if (headersUnsafe instanceof Headers) {\n const headersSafe = headersUnsafe as HeadersRequestSafe;\n const headersObj: Record<string, string> = {};\n headersSafe.forEach((value, key) => {\n headersObj[key] = value;\n });\n this._headers = headersObj;\n } else if (typeof headersUnsafe === 'object') {\n this._headers = headersUnsafe as Record<string, string>;\n }\n\n return this._headers;\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\nexport class RequestWrapperXhr implements IRequestWrapper {\n constructor(readonly body: XMLHttpRequestBodyInitSafe | null) {}\n\n get bodySize(): number | undefined {\n return getBodySize(this.body as FetchRequestBody, MAXIMUM_ENTRIES);\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 interface IResponseWrapper {\n headers?: Record<string, string>;\n bodySize?: number;\n status?: number;\n body?: string | Blob | ReadableStream | ArrayBuffer | FormDataSafe | URLSearchParams | ArrayBufferView | 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 * * NEVER .clone() the Response object. This will 2x's 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 _headers: Record<string, string> | undefined;\n private _bodySize: number | undefined;\n constructor(private response: ResponseSafe) {}\n\n get headers(): Record<string, string> | undefined {\n if (this._headers) return this._headers;\n\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 this._headers = headersOut;\n return headersOut;\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\nexport class ResponseWrapperXhr implements IResponseWrapper {\n constructor(readonly statusCode: number, readonly headersString: string, readonly size: number | undefined) {}\n\n get bodySize(): number | undefined {\n return this.size;\n }\n\n get status(): number {\n return this.statusCode;\n }\n\n get headers(): 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 headers;\n }\n}\n\nexport class NetworkRequestEvent {\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,\n requestBodySize: this.requestWrapper?.bodySize,\n responseHeaders: this.responseWrapper?.headers,\n responseBodySize: this.responseWrapper?.bodySize,\n };\n\n return Object.fromEntries(Object.entries(serialized).filter(([_, v]) => v !== undefined));\n }\n}\n"]}
|
|
@@ -9,7 +9,7 @@ var CookieStorage = /** @class */ (function () {
|
|
|
9
9
|
}
|
|
10
10
|
CookieStorage.prototype.isEnabled = function () {
|
|
11
11
|
return tslib_1.__awaiter(this, void 0, void 0, function () {
|
|
12
|
-
var
|
|
12
|
+
var testStorage, testKey, value, _a;
|
|
13
13
|
return tslib_1.__generator(this, function (_b) {
|
|
14
14
|
switch (_b.label) {
|
|
15
15
|
case 0:
|
|
@@ -18,15 +18,15 @@ var CookieStorage = /** @class */ (function () {
|
|
|
18
18
|
return [2 /*return*/, false];
|
|
19
19
|
}
|
|
20
20
|
CookieStorage.testValue = String(Date.now());
|
|
21
|
-
|
|
21
|
+
testStorage = new CookieStorage(this.options);
|
|
22
22
|
testKey = 'AMP_TEST';
|
|
23
23
|
_b.label = 1;
|
|
24
24
|
case 1:
|
|
25
25
|
_b.trys.push([1, 4, 5, 7]);
|
|
26
|
-
return [4 /*yield*/,
|
|
26
|
+
return [4 /*yield*/, testStorage.set(testKey, CookieStorage.testValue)];
|
|
27
27
|
case 2:
|
|
28
28
|
_b.sent();
|
|
29
|
-
return [4 /*yield*/,
|
|
29
|
+
return [4 /*yield*/, testStorage.get(testKey)];
|
|
30
30
|
case 3:
|
|
31
31
|
value = _b.sent();
|
|
32
32
|
return [2 /*return*/, value === CookieStorage.testValue];
|
|
@@ -34,7 +34,7 @@ var CookieStorage = /** @class */ (function () {
|
|
|
34
34
|
_a = _b.sent();
|
|
35
35
|
/* istanbul ignore next */
|
|
36
36
|
return [2 /*return*/, false];
|
|
37
|
-
case 5: return [4 /*yield*/,
|
|
37
|
+
case 5: return [4 /*yield*/, testStorage.remove(testKey)];
|
|
38
38
|
case 6:
|
|
39
39
|
_b.sent();
|
|
40
40
|
return [7 /*endfinally*/];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cookie.js","sourceRoot":"","sources":["../../../src/storage/cookie.ts"],"names":[],"mappings":";;;;AACA,gDAAiD;AAEjD;IAIE,uBAAY,OAA8B;QACxC,IAAI,CAAC,OAAO,wBAAQ,OAAO,CAAE,CAAC;IAChC,CAAC;IAEK,iCAAS,GAAf;;;;;;wBACE,wBAAwB;wBACxB,IAAI,CAAC,IAAA,6BAAc,GAAE,EAAE;4BACrB,sBAAO,KAAK,EAAC;yBACd;wBAED,aAAa,CAAC,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;wBACvC,
|
|
1
|
+
{"version":3,"file":"cookie.js","sourceRoot":"","sources":["../../../src/storage/cookie.ts"],"names":[],"mappings":";;;;AACA,gDAAiD;AAEjD;IAIE,uBAAY,OAA8B;QACxC,IAAI,CAAC,OAAO,wBAAQ,OAAO,CAAE,CAAC;IAChC,CAAC;IAEK,iCAAS,GAAf;;;;;;wBACE,wBAAwB;wBACxB,IAAI,CAAC,IAAA,6BAAc,GAAE,EAAE;4BACrB,sBAAO,KAAK,EAAC;yBACd;wBAED,aAAa,CAAC,SAAS,GAAG,MAAM,CAAC,IAAI,C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AC,KAAK,CAAC,CAAC,CAAC,CAAC;KAC5D;IAAC,WAAM;QACN,OAAO,SAAS,CAAC;KAClB;AACH,CAAC,CAAC","sourcesContent":["import { Storage, CookieStorageOptions } from '../types/storage';\nimport { getGlobalScope } from '../global-scope';\n\nexport class CookieStorage<T> implements Storage<T> {\n options: CookieStorageOptions;\n private static testValue: undefined | string;\n\n constructor(options?: CookieStorageOptions) {\n this.options = { ...options };\n }\n\n async isEnabled(): Promise<boolean> {\n /* istanbul ignore if */\n if (!getGlobalScope()) {\n return false;\n }\n\n CookieStorage.testValue = String(Date.now());\n const testStorage = new CookieStorage<string>(this.options);\n const testKey = 'AMP_TEST';\n try {\n await testStorage.set(testKey, CookieStorage.testValue);\n const value = await testStorage.get(testKey);\n return value === CookieStorage.testValue;\n } catch {\n /* istanbul ignore next */\n return false;\n } finally {\n await testStorage.remove(testKey);\n }\n }\n\n async get(key: string): Promise<T | undefined> {\n const value = await this.getRaw(key);\n if (!value) {\n return undefined;\n }\n try {\n const decodedValue = decodeCookiesAsDefault(value) ?? decodeCookiesWithDoubleUrlEncoding(value);\n if (decodedValue === undefined) {\n console.error(`Amplitude Logger [Error]: Failed to decode cookie value for key: ${key}, value: ${value}`);\n return undefined;\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return JSON.parse(decodedValue);\n } catch {\n console.error(`Amplitude Logger [Error]: Failed to parse cookie value for key: ${key}, value: ${value}`);\n return undefined;\n }\n }\n\n async getRaw(key: string): Promise<string | undefined> {\n const globalScope = getGlobalScope();\n const cookie = globalScope?.document?.cookie.split('; ') ?? [];\n const match = cookie.find((c) => c.indexOf(key + '=') === 0);\n if (!match) {\n return undefined;\n }\n return match.substring(key.length + 1);\n }\n\n async set(key: string, value: T | null): Promise<void> {\n try {\n const expirationDays = this.options.expirationDays ?? 0;\n const expires = value !== null ? expirationDays : -1;\n let expireDate: Date | undefined = undefined;\n if (expires) {\n const date = new Date();\n date.setTime(date.getTime() + expires * 24 * 60 * 60 * 1000);\n expireDate = date;\n }\n let str = `${key}=${btoa(encodeURIComponent(JSON.stringify(value)))}`;\n if (expireDate) {\n str += `; expires=${expireDate.toUTCString()}`;\n }\n str += '; path=/';\n if (this.options.domain) {\n str += `; domain=${this.options.domain}`;\n }\n if (this.options.secure) {\n str += '; Secure';\n }\n if (this.options.sameSite) {\n str += `; SameSite=${this.options.sameSite}`;\n }\n const globalScope = getGlobalScope();\n if (globalScope) {\n globalScope.document.cookie = str;\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n console.error(`Amplitude Logger [Error]: Failed to set cookie for key: ${key}. Error: ${errorMessage}`);\n }\n }\n\n async remove(key: string): Promise<void> {\n await this.set(key, null);\n }\n\n async reset(): Promise<void> {\n return;\n }\n}\n\nconst decodeCookiesAsDefault = (value: string): string | undefined => {\n try {\n return decodeURIComponent(atob(value));\n } catch {\n return undefined;\n }\n};\n\nconst decodeCookiesWithDoubleUrlEncoding = (value: string): string | undefined => {\n // Modern Ruby (v7+) automatically encodes cookies with URL encoding by\n // https://api.rubyonrails.org/classes/ActionDispatch/Cookies.html\n try {\n return decodeURIComponent(atob(decodeURIComponent(value)));\n } catch {\n return undefined;\n }\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-observer.d.ts","sourceRoot":"","sources":["../../src/network-observer.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,MAAM,
|
|
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;AAmBjC,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;AAmBD,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;IA4B/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,OAAO,CAAC,UAAU;CAyFnB;AAGD,eAAO,MAAM,eAAe,iBAAwB,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { __assign, __awaiter, __generator, __read } from "tslib";
|
|
2
|
-
import { getGlobalScope } from './';
|
|
2
|
+
import { getGlobalScope } from './global-scope';
|
|
3
3
|
import { UUID } from './utils/uuid';
|
|
4
4
|
import { NetworkRequestEvent, RequestWrapperFetch, ResponseWrapperFetch, RequestWrapperXhr, ResponseWrapperXhr, } from './network-request-event';
|
|
5
5
|
/**
|
|
@@ -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,yBAA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;AAAD,CAAC,AA7RD,IA6RC;;AAED,wCAAwC;AACxC,MAAM,CAAC,IAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC","sourcesContent":["import { getGlobalScope } from './';\nimport { UUID } from './utils/uuid';\nimport { ILogger } from '.';\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};\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 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 if (originalXhrOpen && originalXhrSend) {\n this.observeXhr(originalXhrOpen, originalXhrSend);\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 ) {\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 ...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 );\n const requestWrapper = new RequestWrapperXhr(body);\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\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,gBAAgB,CAAC;AAChD,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAEpC,OAAO,EAEL,mBAAmB,EACnB,mBAAmB,EACnB,oBAAoB,EACpB,iBAAiB,EACjB,kBAAkB,GAInB,MAAM,yBAAyB,CAAC;AAYjC;;GAEG;AACH,SAAS,SAAS,CAAC,WAAgB;IACjC,OAAO,OAAO,WAAW,KAAK,QAAQ,IAAI,WAAW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sourcesContent":["import { getGlobalScope } from './global-scope';\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};\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 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 if (originalXhrOpen && originalXhrSend) {\n this.observeXhr(originalXhrOpen, originalXhrSend);\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 ) {\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 ...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 );\n const requestWrapper = new RequestWrapperXhr(body);\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\n// singleton instance of NetworkObserver\nexport const networkObserver = new NetworkObserver();\n"]}
|
|
@@ -123,7 +123,7 @@ export declare class NetworkRequestEvent {
|
|
|
123
123
|
readonly startTime: number;
|
|
124
124
|
readonly url?: string | undefined;
|
|
125
125
|
readonly requestWrapper?: IRequestWrapper | undefined;
|
|
126
|
-
readonly status
|
|
126
|
+
readonly status: number;
|
|
127
127
|
readonly duration?: number | undefined;
|
|
128
128
|
readonly responseWrapper?: IResponseWrapper | undefined;
|
|
129
129
|
readonly error?: {
|
|
@@ -131,7 +131,7 @@ export declare class NetworkRequestEvent {
|
|
|
131
131
|
message: string;
|
|
132
132
|
} | undefined;
|
|
133
133
|
readonly endTime?: number | undefined;
|
|
134
|
-
constructor(type: 'xhr' | 'fetch', method: string, timestamp: number, startTime: number, url?: string | undefined, requestWrapper?: IRequestWrapper | undefined, status?: number
|
|
134
|
+
constructor(type: 'xhr' | 'fetch', method: string, timestamp: number, startTime: number, url?: string | undefined, requestWrapper?: IRequestWrapper | undefined, status?: number, duration?: number | undefined, responseWrapper?: IResponseWrapper | undefined, error?: {
|
|
135
135
|
name: string;
|
|
136
136
|
message: string;
|
|
137
137
|
} | undefined, endTime?: number | undefined);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-request-event.d.ts","sourceRoot":"","sources":["../../src/network-request-event.ts"],"names":[],"mappings":"AAMA,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;IAC9C,OAAO,CAAC,UAAU,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,KAAK,IAAI,GAAG,IAAI,CAAC;CACjE,CAAC;AAEF,KAAK,mBAAmB,GAAG;IACzB,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;IACjC,OAAO,CAAC,UAAU,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,KAAK,IAAI,GAAG,IAAI,CAAC;CACjE,CAAC;AAEF,KAAK,eAAe,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AAS,CAEjC;IAED,IAAI,MAAM,IAAI,MAAM,CAEnB;IAED,IAAI,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,CAahD;CACF;AAED,qBAAa,mBAAmB;aAEZ,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;gBAbR,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"}
|
|
@@ -289,6 +289,7 @@ var ResponseWrapperXhr = /** @class */ (function () {
|
|
|
289
289
|
export { ResponseWrapperXhr };
|
|
290
290
|
var NetworkRequestEvent = /** @class */ (function () {
|
|
291
291
|
function NetworkRequestEvent(type, method, timestamp, startTime, url, requestWrapper, status, duration, responseWrapper, error, endTime) {
|
|
292
|
+
if (status === void 0) { status = 0; }
|
|
292
293
|
this.type = type;
|
|
293
294
|
this.method = method;
|
|
294
295
|
this.timestamp = timestamp;
|
|
@@ -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,gB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C;IAC5F,CAAC;IACH,0BAAC;AAAD,CAAC,AArCD,IAqCC","sourcesContent":["import { getGlobalScope } from './global-scope';\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};\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 headers?: Record<string, string>;\n bodySize?: number;\n method?: string;\n body?: FetchRequestBody | XMLHttpRequestBodyInitSafe | 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 _headers: Record<string, string> | undefined;\n private _bodySize: number | undefined;\n constructor(private request: RequestInitSafe) {}\n\n get headers(): Record<string, string> | undefined {\n if (this._headers) return this._headers;\n\n const headersUnsafe = this.request.headers;\n if (Array.isArray(headersUnsafe)) {\n const headers = headersUnsafe;\n this._headers = headers.reduce((acc, [key, value]) => {\n acc[key] = value;\n return acc;\n }, {} as Record<string, string>);\n } else if (headersUnsafe instanceof Headers) {\n const headersSafe = headersUnsafe as HeadersRequestSafe;\n const headersObj: Record<string, string> = {};\n headersSafe.forEach((value, key) => {\n headersObj[key] = value;\n });\n this._headers = headersObj;\n } else if (typeof headersUnsafe === 'object') {\n this._headers = headersUnsafe as Record<string, string>;\n }\n\n return this._headers;\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\nexport class RequestWrapperXhr implements IRequestWrapper {\n constructor(readonly body: XMLHttpRequestBodyInitSafe | null) {}\n\n get bodySize(): number | undefined {\n return getBodySize(this.body as FetchRequestBody, MAXIMUM_ENTRIES);\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 interface IResponseWrapper {\n headers?: Record<string, string>;\n bodySize?: number;\n status?: number;\n body?: string | Blob | ReadableStream | ArrayBuffer | FormDataSafe | URLSearchParams | ArrayBufferView | 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 * * NEVER .clone() the Response object. This will 2x's 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 _headers: Record<string, string> | undefined;\n private _bodySize: number | undefined;\n constructor(private response: ResponseSafe) {}\n\n get headers(): Record<string, string> | undefined {\n if (this._headers) return this._headers;\n\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 this._headers = headersOut;\n return headersOut;\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\nexport class ResponseWrapperXhr implements IResponseWrapper {\n constructor(readonly statusCode: number, readonly headersString: string, readonly size: number | undefined) {}\n\n get bodySize(): number | undefined {\n return this.size;\n }\n\n get status(): number {\n return this.statusCode;\n }\n\n get headers(): 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 headers;\n }\n}\n\nexport class NetworkRequestEvent {\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,\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,\n requestBodySize: this.requestWrapper?.bodySize,\n responseHeaders: this.responseWrapper?.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;AAiFhD,MAAM,CAAC,IAAM,eAAe,GAAG,GAAG,CAAC;AAEnC;;;;;;;;;;;;;;;;;GAiBG;AACH;IAGE,6BAAoB,OAAwB;QAAxB,YAAO,GAAP,OAAO,CAAiB;IAAG,CAAC;IAEhD,sBAAI,wCAAO;aAAX;YACE,IAAI,IAAI,CAAC,QAAQ;gBAAE,OAAO,IAAI,CAAC,QAAQ,CAAC;YAExC,IAAM,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;YAC3C,IAAI,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE;gBAChC,IAAM,OAAO,GAAG,aAAa,CAAC;gBAC9B,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,MAAM,CAAC,UAAC,GAAG,EAAE,EAAY;wBAAZ,KA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,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;YAC5C,eAAe,EAAE,MAAA,IAAI,CAAC,cAAc,0CAAE,QAAQ;YAC9C,eAAe,EAAE,MAAA,IAAI,CAAC,eAAe,0CAAE,OAAO;YAC9C,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,AArCD,IAqCC","sourcesContent":["import { getGlobalScope } from './global-scope';\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};\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 headers?: Record<string, string>;\n bodySize?: number;\n method?: string;\n body?: FetchRequestBody | XMLHttpRequestBodyInitSafe | 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 _headers: Record<string, string> | undefined;\n private _bodySize: number | undefined;\n constructor(private request: RequestInitSafe) {}\n\n get headers(): Record<string, string> | undefined {\n if (this._headers) return this._headers;\n\n const headersUnsafe = this.request.headers;\n if (Array.isArray(headersUnsafe)) {\n const headers = headersUnsafe;\n this._headers = headers.reduce((acc, [key, value]) => {\n acc[key] = value;\n return acc;\n }, {} as Record<string, string>);\n } else if (headersUnsafe instanceof Headers) {\n const headersSafe = headersUnsafe as HeadersRequestSafe;\n const headersObj: Record<string, string> = {};\n headersSafe.forEach((value, key) => {\n headersObj[key] = value;\n });\n this._headers = headersObj;\n } else if (typeof headersUnsafe === 'object') {\n this._headers = headersUnsafe as Record<string, string>;\n }\n\n return this._headers;\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\nexport class RequestWrapperXhr implements IRequestWrapper {\n constructor(readonly body: XMLHttpRequestBodyInitSafe | null) {}\n\n get bodySize(): number | undefined {\n return getBodySize(this.body as FetchRequestBody, MAXIMUM_ENTRIES);\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 interface IResponseWrapper {\n headers?: Record<string, string>;\n bodySize?: number;\n status?: number;\n body?: string | Blob | ReadableStream | ArrayBuffer | FormDataSafe | URLSearchParams | ArrayBufferView | 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 * * NEVER .clone() the Response object. This will 2x's 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 _headers: Record<string, string> | undefined;\n private _bodySize: number | undefined;\n constructor(private response: ResponseSafe) {}\n\n get headers(): Record<string, string> | undefined {\n if (this._headers) return this._headers;\n\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 this._headers = headersOut;\n return headersOut;\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\nexport class ResponseWrapperXhr implements IResponseWrapper {\n constructor(readonly statusCode: number, readonly headersString: string, readonly size: number | undefined) {}\n\n get bodySize(): number | undefined {\n return this.size;\n }\n\n get status(): number {\n return this.statusCode;\n }\n\n get headers(): 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 headers;\n }\n}\n\nexport class NetworkRequestEvent {\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,\n requestBodySize: this.requestWrapper?.bodySize,\n responseHeaders: this.responseWrapper?.headers,\n responseBodySize: this.responseWrapper?.bodySize,\n };\n\n return Object.fromEntries(Object.entries(serialized).filter(([_, v]) => v !== undefined));\n }\n}\n"]}
|
|
@@ -6,7 +6,7 @@ var CookieStorage = /** @class */ (function () {
|
|
|
6
6
|
}
|
|
7
7
|
CookieStorage.prototype.isEnabled = function () {
|
|
8
8
|
return __awaiter(this, void 0, void 0, function () {
|
|
9
|
-
var
|
|
9
|
+
var testStorage, testKey, value, _a;
|
|
10
10
|
return __generator(this, function (_b) {
|
|
11
11
|
switch (_b.label) {
|
|
12
12
|
case 0:
|
|
@@ -15,15 +15,15 @@ var CookieStorage = /** @class */ (function () {
|
|
|
15
15
|
return [2 /*return*/, false];
|
|
16
16
|
}
|
|
17
17
|
CookieStorage.testValue = String(Date.now());
|
|
18
|
-
|
|
18
|
+
testStorage = new CookieStorage(this.options);
|
|
19
19
|
testKey = 'AMP_TEST';
|
|
20
20
|
_b.label = 1;
|
|
21
21
|
case 1:
|
|
22
22
|
_b.trys.push([1, 4, 5, 7]);
|
|
23
|
-
return [4 /*yield*/,
|
|
23
|
+
return [4 /*yield*/, testStorage.set(testKey, CookieStorage.testValue)];
|
|
24
24
|
case 2:
|
|
25
25
|
_b.sent();
|
|
26
|
-
return [4 /*yield*/,
|
|
26
|
+
return [4 /*yield*/, testStorage.get(testKey)];
|
|
27
27
|
case 3:
|
|
28
28
|
value = _b.sent();
|
|
29
29
|
return [2 /*return*/, value === CookieStorage.testValue];
|
|
@@ -31,7 +31,7 @@ var CookieStorage = /** @class */ (function () {
|
|
|
31
31
|
_a = _b.sent();
|
|
32
32
|
/* istanbul ignore next */
|
|
33
33
|
return [2 /*return*/, false];
|
|
34
|
-
case 5: return [4 /*yield*/,
|
|
34
|
+
case 5: return [4 /*yield*/, testStorage.remove(testKey)];
|
|
35
35
|
case 6:
|
|
36
36
|
_b.sent();
|
|
37
37
|
return [7 /*endfinally*/];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cookie.js","sourceRoot":"","sources":["../../../src/storage/cookie.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAEjD;IAIE,uBAAY,OAA8B;QACxC,IAAI,CAAC,OAAO,gBAAQ,OAAO,CAAE,CAAC;IAChC,CAAC;IAEK,iCAAS,GAAf;;;;;;wBACE,wBAAwB;wBACxB,IAAI,CAAC,cAAc,EAAE,EAAE;4BACrB,sBAAO,KAAK,EAAC;yBACd;wBAED,aAAa,CAAC,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;wBACvC,
|
|
1
|
+
{"version":3,"file":"cookie.js","sourceRoot":"","sources":["../../../src/storage/cookie.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAEjD;IAIE,uBAAY,OAA8B;QACxC,IAAI,CAAC,OAAO,gBAAQ,OAAO,CAAE,CAAC;IAChC,CAAC;IAEK,iCAAS,GAAf;;;;;;wBACE,wBAAwB;wBACxB,IAAI,CAAC,cAAc,EAAE,EAAE;4BACrB,sBAAO,KAAK,EAAC;yBACd;wBAED,aAAa,CAAC,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;wBACvC,WAAW,GAAG,IAAI,aAAa,CAAS,IAAI,CAAC,OAAO,CAAC,CAAC;wBACtD,OAAO,GAAG,UAAU,CAAC;;;;wBAEzB,qBAAM,WAAW,CAAC,GAAG,CAAC,OAAO,EAAE,aAAa,CAAC,SAAS,CAAC,EAAA;;wBAAvD,SAAuD,CAAC;wBAC1C,qBAAM,WAAW,CAAC,GAAG,CAAC,OAAO,CAAC,EAAA;;wBAAtC,KAAK,GAAG,SAA8B;wBAC5C,sBAAO,KAAK,KAAK,aAAa,CAAC,SAAS,EAAC;;;wBAEzC,0BAA0B;wBAC1B,sBAAO,KAAK,EAAC;4BAEb,qBAAM,WAAW,CA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OAAO,KAAK,EAAE;oBACR,YAAY,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;oBAC5E,OAAO,CAAC,KAAK,CAAC,kEAA2D,GAAG,sBAAY,YAAY,CAAE,CAAC,CAAC;iBACzG;;;;KACF;IAEK,8BAAM,GAAZ,UAAa,GAAW;;;;4BACtB,qBAAM,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,EAAA;;wBAAzB,SAAyB,CAAC;;;;;KAC3B;IAEK,6BAAK,GAAX;;;gBACE,sBAAO;;;KACR;IACH,oBAAC;AAAD,CAAC,AAnGD,IAmGC;;AAED,IAAM,sBAAsB,GAAG,UAAC,KAAa;IAC3C,IAAI;QACF,OAAO,kBAAkB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;KACxC;IAAC,WAAM;QACN,OAAO,SAAS,CAAC;KAClB;AACH,CAAC,CAAC;AAEF,IAAM,kCAAkC,GAAG,UAAC,KAAa;IACvD,uEAAuE;IACvE,kEAAkE;IAClE,IAAI;QACF,OAAO,kBAAkB,CAAC,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;KAC5D;IAAC,WAAM;QACN,OAAO,SAAS,CAAC;KAClB;AACH,CAAC,CAAC","sourcesContent":["import { Storage, CookieStorageOptions } from '../types/storage';\nimport { getGlobalScope } from '../global-scope';\n\nexport class CookieStorage<T> implements Storage<T> {\n options: CookieStorageOptions;\n private static testValue: undefined | string;\n\n constructor(options?: CookieStorageOptions) {\n this.options = { ...options };\n }\n\n async isEnabled(): Promise<boolean> {\n /* istanbul ignore if */\n if (!getGlobalScope()) {\n return false;\n }\n\n CookieStorage.testValue = String(Date.now());\n const testStorage = new CookieStorage<string>(this.options);\n const testKey = 'AMP_TEST';\n try {\n await testStorage.set(testKey, CookieStorage.testValue);\n const value = await testStorage.get(testKey);\n return value === CookieStorage.testValue;\n } catch {\n /* istanbul ignore next */\n return false;\n } finally {\n await testStorage.remove(testKey);\n }\n }\n\n async get(key: string): Promise<T | undefined> {\n const value = await this.getRaw(key);\n if (!value) {\n return undefined;\n }\n try {\n const decodedValue = decodeCookiesAsDefault(value) ?? decodeCookiesWithDoubleUrlEncoding(value);\n if (decodedValue === undefined) {\n console.error(`Amplitude Logger [Error]: Failed to decode cookie value for key: ${key}, value: ${value}`);\n return undefined;\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return JSON.parse(decodedValue);\n } catch {\n console.error(`Amplitude Logger [Error]: Failed to parse cookie value for key: ${key}, value: ${value}`);\n return undefined;\n }\n }\n\n async getRaw(key: string): Promise<string | undefined> {\n const globalScope = getGlobalScope();\n const cookie = globalScope?.document?.cookie.split('; ') ?? [];\n const match = cookie.find((c) => c.indexOf(key + '=') === 0);\n if (!match) {\n return undefined;\n }\n return match.substring(key.length + 1);\n }\n\n async set(key: string, value: T | null): Promise<void> {\n try {\n const expirationDays = this.options.expirationDays ?? 0;\n const expires = value !== null ? expirationDays : -1;\n let expireDate: Date | undefined = undefined;\n if (expires) {\n const date = new Date();\n date.setTime(date.getTime() + expires * 24 * 60 * 60 * 1000);\n expireDate = date;\n }\n let str = `${key}=${btoa(encodeURIComponent(JSON.stringify(value)))}`;\n if (expireDate) {\n str += `; expires=${expireDate.toUTCString()}`;\n }\n str += '; path=/';\n if (this.options.domain) {\n str += `; domain=${this.options.domain}`;\n }\n if (this.options.secure) {\n str += '; Secure';\n }\n if (this.options.sameSite) {\n str += `; SameSite=${this.options.sameSite}`;\n }\n const globalScope = getGlobalScope();\n if (globalScope) {\n globalScope.document.cookie = str;\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n console.error(`Amplitude Logger [Error]: Failed to set cookie for key: ${key}. Error: ${errorMessage}`);\n }\n }\n\n async remove(key: string): Promise<void> {\n await this.set(key, null);\n }\n\n async reset(): Promise<void> {\n return;\n }\n}\n\nconst decodeCookiesAsDefault = (value: string): string | undefined => {\n try {\n return decodeURIComponent(atob(value));\n } catch {\n return undefined;\n }\n};\n\nconst decodeCookiesWithDoubleUrlEncoding = (value: string): string | undefined => {\n // Modern Ruby (v7+) automatically encodes cookies with URL encoding by\n // https://api.rubyonrails.org/classes/ActionDispatch/Cookies.html\n try {\n return decodeURIComponent(atob(decodeURIComponent(value)));\n } catch {\n return undefined;\n }\n};\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amplitude/analytics-core",
|
|
3
|
-
"version": "2.12.
|
|
3
|
+
"version": "2.12.3",
|
|
4
4
|
"description": "",
|
|
5
5
|
"author": "Amplitude Inc",
|
|
6
6
|
"homepage": "https://github.com/amplitude/Amplitude-TypeScript",
|
|
@@ -42,5 +42,5 @@
|
|
|
42
42
|
"files": [
|
|
43
43
|
"lib"
|
|
44
44
|
],
|
|
45
|
-
"gitHead": "
|
|
45
|
+
"gitHead": "16c45a70df22880b2568231e9ae1ddfc65ddfbf4"
|
|
46
46
|
}
|