@amplitude/analytics-core 2.21.2 → 2.22.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/network-observer.d.ts +11 -0
- package/lib/cjs/network-observer.d.ts.map +1 -1
- package/lib/cjs/network-observer.js +47 -5
- package/lib/cjs/network-observer.js.map +1 -1
- package/lib/cjs/network-request-event.d.ts +3 -8
- package/lib/cjs/network-request-event.d.ts.map +1 -1
- package/lib/cjs/network-request-event.js +18 -52
- package/lib/cjs/network-request-event.js.map +1 -1
- package/lib/cjs/types/element-interactions.d.ts +7 -0
- package/lib/cjs/types/element-interactions.d.ts.map +1 -1
- package/lib/cjs/types/element-interactions.js.map +1 -1
- package/lib/cjs/types/frustration-interactions.d.ts +7 -0
- package/lib/cjs/types/frustration-interactions.d.ts.map +1 -1
- package/lib/cjs/types/frustration-interactions.js.map +1 -1
- package/lib/esm/network-observer.d.ts +11 -0
- package/lib/esm/network-observer.d.ts.map +1 -1
- package/lib/esm/network-observer.js +47 -5
- package/lib/esm/network-observer.js.map +1 -1
- package/lib/esm/network-request-event.d.ts +3 -8
- package/lib/esm/network-request-event.d.ts.map +1 -1
- package/lib/esm/network-request-event.js +18 -52
- package/lib/esm/network-request-event.js.map +1 -1
- package/lib/esm/types/element-interactions.d.ts +7 -0
- package/lib/esm/types/element-interactions.d.ts.map +1 -1
- package/lib/esm/types/element-interactions.js.map +1 -1
- package/lib/esm/types/frustration-interactions.d.ts +7 -0
- package/lib/esm/types/frustration-interactions.d.ts.map +1 -1
- package/lib/esm/types/frustration-interactions.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"element-interactions.d.ts","sourceRoot":"","sources":["../../../src/types/element-interactions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,MAAM,MAAM,UAAU,GAAG,OAAO,GAAG,QAAQ,CAAC;AAE5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AAM,CAAC;IACX,UAAU,EAAE,uBAAuB,CAAC;IACpC,UAAU,EAAE,UAAU,CAAC;IACvB,cAAc,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG;IACvB,UAAU,EAAE,aAAa,GAAG,cAAc,CAAC;CAC5C,GAAG,CACA;IACE,UAAU,EAAE,aAAa,CAAC;IAC1B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,kBAAkB,EAAE,MAAM,GAAG,WAAW,CAAC;IACzC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,GACD;IACE,UAAU,EAAE,cAAc,CAAC;IAC3B,YAAY,EAAE,MAAM,CAAC;CACtB,CACJ,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG,0BAA0B,GAAG,+BAA+B,CAAC;AAE3F,MAAM,MAAM,MAAM,GAAG;IACnB,WAAW,EAAE,eAAe,CAAC;IAC7B,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,EAAE,CAAC;CACzB,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG;IACzB,EAAE,EAAE,MAAM,CAAC;IACX,UAAU,EAAE;QACV,UAAU,EAAE,6BAA6B,GAAG,6BAA6B,CAAC;QAC1E,OAAO,EAAE,MAAM,EAAE,CAAC;KACnB,EAAE,CAAC;CACL,CAAC;AAEF,MAAM,WAAW,SAAS;IACxB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB;AAKD,KAAK,UAAU,GAAG,OAAO,UAAU,SAAS;IAC1C,OAAO,EAAE,KAAK,GAAG,IAAI,EAAE,GAAG,KAAK,MAAM,CAAC,CAAC;CACxC,GACG,CAAC,GACD,KAAK,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"element-interactions.js","sourceRoot":"","sources":["../../../src/types/element-interactions.ts"],"names":[],"mappings":";;;AAIA;;;;;;;;GAQG;AACU,QAAA,8BAA8B,GAAG;IAC5C,GAAG;IACH,QAAQ;IACR,OAAO;IACP,QAAQ;IACR,UAAU;IACV,OAAO;IACP,OAAO;IACP,OAAO;IACP,4BAA4B;IAC5B,0BAA0B;IAC1B,oBAAoB;CACrB,CAAC;AAEF;;GAEG;AACU,QAAA,6BAA6B,GAAG,iBAAiB,CAAC;AAE/D;;GAEG;AACU,QAAA,8BAA8B,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC","sourcesContent":["import { ILogger } from '../logger';\n\nexport type ActionType = 'click' | 'change';\n\n/**\n * Default CSS selectors to define which elements on the page to track.\n * Extend this list to include additional elements to track. For example:\n * ```\n * autocapturePlugin({\n * cssSelectorAllowlist: [...DEFAULT_CSS_SELECTOR_ALLOWLIST, \".my-class\"],\n * })\n * ```\n */\nexport const DEFAULT_CSS_SELECTOR_ALLOWLIST = [\n 'a',\n 'button',\n 'input',\n 'select',\n 'textarea',\n 'label',\n 'video',\n 'audio',\n '[contenteditable=\"true\" i]',\n '[data-amp-default-track]',\n '.amp-default-track',\n];\n\n/**\n * Default prefix to allow the plugin to capture data attributes as an event property.\n */\nexport const DEFAULT_DATA_ATTRIBUTE_PREFIX = 'data-amp-track-';\n\n/**\n * Default list of elements on the page should be tracked when the page changes.\n */\nexport const DEFAULT_ACTION_CLICK_ALLOWLIST = ['div', 'span', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];\n\nexport interface ElementInteractionsOptions {\n /**\n * List of CSS selectors to allow auto tracking on.\n * When provided, allow elements matching any selector to be tracked.\n * Default is ['a', 'button', 'input', 'select', 'textarea', 'label', '[data-amp-default-track]', '.amp-default-track'].\n */\n cssSelectorAllowlist?: string[];\n\n /**\n * List of page URLs to allow auto tracking on.\n * When provided, only allow tracking on these URLs.\n * Both full URLs and regex are supported.\n */\n pageUrlAllowlist?: (string | RegExp)[];\n\n /**\n * Function to determine whether an event should be tracked.\n * When provided, this function overwrites all other allowlists and configurations.\n * If the function returns true, the event will be tracked.\n * If the function returns false, the event will not be tracked.\n * @param actionType - The type of action that triggered the event.\n * @param element - The [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) that triggered the event.\n */\n shouldTrackEventResolver?: (actionType: ActionType, element: DomElement) => boolean;\n\n /**\n * Prefix for data attributes to allow auto collecting.\n * Default is 'data-amp-track-'.\n */\n dataAttributePrefix?: string;\n\n /**\n * Options for integrating visual tagging selector.\n */\n visualTaggingOptions?: {\n enabled?: boolean;\n messenger?: Messenger;\n };\n\n /**\n * Debounce time in milliseconds for tracking events.\n * This is used to detect rage clicks.\n */\n debounceTime?: number;\n\n /**\n * CSS selector allowlist for tracking clicks that result in a DOM change/navigation on elements not already allowed by the cssSelectorAllowlist\n */\n actionClickAllowlist?: string[];\n\n /**\n * Remote config for page actions\n */\n pageActions?: {\n triggers: Trigger[];\n labeledEvents: Record<string, LabeledEvent>;\n };\n}\n\ntype MatchingCondition = {\n type: 'LABELED_EVENT';\n match: {\n eventId: string;\n };\n};\n\nexport type Trigger = {\n id: string;\n name: string; // Human friendly name for the trigger\n conditions: MatchingCondition[]; // Configures when the actions should be executed; AND\n actions: Array<PageAction | string>; // Actions to execute if conditions are met\n};\n\nexport type PageAction = {\n id: string;\n actionType: 'ATTACH_EVENT_PROPERTY';\n dataSource: DataSource; // Defines where and how to get the data\n destinationKey: string; // Property key name for the data (e.g. event property name, data layer key, user property name)\n};\n\nexport type DataSource = {\n sourceType: 'DOM_ELEMENT' | 'PAGE_CONTEXT'; // | 'URL' ;\n} & (\n | {\n sourceType: 'DOM_ELEMENT';\n selector?: string; // For DOM_ELEMENT: CSS selector for the target element\n elementExtractType: 'TEXT' | 'ATTRIBUTE';\n attribute?: string; // For DOM_ELEMENT: Attribute name to extract (null/empty for text content)\n scope?: string; // CSS selector for the scope of the element, document by default\n }\n | {\n sourceType: 'PAGE_CONTEXT';\n propertyPath: string; // For PAGE_CONTEXT: e.g., 'document.title'\n }\n);\n\nexport type EventSubpropKey = '[Amplitude] Element Text' | '[Amplitude] Element Hierarchy';\n\nexport type Filter = {\n subprop_key: EventSubpropKey;\n subprop_op: string; // exact, autotrack css match\n subprop_value: string[];\n};\n\nexport type LabeledEvent = {\n id: string;\n definition: {\n event_type: '[Amplitude] Element Clicked' | '[Amplitude] Element Changed';\n filters: Filter[];\n }[];\n};\n\nexport interface Messenger {\n logger?: ILogger;\n setup: () => void;\n}\n\n// DomElement is [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) if the dom library is included in tsconfig.json\n// and never if it is not included\n// eslint-disable-next-line no-restricted-globals\ntype DomElement = typeof globalThis extends {\n Element: new (...args: any) => infer T;\n}\n ? T\n : never;\n"]}
|
|
1
|
+
{"version":3,"file":"element-interactions.js","sourceRoot":"","sources":["../../../src/types/element-interactions.ts"],"names":[],"mappings":";;;AAIA;;;;;;;;GAQG;AACU,QAAA,8BAA8B,GAAG;IAC5C,GAAG;IACH,QAAQ;IACR,OAAO;IACP,QAAQ;IACR,UAAU;IACV,OAAO;IACP,OAAO;IACP,OAAO;IACP,4BAA4B;IAC5B,0BAA0B;IAC1B,oBAAoB;CACrB,CAAC;AAEF;;GAEG;AACU,QAAA,6BAA6B,GAAG,iBAAiB,CAAC;AAE/D;;GAEG;AACU,QAAA,8BAA8B,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC","sourcesContent":["import { ILogger } from '../logger';\n\nexport type ActionType = 'click' | 'change';\n\n/**\n * Default CSS selectors to define which elements on the page to track.\n * Extend this list to include additional elements to track. For example:\n * ```\n * autocapturePlugin({\n * cssSelectorAllowlist: [...DEFAULT_CSS_SELECTOR_ALLOWLIST, \".my-class\"],\n * })\n * ```\n */\nexport const DEFAULT_CSS_SELECTOR_ALLOWLIST = [\n 'a',\n 'button',\n 'input',\n 'select',\n 'textarea',\n 'label',\n 'video',\n 'audio',\n '[contenteditable=\"true\" i]',\n '[data-amp-default-track]',\n '.amp-default-track',\n];\n\n/**\n * Default prefix to allow the plugin to capture data attributes as an event property.\n */\nexport const DEFAULT_DATA_ATTRIBUTE_PREFIX = 'data-amp-track-';\n\n/**\n * Default list of elements on the page should be tracked when the page changes.\n */\nexport const DEFAULT_ACTION_CLICK_ALLOWLIST = ['div', 'span', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];\n\nexport interface ElementInteractionsOptions {\n /**\n * List of CSS selectors to allow auto tracking on.\n * When provided, allow elements matching any selector to be tracked.\n * Default is ['a', 'button', 'input', 'select', 'textarea', 'label', '[data-amp-default-track]', '.amp-default-track'].\n */\n cssSelectorAllowlist?: string[];\n\n /**\n * List of page URLs to allow auto tracking on.\n * When provided, only allow tracking on these URLs.\n * Both full URLs and regex are supported.\n */\n pageUrlAllowlist?: (string | RegExp)[];\n\n /**\n * Function to determine whether an event should be tracked.\n * When provided, this function overwrites all other allowlists and configurations.\n * If the function returns true, the event will be tracked.\n * If the function returns false, the event will not be tracked.\n * @param actionType - The type of action that triggered the event.\n * @param element - The [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) that triggered the event.\n */\n shouldTrackEventResolver?: (actionType: ActionType, element: DomElement) => boolean;\n\n /**\n * Prefix for data attributes to allow auto collecting.\n * Default is 'data-amp-track-'.\n */\n dataAttributePrefix?: string;\n\n /**\n * Options for integrating visual tagging selector.\n */\n visualTaggingOptions?: {\n enabled?: boolean;\n messenger?: Messenger;\n };\n\n /**\n * Debounce time in milliseconds for tracking events.\n * This is used to detect rage clicks.\n */\n debounceTime?: number;\n\n /**\n * CSS selector allowlist for tracking clicks that result in a DOM change/navigation on elements not already allowed by the cssSelectorAllowlist\n */\n actionClickAllowlist?: string[];\n\n /**\n * Remote config for page actions\n */\n pageActions?: {\n triggers: Trigger[];\n labeledEvents: Record<string, LabeledEvent>;\n };\n\n /**\n * RegExp pattern list to allow custom patterns for text masking\n */\n maskTextRegex?: (RegExp | { pattern: string; description: string })[];\n}\n\ntype MatchingCondition = {\n type: 'LABELED_EVENT';\n match: {\n eventId: string;\n };\n};\n\nexport type Trigger = {\n id: string;\n name: string; // Human friendly name for the trigger\n conditions: MatchingCondition[]; // Configures when the actions should be executed; AND\n actions: Array<PageAction | string>; // Actions to execute if conditions are met\n};\n\nexport type PageAction = {\n id: string;\n actionType: 'ATTACH_EVENT_PROPERTY';\n dataSource: DataSource; // Defines where and how to get the data\n destinationKey: string; // Property key name for the data (e.g. event property name, data layer key, user property name)\n};\n\nexport type DataSource = {\n sourceType: 'DOM_ELEMENT' | 'PAGE_CONTEXT'; // | 'URL' ;\n} & (\n | {\n sourceType: 'DOM_ELEMENT';\n selector?: string; // For DOM_ELEMENT: CSS selector for the target element\n elementExtractType: 'TEXT' | 'ATTRIBUTE';\n attribute?: string; // For DOM_ELEMENT: Attribute name to extract (null/empty for text content)\n scope?: string; // CSS selector for the scope of the element, document by default\n }\n | {\n sourceType: 'PAGE_CONTEXT';\n propertyPath: string; // For PAGE_CONTEXT: e.g., 'document.title'\n }\n);\n\nexport type EventSubpropKey = '[Amplitude] Element Text' | '[Amplitude] Element Hierarchy';\n\nexport type Filter = {\n subprop_key: EventSubpropKey;\n subprop_op: string; // exact, autotrack css match\n subprop_value: string[];\n};\n\nexport type LabeledEvent = {\n id: string;\n definition: {\n event_type: '[Amplitude] Element Clicked' | '[Amplitude] Element Changed';\n filters: Filter[];\n }[];\n};\n\nexport interface Messenger {\n logger?: ILogger;\n setup: () => void;\n}\n\n// DomElement is [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) if the dom library is included in tsconfig.json\n// and never if it is not included\n// eslint-disable-next-line no-restricted-globals\ntype DomElement = typeof globalThis extends {\n Element: new (...args: any) => infer T;\n}\n ? T\n : never;\n"]}
|
|
@@ -52,6 +52,13 @@ export interface FrustrationInteractionsOptions {
|
|
|
52
52
|
* Configuration for rage clicks tracking
|
|
53
53
|
*/
|
|
54
54
|
rageClicks?: RageClickOptions;
|
|
55
|
+
/**
|
|
56
|
+
* RegExp pattern list to allow custom patterns for text masking
|
|
57
|
+
*/
|
|
58
|
+
maskTextRegex?: (RegExp | {
|
|
59
|
+
pattern: string;
|
|
60
|
+
description: string;
|
|
61
|
+
})[];
|
|
55
62
|
}
|
|
56
63
|
/**
|
|
57
64
|
* Default CSS selectors for dead clicks tracking
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"frustration-interactions.d.ts","sourceRoot":"","sources":["../../../src/types/frustration-interactions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAEpD;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;CACjC;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;CACjC;AAED;;;GAGG;AACH,MAAM,WAAW,8BAA8B;IAC7C;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC;IAEvC;;;;;;;OAOG;IACH,wBAAwB,CAAC,EAAE,CAAC,UAAU,EAAE,UAAU,EAAE,OAAO,EAAE,UAAU,KAAK,OAAO,CAAC;IAEpF;;;OAGG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAE7B;;OAEG;IACH,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAE9B;;OAEG;IACH,UAAU,CAAC,EAAE,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"frustration-interactions.d.ts","sourceRoot":"","sources":["../../../src/types/frustration-interactions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAEpD;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;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/frustration-interactions.ts"],"names":[],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"frustration-interactions.js","sourceRoot":"","sources":["../../../src/types/frustration-interactions.ts"],"names":[],"mappings":";;;;AAoEA,IAAM,2BAA2B,GAAG;IAClC,GAAG;IACH,QAAQ;IACR,iBAAiB;IACjB,eAAe;IACf,mBAAmB;IACnB,2BAA2B;IAC3B,wBAAwB;IACxB,iBAAiB;IACjB,cAAc;IACd,mBAAmB;IACnB,4BAA4B;CAC7B,CAAC;AAEF;;GAEG;AACU,QAAA,4BAA4B;IACvC,sBAAsB;IACtB,sBAAsB;IACtB,qBAAqB;IACrB,qBAAqB;IACrB,oBAAoB;kBACjB,2BAA2B,UAC9B;AAEF;;GAEG;AACU,QAAA,4BAA4B,GAAG,CAAC,GAAG,CAAC,CAAC;AAElD;;GAEG;AACU,QAAA,4BAA4B,GAAG,IAAK,CAAC;AAElD;;GAEG;AACU,QAAA,4BAA4B,GAAG,IAAK,CAAC;AAElD;;GAEG;AACU,QAAA,4BAA4B,GAAG,CAAC,CAAC;AAE9C;;GAEG;AACU,QAAA,0CAA0C,GAAG,EAAE,CAAC,CAAC,SAAS","sourcesContent":["import { ActionType } from './element-interactions';\n\n/**\n * Configuration options for dead clicks tracking\n */\nexport interface DeadClickOptions {\n /**\n * CSS selectors to define which elements on the page to track for dead clicks.\n * A dead click is a click that doesn't result in any visible change or navigation.\n */\n cssSelectorAllowlist?: string[];\n}\n\n/**\n * Configuration options for rage clicks tracking\n */\nexport interface RageClickOptions {\n /**\n * CSS selectors to define which elements on the page to track for rage clicks.\n * A rage click is multiple rapid clicks on the same element within a 3s time window.\n */\n cssSelectorAllowlist?: string[];\n}\n\n/**\n * Configuration options for frustration interactions tracking.\n * This includes dead clicks and rage clicks tracking.\n */\nexport interface FrustrationInteractionsOptions {\n /**\n * List of page URLs to allow auto tracking on.\n * When provided, only allow tracking on these URLs.\n * Both full URLs and regex are supported.\n */\n pageUrlAllowlist?: (string | RegExp)[];\n\n /**\n * Function to determine whether an event should be tracked.\n * When provided, this function overwrites all other allowlists and configurations.\n * If the function returns true, the event will be tracked.\n * If the function returns false, the event will not be tracked.\n * @param actionType - The type of action that triggered the event.\n * @param element - The [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) that triggered the event.\n */\n shouldTrackEventResolver?: (actionType: ActionType, element: DomElement) => boolean;\n\n /**\n * Prefix for data attributes to allow auto collecting.\n * Default is 'data-amp-track-'.\n */\n dataAttributePrefix?: string;\n\n /**\n * Configuration for dead clicks tracking\n */\n deadClicks?: DeadClickOptions;\n\n /**\n * Configuration for rage clicks tracking\n */\n rageClicks?: RageClickOptions;\n\n /**\n * RegExp pattern list to allow custom patterns for text masking\n */\n maskTextRegex?: (RegExp | { pattern: string; description: string })[];\n}\n\nconst CLICKABLE_ELEMENT_SELECTORS = [\n 'a',\n 'button',\n '[role=\"button\"]',\n '[role=\"link\"]',\n '[role=\"menuitem\"]',\n '[role=\"menuitemcheckbox\"]',\n '[role=\"menuitemradio\"]',\n '[role=\"option\"]',\n '[role=\"tab\"]',\n '[role=\"treeitem\"]',\n '[contenteditable=\"true\" i]',\n];\n\n/**\n * Default CSS selectors for dead clicks tracking\n */\nexport const DEFAULT_DEAD_CLICK_ALLOWLIST = [\n 'input[type=\"button\"]',\n 'input[type=\"submit\"]',\n 'input[type=\"reset\"]',\n 'input[type=\"image\"]',\n 'input[type=\"file\"]',\n ...CLICKABLE_ELEMENT_SELECTORS,\n];\n\n/**\n * Default CSS selectors for rage clicks tracking\n */\nexport const DEFAULT_RAGE_CLICK_ALLOWLIST = ['*'];\n\n/**\n * Default time window for dead clicks (3 seconds)\n */\nexport const DEFAULT_DEAD_CLICK_WINDOW_MS = 3_000;\n\n/**\n * Default time window for rage clicks (1 second)\n */\nexport const DEFAULT_RAGE_CLICK_WINDOW_MS = 1_000;\n\n/**\n * Default threshold for rage clicks (4 clicks)\n */\nexport const DEFAULT_RAGE_CLICK_THRESHOLD = 4;\n\n/**\n * Default threshold for rage clicks to be considered out of bounds (50 pixels)\n */\nexport const DEFAULT_RAGE_CLICK_OUT_OF_BOUNDS_THRESHOLD = 50; // pixels\n\n// DomElement is [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) if the dom library is included in tsconfig.json\n// and never if it is not included\n// eslint-disable-next-line no-restricted-globals\ntype DomElement = typeof globalThis extends {\n Element: new (...args: any) => infer T;\n}\n ? T\n : never;\n"]}
|
|
@@ -19,6 +19,17 @@ export declare class NetworkObserver {
|
|
|
19
19
|
private handleNetworkRequestEvent;
|
|
20
20
|
private getTimestamps;
|
|
21
21
|
private observeFetch;
|
|
22
|
+
/**
|
|
23
|
+
* Creates a function that parses the response of an XMLHttpRequest as JSON.
|
|
24
|
+
*
|
|
25
|
+
* Returns function instead of JSON object to avoid unnecessary parsing if the
|
|
26
|
+
* body is not being captured.
|
|
27
|
+
*
|
|
28
|
+
* @param xhrSafe - The XMLHttpRequest object.
|
|
29
|
+
* @param context - The NetworkObserver instance.
|
|
30
|
+
* @returns A function that parses the response of an XMLHttpRequest as JSON.
|
|
31
|
+
*/
|
|
32
|
+
static createXhrJsonParser(xhrUnsafe: XMLHttpRequest, context: NetworkObserver): () => any;
|
|
22
33
|
private observeXhr;
|
|
23
34
|
}
|
|
24
35
|
export declare const networkObserver: NetworkObserver;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-observer.d.ts","sourceRoot":"","sources":["../../src/network-observer.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AACnC,OAAO,EAEL,mBAAmB,EAQpB,MAAM,yBAAyB,CAAC;AAoBjC,MAAM,MAAM,sBAAsB,GAAG,CAAC,KAAK,EAAE,mBAAmB,KAAK,IAAI,CAAC;AAE1E,qBAAa,oBAAoB;aACH,QAAQ,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,IAAI;aAAkB,EAAE,EAAE,MAAM;gBAA1E,QAAQ,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,IAAI,EAAkB,EAAE,GAAE,MAAe;CAChH;
|
|
1
|
+
{"version":3,"file":"network-observer.d.ts","sourceRoot":"","sources":["../../src/network-observer.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AACnC,OAAO,EAEL,mBAAmB,EAQpB,MAAM,yBAAyB,CAAC;AAoBjC,MAAM,MAAM,sBAAsB,GAAG,CAAC,KAAK,EAAE,mBAAmB,KAAK,IAAI,CAAC;AAE1E,qBAAa,oBAAoB;aACH,QAAQ,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,IAAI;aAAkB,EAAE,EAAE,MAAM;gBAA1E,QAAQ,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,IAAI,EAAkB,EAAE,GAAE,MAAe;CAChH;AAqBD,qBAAa,eAAe;IAC1B,OAAO,CAAC,cAAc,CAAgD;IAEtE,OAAO,CAAC,WAAW,CAAC,CAAoB;IACxC,OAAO,CAAC,MAAM,CAAC,CAAU;IACzB,OAAO,CAAC,WAAW,CAAS;gBAChB,MAAM,CAAC,EAAE,OAAO;IAU5B,MAAM,CAAC,WAAW,IAAI,OAAO;IAK7B,SAAS,CAAC,aAAa,EAAE,oBAAoB,EAAE,MAAM,CAAC,EAAE,OAAO;IA+B/D,WAAW,CAAC,aAAa,EAAE,oBAAoB;IAI/C,SAAS,CAAC,qBAAqB,CAAC,KAAK,EAAE,mBAAmB;IAa1D,OAAO,CAAC,yBAAyB;IA4DjC,OAAO,CAAC,aAAa;IAQrB,OAAO,CAAC,YAAY;IA8DpB;;;;;;;;;OASG;IACH,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,cAAc,EAAE,OAAO,EAAE,eAAe;IA8B9E,OAAO,CAAC,UAAU;CAqHnB;AAGD,eAAO,MAAM,eAAe,iBAAwB,CAAC"}
|
|
@@ -189,6 +189,46 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
189
189
|
});
|
|
190
190
|
}); };
|
|
191
191
|
};
|
|
192
|
+
/**
|
|
193
|
+
* Creates a function that parses the response of an XMLHttpRequest as JSON.
|
|
194
|
+
*
|
|
195
|
+
* Returns function instead of JSON object to avoid unnecessary parsing if the
|
|
196
|
+
* body is not being captured.
|
|
197
|
+
*
|
|
198
|
+
* @param xhrSafe - The XMLHttpRequest object.
|
|
199
|
+
* @param context - The NetworkObserver instance.
|
|
200
|
+
* @returns A function that parses the response of an XMLHttpRequest as JSON.
|
|
201
|
+
*/
|
|
202
|
+
NetworkObserver.createXhrJsonParser = function (xhrUnsafe, context) {
|
|
203
|
+
return function () {
|
|
204
|
+
var _a, _b;
|
|
205
|
+
try {
|
|
206
|
+
if (xhrUnsafe.responseType === 'json') {
|
|
207
|
+
// if response is a JS object, clone it so that subscribers can't mutate it
|
|
208
|
+
if ((_a = context.globalScope) === null || _a === void 0 ? void 0 : _a.structuredClone) {
|
|
209
|
+
/* eslint-disable-next-line @typescript-eslint/no-unsafe-return */
|
|
210
|
+
return context.globalScope.structuredClone(xhrUnsafe.response);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
else if (['text', ''].includes(xhrUnsafe.responseType)) {
|
|
214
|
+
// if response is a string, parse it as JSON
|
|
215
|
+
/* eslint-disable-next-line @typescript-eslint/no-unsafe-return */
|
|
216
|
+
return JSON.parse(xhrUnsafe.responseText);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
catch (err) {
|
|
220
|
+
/* istanbul ignore if */
|
|
221
|
+
if (err instanceof Error && err.name === 'InvalidStateError') {
|
|
222
|
+
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText#exceptions
|
|
223
|
+
// if we reach here, it means we don't handle responseType correctly
|
|
224
|
+
(_b = context.logger) === null || _b === void 0 ? void 0 : _b.error("unexpected error when retrieving responseText. responseType='".concat(xhrUnsafe.responseType, "'"));
|
|
225
|
+
}
|
|
226
|
+
// the other possible error is Json Parse error which we fail silently
|
|
227
|
+
return null;
|
|
228
|
+
}
|
|
229
|
+
return null;
|
|
230
|
+
};
|
|
231
|
+
};
|
|
192
232
|
NetworkObserver.prototype.observeXhr = function (originalXhrOpen, originalXhrSend, originalXhrSetRequestHeader) {
|
|
193
233
|
/* istanbul ignore next */
|
|
194
234
|
if (!this.globalScope || !originalXhrOpen || !originalXhrSend) {
|
|
@@ -216,7 +256,7 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
216
256
|
}
|
|
217
257
|
catch (err) {
|
|
218
258
|
/* istanbul ignore next */
|
|
219
|
-
(_b = networkObserverContext.logger) === null || _b === void 0 ? void 0 : _b.
|
|
259
|
+
(_b = networkObserverContext.logger) === null || _b === void 0 ? void 0 : _b.error('an unexpected error occurred while calling xhr open', err);
|
|
220
260
|
}
|
|
221
261
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
|
222
262
|
return originalXhrOpen.apply(xhrSafe, args);
|
|
@@ -235,7 +275,9 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
235
275
|
args[_i] = arguments[_i];
|
|
236
276
|
}
|
|
237
277
|
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
238
|
-
var
|
|
278
|
+
var xhrUnsafe = this;
|
|
279
|
+
var xhrSafe = xhrUnsafe;
|
|
280
|
+
var getJson = NetworkObserver.createXhrJsonParser(xhrUnsafe, networkObserverContext);
|
|
239
281
|
var body = args[0];
|
|
240
282
|
var requestEvent = xhrSafe.$$AmplitudeAnalyticsEvent;
|
|
241
283
|
xhrSafe.addEventListener('loadend', function () {
|
|
@@ -245,7 +287,7 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
245
287
|
var responseBodySize = xhrSafe.getResponseHeader('content-length');
|
|
246
288
|
var responseWrapper = new ResponseWrapperXhr(xhrSafe.status, responseHeaders,
|
|
247
289
|
/* istanbul ignore next */
|
|
248
|
-
responseBodySize ? parseInt(responseBodySize, 10) : undefined,
|
|
290
|
+
responseBodySize ? parseInt(responseBodySize, 10) : undefined, getJson);
|
|
249
291
|
var requestHeaders = xhrSafe.$$AmplitudeAnalyticsEvent.headers;
|
|
250
292
|
var requestWrapper = new RequestWrapperXhr(body, requestHeaders);
|
|
251
293
|
requestEvent.status = xhrSafe.status;
|
|
@@ -253,7 +295,7 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
253
295
|
}
|
|
254
296
|
catch (err) {
|
|
255
297
|
/* istanbul ignore next */
|
|
256
|
-
(_a = networkObserverContext.logger) === null || _a === void 0 ? void 0 : _a.
|
|
298
|
+
(_a = networkObserverContext.logger) === null || _a === void 0 ? void 0 : _a.error('an unexpected error occurred while handling xhr send', err);
|
|
257
299
|
}
|
|
258
300
|
});
|
|
259
301
|
/* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */
|
|
@@ -276,7 +318,7 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
276
318
|
}
|
|
277
319
|
catch (err) {
|
|
278
320
|
/* istanbul ignore next */
|
|
279
|
-
(_a = networkObserverContext.logger) === null || _a === void 0 ? void 0 : _a.
|
|
321
|
+
(_a = networkObserverContext.logger) === null || _a === void 0 ? void 0 : _a.error('an unexpected error occurred while calling xhr setRequestHeader', err);
|
|
280
322
|
}
|
|
281
323
|
/* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */
|
|
282
324
|
originalXhrSetRequestHeader.apply(xhrSafe, [headerName, headerValue]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-observer.js","sourceRoot":"","sources":["../../src/network-observer.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,IAAI,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAEpC,OAAO,EAEL,mBAAmB,EACnB,mBAAmB,EACnB,oBAAoB,EACpB,iBAAiB,EACjB,kBAAkB,GAInB,MAAM,yBAAyB,CAAC;AAajC;;GAEG;AACH,SAAS,SAAS,CAAC,WAAgB;IACjC,OAAO,OAAO,WAAW,KAAK,QAAQ,IAAI,WAAW,K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M,0CAAE,KAAK,CAAC,sDAAsD,EAAE,GAAG,CAAC,CAAC;iBACnG;YACH,CAAC,CAAC,CAAC;YACH,oEAAoE;YACpE,OAAO,eAAe,CAAC,KAAK,CAAC,OAAO,EAAE,IAAW,CAAC,CAAC;QACrD,CAAC,CAAC;QAEF;;;;;WAKG;QACH,oEAAoE;QACpE,oEAAoE;QACpE,QAAQ,CAAC,gBAAgB,GAAG,UAAU,UAAe,EAAE,WAAgB;;YACrE,IAAM,OAAO,GAAG,IAA8C,CAAC;YAC/D,IAAI;gBACF,sEAAsE;gBACtE,OAAO,CAAC,yBAAyB,CAAC,OAAO,CAAC,UAAoB,CAAC,GAAG,WAAqB,CAAC;aACzF;YAAC,OAAO,GAAG,EAAE;gBACZ,0BAA0B;gBAC1B,MAAA,sBAAsB,CAAC,MAAM,0CAAE,KAAK,CAAC,iEAAiE,EAAE,GAAG,CAAC,CAAC;aAC9G;YACD,oEAAoE;YACpE,2BAA2B,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC,CAAC;QACxE,CAAC,CAAC;IACJ,CAAC;IACH,sBAAC;AAAD,CAAC,AAzTD,IAyTC;;AAED,wCAAwC;AACxC,MAAM,CAAC,IAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC","sourcesContent":["import { getGlobalScope } from './';\nimport { UUID } from './utils/uuid';\nimport { ILogger } from './logger';\nimport {\n IRequestWrapper,\n NetworkRequestEvent,\n RequestWrapperFetch,\n ResponseWrapperFetch,\n RequestWrapperXhr,\n ResponseWrapperXhr,\n IResponseWrapper,\n RequestInitSafe,\n XMLHttpRequestBodyInitSafe,\n} from './network-request-event';\n\n// object that is added to each XHR instance so\n// that info can be set in xhr.open and retrieved in xhr.send\ntype AmplitudeAnalyticsEvent = {\n method: string;\n url: string | URL;\n startTime: number;\n durationStart: number;\n status?: number;\n headers: Record<string, string>;\n};\n\n/**\n * Typeguard function checks if an input is a Request object.\n */\nfunction isRequest(requestInfo: any): requestInfo is Request {\n return typeof requestInfo === 'object' && requestInfo !== null && 'url' in requestInfo && 'method' in requestInfo;\n}\n\nexport type NetworkEventCallbackFn = (event: NetworkRequestEvent) => void;\n\nexport class NetworkEventCallback {\n constructor(public readonly callback: (event: NetworkRequestEvent) => void, public readonly id: string = UUID()) {}\n}\n\ntype RequestUrlAndMethod = {\n url: string | URL | undefined;\n method: string | undefined;\n};\n\n// A narrowed down [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) type\n// that only includes the properties we need to access and adds the $$AmplitudeAnalyticsEvent property\n// Use great care when modifying this type, make sure you only use read-only properties and only add\n// what you need to access, nothing more.\ntype AmplitudeXMLHttpRequestSafe = {\n $$AmplitudeAnalyticsEvent: AmplitudeAnalyticsEvent;\n status: number;\n responseText: string;\n getAllResponseHeaders: typeof XMLHttpRequest.prototype.getAllResponseHeaders;\n getResponseHeader: typeof XMLHttpRequest.prototype.getResponseHeader;\n addEventListener: (type: 'loadend', listener: () => void) => void;\n};\n\nexport class NetworkObserver {\n private eventCallbacks: Map<string, NetworkEventCallback> = new Map();\n // eslint-disable-next-line no-restricted-globals\n private globalScope?: typeof globalThis;\n private logger?: ILogger;\n private isObserving = false;\n constructor(logger?: ILogger) {\n this.logger = logger;\n const globalScope = getGlobalScope();\n if (!NetworkObserver.isSupported()) {\n /* istanbul ignore next */\n return;\n }\n this.globalScope = globalScope;\n }\n\n static isSupported(): boolean {\n const globalScope = getGlobalScope();\n return !!globalScope && !!globalScope.fetch;\n }\n\n subscribe(eventCallback: NetworkEventCallback, logger?: ILogger) {\n if (!this.logger) {\n this.logger = logger;\n }\n this.eventCallbacks.set(eventCallback.id, eventCallback);\n if (!this.isObserving) {\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrOpen = this.globalScope?.XMLHttpRequest?.prototype?.open;\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrSend = this.globalScope?.XMLHttpRequest?.prototype?.send;\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrSetRequestHeader = this.globalScope?.XMLHttpRequest?.prototype?.setRequestHeader;\n if (originalXhrOpen && originalXhrSend && originalXhrSetRequestHeader) {\n this.observeXhr(originalXhrOpen, originalXhrSend, originalXhrSetRequestHeader);\n }\n\n /* istanbul ignore next */\n const originalFetch = this.globalScope?.fetch;\n /* istanbul ignore next */\n if (originalFetch) {\n this.observeFetch(originalFetch);\n }\n\n /* istanbul ignore next */\n this.isObserving = true;\n }\n }\n\n unsubscribe(eventCallback: NetworkEventCallback) {\n this.eventCallbacks.delete(eventCallback.id);\n }\n\n protected triggerEventCallbacks(event: NetworkRequestEvent) {\n this.eventCallbacks.forEach((callback) => {\n try {\n callback.callback(event);\n } catch (err) {\n // if the callback throws an error, we should catch it\n // to avoid breaking the fetch promise chain\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while triggering event callbacks', err);\n }\n });\n }\n\n private handleNetworkRequestEvent(\n requestType: 'fetch' | 'xhr',\n requestInfo: RequestInfo | URL | RequestUrlAndMethod | undefined,\n requestWrapper: IRequestWrapper | undefined,\n responseWrapper: IResponseWrapper | undefined,\n typedError: Error | undefined,\n startTime?: number,\n durationStart?: number,\n ) {\n /* istanbul ignore next */\n if (startTime === undefined || durationStart === undefined) {\n // if we reach this point, it means that the performance API is not supported\n // so we can't construct a NetworkRequestEvent\n return;\n }\n\n // parse the URL and Method\n let url: string | undefined;\n let method = 'GET';\n if (isRequest(requestInfo)) {\n url = requestInfo['url'];\n method = requestInfo['method'];\n } else {\n url = requestInfo?.toString?.();\n }\n method = requestWrapper?.method || method;\n\n let status, error;\n if (responseWrapper) {\n status = responseWrapper.status;\n }\n\n if (typedError) {\n error = {\n name: typedError.name || 'UnknownError',\n message: typedError.message || 'An unknown error occurred',\n };\n status = 0;\n }\n\n const duration = Math.floor(performance.now() - durationStart);\n const endTime = Math.floor(startTime + duration);\n\n const requestEvent = new NetworkRequestEvent(\n requestType,\n method,\n startTime, // timestamp and startTime are aliases\n startTime,\n url,\n requestWrapper,\n status,\n duration,\n responseWrapper,\n error,\n endTime,\n );\n\n this.triggerEventCallbacks(requestEvent);\n }\n\n private getTimestamps() {\n /* istanbul ignore next */\n return {\n startTime: Date.now?.(),\n durationStart: performance?.now?.(),\n };\n }\n\n private observeFetch(\n originalFetch: (requestInfo: RequestInfo | URL, requestInit?: RequestInit) => Promise<Response>,\n ) {\n /* istanbul ignore next */\n if (!this.globalScope || !originalFetch) {\n return;\n }\n /**\n * IMPORTANT: This overrides window.fetch in browsers.\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of fetch\n * and make sure another developer who is an expert reviews this change throughly\n */\n this.globalScope.fetch = async (requestInfo?: RequestInfo | URL, requestInit?: RequestInit) => {\n // 1: capture the start time and duration start time before the fetch call\n let timestamps;\n try {\n timestamps = this.getTimestamps();\n } catch (error) {\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while retrieving timestamps', error);\n }\n\n // 2. make the call to the original fetch and preserve the response or error\n let originalResponse, originalError;\n try {\n originalResponse = await originalFetch(requestInfo as RequestInfo | URL, requestInit);\n } catch (err) {\n // Capture error information\n originalError = err;\n }\n\n // 3. call the handler after the fetch call is done\n try {\n this.handleNetworkRequestEvent(\n 'fetch',\n requestInfo,\n requestInit ? new RequestWrapperFetch(requestInit as RequestInitSafe) : undefined,\n originalResponse ? new ResponseWrapperFetch(originalResponse) : undefined,\n originalError as Error,\n /* istanbul ignore next */\n timestamps?.startTime,\n /* istanbul ignore next */\n timestamps?.durationStart,\n );\n } catch (err) {\n // this catch shouldn't be reachable, but keep it here for safety\n // because we're overriding the fetch function and better to be safe than sorry\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while handling fetch', err);\n }\n\n // 4. return the original response or throw the original error\n if (originalResponse) {\n // if the response is not undefined, return it\n return originalResponse;\n } else {\n throw originalError;\n }\n };\n }\n\n private observeXhr(\n originalXhrOpen:\n | ((\n method: string,\n url: string | URL,\n async?: boolean,\n username?: string | null,\n password?: string | null,\n ) => void)\n | undefined,\n originalXhrSend: ((body?: Document | XMLHttpRequestBodyInit | null) => void) | undefined,\n originalXhrSetRequestHeader: (headerName: string, headerValue: string) => void,\n ) {\n /* istanbul ignore next */\n if (!this.globalScope || !originalXhrOpen || !originalXhrSend) {\n return;\n }\n\n const xhrProto = this.globalScope.XMLHttpRequest.prototype;\n\n const networkObserverContext = this as NetworkObserver;\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.open\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.open\n * and make sure another developer who is an expert reviews this change throughly\n */\n xhrProto.open = function (...args: any[]) {\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n const [method, url] = args as [string, string | URL];\n try {\n /* istanbul ignore next */\n xhrSafe.$$AmplitudeAnalyticsEvent = {\n method,\n url: url?.toString?.(),\n headers: {},\n ...networkObserverContext.getTimestamps(),\n } as AmplitudeAnalyticsEvent;\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.debug('an unexpected error occurred while calling xhr open', err);\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return originalXhrOpen.apply(xhrSafe, args as any);\n };\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.send\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.send\n * and make sure another developer who is an expert reviews this change throughly\n */\n // allow \"any\" type for args to reflect how it's used in the browser\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n xhrProto.send = function (...args: any[]) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n const body = args[0] as XMLHttpRequestBodyInitSafe;\n const requestEvent = xhrSafe.$$AmplitudeAnalyticsEvent;\n\n xhrSafe.addEventListener('loadend', function () {\n try {\n const responseHeaders = xhrSafe.getAllResponseHeaders();\n const responseBodySize = xhrSafe.getResponseHeader('content-length');\n const responseWrapper = new ResponseWrapperXhr(\n xhrSafe.status,\n responseHeaders,\n /* istanbul ignore next */\n responseBodySize ? parseInt(responseBodySize, 10) : undefined,\n xhrSafe.responseText,\n );\n const requestHeaders = xhrSafe.$$AmplitudeAnalyticsEvent.headers;\n const requestWrapper = new RequestWrapperXhr(body, requestHeaders);\n requestEvent.status = xhrSafe.status;\n networkObserverContext.handleNetworkRequestEvent(\n 'xhr',\n { url: requestEvent.url, method: requestEvent.method },\n requestWrapper,\n responseWrapper,\n undefined,\n requestEvent.startTime,\n requestEvent.durationStart,\n );\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.debug('an unexpected error occurred while handling xhr send', err);\n }\n });\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n return originalXhrSend.apply(xhrSafe, args as any);\n };\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.setRequestHeader\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.setRequestHeader\n * and make sure another developer who is an expert reviews this change throughly\n */\n // allow \"any\" type for args to reflect how it's used in the browser\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n xhrProto.setRequestHeader = function (headerName: any, headerValue: any) {\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n try {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-assignment */\n xhrSafe.$$AmplitudeAnalyticsEvent.headers[headerName as string] = headerValue as string;\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.debug('an unexpected error occurred while calling xhr setRequestHeader', err);\n }\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n originalXhrSetRequestHeader.apply(xhrSafe, [headerName, headerValue]);\n };\n }\n}\n\n// singleton instance of NetworkObserver\nexport const networkObserver = new NetworkObserver();\n"]}
|
|
1
|
+
{"version":3,"file":"network-observer.js","sourceRoot":"","sources":["../../src/network-observer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AAC,OAAO,GAAG,EAAE;oBACZ,0BAA0B;oBAC1B,MAAA,sBAAsB,CAAC,MAAM,0CAAE,KAAK,CAAC,sDAAsD,EAAE,GAAG,CAAC,CAAC;iBACnG;YACH,CAAC,CAAC,CAAC;YACH,oEAAoE;YACpE,OAAO,eAAe,CAAC,KAAK,CAAC,OAAO,EAAE,IAAW,CAAC,CAAC;QACrD,CAAC,CAAC;QAEF;;;;;WAKG;QACH,oEAAoE;QACpE,oEAAoE;QACpE,QAAQ,CAAC,gBAAgB,GAAG,UAAU,UAAe,EAAE,WAAgB;;YACrE,IAAM,OAAO,GAAG,IAA8C,CAAC;YAC/D,IAAI;gBACF,sEAAsE;gBACtE,OAAO,CAAC,yBAAyB,CAAC,OAAO,CAAC,UAAoB,CAAC,GAAG,WAAqB,CAAC;aACzF;YAAC,OAAO,GAAG,EAAE;gBACZ,0BAA0B;gBAC1B,MAAA,sBAAsB,CAAC,MAAM,0CAAE,KAAK,CAAC,iEAAiE,EAAE,GAAG,CAAC,CAAC;aAC9G;YACD,oEAAoE;YACpE,2BAA2B,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC,CAAC;QACxE,CAAC,CAAC;IACJ,CAAC;IACH,sBAAC;AAAD,CAAC,AApWD,IAoWC;;AAED,wCAAwC;AACxC,MAAM,CAAC,IAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC","sourcesContent":["import { getGlobalScope } from './';\nimport { UUID } from './utils/uuid';\nimport { ILogger } from './logger';\nimport {\n IRequestWrapper,\n NetworkRequestEvent,\n RequestWrapperFetch,\n ResponseWrapperFetch,\n RequestWrapperXhr,\n ResponseWrapperXhr,\n IResponseWrapper,\n RequestInitSafe,\n XMLHttpRequestBodyInitSafe,\n} from './network-request-event';\n\n// object that is added to each XHR instance so\n// that info can be set in xhr.open and retrieved in xhr.send\ntype AmplitudeAnalyticsEvent = {\n method: string;\n url: string | URL;\n startTime: number;\n durationStart: number;\n status?: number;\n headers: Record<string, string>;\n};\n\n/**\n * Typeguard function checks if an input is a Request object.\n */\nfunction isRequest(requestInfo: any): requestInfo is Request {\n return typeof requestInfo === 'object' && requestInfo !== null && 'url' in requestInfo && 'method' in requestInfo;\n}\n\nexport type NetworkEventCallbackFn = (event: NetworkRequestEvent) => void;\n\nexport class NetworkEventCallback {\n constructor(public readonly callback: (event: NetworkRequestEvent) => void, public readonly id: string = UUID()) {}\n}\n\ntype RequestUrlAndMethod = {\n url: string | URL | undefined;\n method: string | undefined;\n};\n\n// A narrowed down [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) type\n// that only includes the properties we need to access and adds the $$AmplitudeAnalyticsEvent property\n// Use great care when modifying this type, make sure you only use read-only properties and only add\n// what you need to access, nothing more.\ntype AmplitudeXMLHttpRequestSafe = {\n $$AmplitudeAnalyticsEvent: AmplitudeAnalyticsEvent;\n status: number;\n responseText: string;\n responseType: XMLHttpRequestResponseType;\n getAllResponseHeaders: typeof XMLHttpRequest.prototype.getAllResponseHeaders;\n getResponseHeader: typeof XMLHttpRequest.prototype.getResponseHeader;\n addEventListener: (type: 'loadend', listener: () => void) => void;\n};\n\nexport class NetworkObserver {\n private eventCallbacks: Map<string, NetworkEventCallback> = new Map();\n // eslint-disable-next-line no-restricted-globals\n private globalScope?: typeof globalThis;\n private logger?: ILogger;\n private isObserving = false;\n constructor(logger?: ILogger) {\n this.logger = logger;\n const globalScope = getGlobalScope();\n if (!NetworkObserver.isSupported()) {\n /* istanbul ignore next */\n return;\n }\n this.globalScope = globalScope;\n }\n\n static isSupported(): boolean {\n const globalScope = getGlobalScope();\n return !!globalScope && !!globalScope.fetch;\n }\n\n subscribe(eventCallback: NetworkEventCallback, logger?: ILogger) {\n if (!this.logger) {\n this.logger = logger;\n }\n this.eventCallbacks.set(eventCallback.id, eventCallback);\n if (!this.isObserving) {\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrOpen = this.globalScope?.XMLHttpRequest?.prototype?.open;\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrSend = this.globalScope?.XMLHttpRequest?.prototype?.send;\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrSetRequestHeader = this.globalScope?.XMLHttpRequest?.prototype?.setRequestHeader;\n if (originalXhrOpen && originalXhrSend && originalXhrSetRequestHeader) {\n this.observeXhr(originalXhrOpen, originalXhrSend, originalXhrSetRequestHeader);\n }\n\n /* istanbul ignore next */\n const originalFetch = this.globalScope?.fetch;\n /* istanbul ignore next */\n if (originalFetch) {\n this.observeFetch(originalFetch);\n }\n\n /* istanbul ignore next */\n this.isObserving = true;\n }\n }\n\n unsubscribe(eventCallback: NetworkEventCallback) {\n this.eventCallbacks.delete(eventCallback.id);\n }\n\n protected triggerEventCallbacks(event: NetworkRequestEvent) {\n this.eventCallbacks.forEach((callback) => {\n try {\n callback.callback(event);\n } catch (err) {\n // if the callback throws an error, we should catch it\n // to avoid breaking the fetch promise chain\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while triggering event callbacks', err);\n }\n });\n }\n\n private handleNetworkRequestEvent(\n requestType: 'fetch' | 'xhr',\n requestInfo: RequestInfo | URL | RequestUrlAndMethod | undefined,\n requestWrapper: IRequestWrapper | undefined,\n responseWrapper: IResponseWrapper | undefined,\n typedError: Error | undefined,\n startTime?: number,\n durationStart?: number,\n ) {\n /* istanbul ignore next */\n if (startTime === undefined || durationStart === undefined) {\n // if we reach this point, it means that the performance API is not supported\n // so we can't construct a NetworkRequestEvent\n return;\n }\n\n // parse the URL and Method\n let url: string | undefined;\n let method = 'GET';\n if (isRequest(requestInfo)) {\n url = requestInfo['url'];\n method = requestInfo['method'];\n } else {\n url = requestInfo?.toString?.();\n }\n method = requestWrapper?.method || method;\n\n let status, error;\n if (responseWrapper) {\n status = responseWrapper.status;\n }\n\n if (typedError) {\n error = {\n name: typedError.name || 'UnknownError',\n message: typedError.message || 'An unknown error occurred',\n };\n status = 0;\n }\n\n const duration = Math.floor(performance.now() - durationStart);\n const endTime = Math.floor(startTime + duration);\n\n const requestEvent = new NetworkRequestEvent(\n requestType,\n method,\n startTime, // timestamp and startTime are aliases\n startTime,\n url,\n requestWrapper,\n status,\n duration,\n responseWrapper,\n error,\n endTime,\n );\n\n this.triggerEventCallbacks(requestEvent);\n }\n\n private getTimestamps() {\n /* istanbul ignore next */\n return {\n startTime: Date.now?.(),\n durationStart: performance?.now?.(),\n };\n }\n\n private observeFetch(\n originalFetch: (requestInfo: RequestInfo | URL, requestInit?: RequestInit) => Promise<Response>,\n ) {\n /* istanbul ignore next */\n if (!this.globalScope || !originalFetch) {\n return;\n }\n /**\n * IMPORTANT: This overrides window.fetch in browsers.\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of fetch\n * and make sure another developer who is an expert reviews this change throughly\n */\n this.globalScope.fetch = async (requestInfo?: RequestInfo | URL, requestInit?: RequestInit) => {\n // 1: capture the start time and duration start time before the fetch call\n let timestamps;\n try {\n timestamps = this.getTimestamps();\n } catch (error) {\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while retrieving timestamps', error);\n }\n\n // 2. make the call to the original fetch and preserve the response or error\n let originalResponse, originalError;\n try {\n originalResponse = await originalFetch(requestInfo as RequestInfo | URL, requestInit);\n } catch (err) {\n // Capture error information\n originalError = err;\n }\n\n // 3. call the handler after the fetch call is done\n try {\n this.handleNetworkRequestEvent(\n 'fetch',\n requestInfo,\n requestInit ? new RequestWrapperFetch(requestInit as RequestInitSafe) : undefined,\n originalResponse ? new ResponseWrapperFetch(originalResponse) : undefined,\n originalError as Error,\n /* istanbul ignore next */\n timestamps?.startTime,\n /* istanbul ignore next */\n timestamps?.durationStart,\n );\n } catch (err) {\n // this catch shouldn't be reachable, but keep it here for safety\n // because we're overriding the fetch function and better to be safe than sorry\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while handling fetch', err);\n }\n\n // 4. return the original response or throw the original error\n if (originalResponse) {\n // if the response is not undefined, return it\n return originalResponse;\n } else {\n throw originalError;\n }\n };\n }\n\n /**\n * Creates a function that parses the response of an XMLHttpRequest as JSON.\n *\n * Returns function instead of JSON object to avoid unnecessary parsing if the\n * body is not being captured.\n *\n * @param xhrSafe - The XMLHttpRequest object.\n * @param context - The NetworkObserver instance.\n * @returns A function that parses the response of an XMLHttpRequest as JSON.\n */\n static createXhrJsonParser(xhrUnsafe: XMLHttpRequest, context: NetworkObserver) {\n return () => {\n try {\n if (xhrUnsafe.responseType === 'json') {\n // if response is a JS object, clone it so that subscribers can't mutate it\n if (context.globalScope?.structuredClone) {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */\n return context.globalScope.structuredClone(xhrUnsafe.response);\n }\n } else if (['text', ''].includes(xhrUnsafe.responseType)) {\n // if response is a string, parse it as JSON\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */\n return JSON.parse(xhrUnsafe.responseText);\n }\n } catch (err) {\n /* istanbul ignore if */\n if (err instanceof Error && err.name === 'InvalidStateError') {\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText#exceptions\n // if we reach here, it means we don't handle responseType correctly\n context.logger?.error(\n `unexpected error when retrieving responseText. responseType='${xhrUnsafe.responseType}'`,\n );\n }\n // the other possible error is Json Parse error which we fail silently\n return null;\n }\n return null;\n };\n }\n\n private observeXhr(\n originalXhrOpen:\n | ((\n method: string,\n url: string | URL,\n async?: boolean,\n username?: string | null,\n password?: string | null,\n ) => void)\n | undefined,\n originalXhrSend: ((body?: Document | XMLHttpRequestBodyInit | null) => void) | undefined,\n originalXhrSetRequestHeader: (headerName: string, headerValue: string) => void,\n ) {\n /* istanbul ignore next */\n if (!this.globalScope || !originalXhrOpen || !originalXhrSend) {\n return;\n }\n\n const xhrProto = this.globalScope.XMLHttpRequest.prototype;\n\n const networkObserverContext = this as NetworkObserver;\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.open\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.open\n * and make sure another developer who is an expert reviews this change throughly\n */\n xhrProto.open = function (...args: any[]) {\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n const [method, url] = args as [string, string | URL];\n try {\n /* istanbul ignore next */\n xhrSafe.$$AmplitudeAnalyticsEvent = {\n method,\n url: url?.toString?.(),\n headers: {},\n ...networkObserverContext.getTimestamps(),\n } as AmplitudeAnalyticsEvent;\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.error('an unexpected error occurred while calling xhr open', err);\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return originalXhrOpen.apply(xhrSafe, args as any);\n };\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.send\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.send\n * and make sure another developer who is an expert reviews this change throughly\n */\n // allow \"any\" type for args to reflect how it's used in the browser\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n xhrProto.send = function (...args: any[]) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhrUnsafe = this;\n const xhrSafe = xhrUnsafe as unknown as AmplitudeXMLHttpRequestSafe;\n const getJson = NetworkObserver.createXhrJsonParser(xhrUnsafe, networkObserverContext);\n const body = args[0] as XMLHttpRequestBodyInitSafe;\n const requestEvent = xhrSafe.$$AmplitudeAnalyticsEvent;\n\n xhrSafe.addEventListener('loadend', function () {\n try {\n const responseHeaders = xhrSafe.getAllResponseHeaders();\n const responseBodySize = xhrSafe.getResponseHeader('content-length');\n\n const responseWrapper = new ResponseWrapperXhr(\n xhrSafe.status,\n responseHeaders,\n /* istanbul ignore next */\n responseBodySize ? parseInt(responseBodySize, 10) : undefined,\n getJson,\n );\n const requestHeaders = xhrSafe.$$AmplitudeAnalyticsEvent.headers;\n const requestWrapper = new RequestWrapperXhr(body, requestHeaders);\n requestEvent.status = xhrSafe.status;\n networkObserverContext.handleNetworkRequestEvent(\n 'xhr',\n { url: requestEvent.url, method: requestEvent.method },\n requestWrapper,\n responseWrapper,\n undefined,\n requestEvent.startTime,\n requestEvent.durationStart,\n );\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.error('an unexpected error occurred while handling xhr send', err);\n }\n });\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n return originalXhrSend.apply(xhrSafe, args as any);\n };\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.setRequestHeader\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.setRequestHeader\n * and make sure another developer who is an expert reviews this change throughly\n */\n // allow \"any\" type for args to reflect how it's used in the browser\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n xhrProto.setRequestHeader = function (headerName: any, headerValue: any) {\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n try {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-assignment */\n xhrSafe.$$AmplitudeAnalyticsEvent.headers[headerName as string] = headerValue as string;\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.error('an unexpected error occurred while calling xhr setRequestHeader', err);\n }\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n originalXhrSetRequestHeader.apply(xhrSafe, [headerName, headerValue]);\n };\n }\n}\n\n// singleton instance of NetworkObserver\nexport const networkObserver = new NetworkObserver();\n"]}
|
|
@@ -73,7 +73,6 @@ export declare const MAXIMUM_ENTRIES = 100;
|
|
|
73
73
|
export declare class RequestWrapperFetch implements IRequestWrapper {
|
|
74
74
|
private request;
|
|
75
75
|
private _bodySize;
|
|
76
|
-
private consumptionCheck;
|
|
77
76
|
constructor(request: RequestInitSafe);
|
|
78
77
|
headers(allow?: string[]): Record<string, string> | undefined;
|
|
79
78
|
get bodySize(): number | undefined;
|
|
@@ -84,7 +83,6 @@ export declare class RequestWrapperFetch implements IRequestWrapper {
|
|
|
84
83
|
export declare class RequestWrapperXhr implements IRequestWrapper {
|
|
85
84
|
readonly bodyRaw: XMLHttpRequestBodyInitSafe | null;
|
|
86
85
|
readonly requestHeaders: Record<string, string>;
|
|
87
|
-
private consumptionCheck;
|
|
88
86
|
constructor(bodyRaw: XMLHttpRequestBodyInitSafe | null, requestHeaders: Record<string, string>);
|
|
89
87
|
headers(allow?: string[]): Record<string, string> | undefined;
|
|
90
88
|
get bodySize(): number | undefined;
|
|
@@ -106,7 +104,6 @@ export interface IResponseWrapper {
|
|
|
106
104
|
bodySize?: number;
|
|
107
105
|
status?: number;
|
|
108
106
|
body?: string | Blob | ReadableStream | ArrayBuffer | FormDataSafe | URLSearchParams | ArrayBufferView | null;
|
|
109
|
-
text: () => Promise<string | null>;
|
|
110
107
|
json: (allow?: string[], exclude?: string[]) => Promise<JsonObject | null>;
|
|
111
108
|
}
|
|
112
109
|
/**
|
|
@@ -131,7 +128,7 @@ export interface IResponseWrapper {
|
|
|
131
128
|
export declare class ResponseWrapperFetch implements IResponseWrapper {
|
|
132
129
|
private response;
|
|
133
130
|
private _bodySize;
|
|
134
|
-
private
|
|
131
|
+
private clonedResponse?;
|
|
135
132
|
constructor(response: ResponseSafe);
|
|
136
133
|
headers(allow?: string[]): Record<string, string> | undefined;
|
|
137
134
|
get bodySize(): number | undefined;
|
|
@@ -143,12 +140,10 @@ export declare class ResponseWrapperXhr implements IResponseWrapper {
|
|
|
143
140
|
readonly statusCode: number;
|
|
144
141
|
readonly headersString: string;
|
|
145
142
|
readonly size: number | undefined;
|
|
146
|
-
readonly
|
|
147
|
-
|
|
148
|
-
constructor(statusCode: number, headersString: string, size: number | undefined, responseText: string);
|
|
143
|
+
readonly getJson: () => any | null;
|
|
144
|
+
constructor(statusCode: number, headersString: string, size: number | undefined, getJson: () => any | null);
|
|
149
145
|
get bodySize(): number | undefined;
|
|
150
146
|
get status(): number;
|
|
151
|
-
text(): Promise<string | null>;
|
|
152
147
|
headers(allow?: string[]): Record<string, string> | undefined;
|
|
153
148
|
json(allow?: string[], exclude?: string[]): Promise<JsonObject | null>;
|
|
154
149
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-request-event.d.ts","sourceRoot":"","sources":["../../src/network-request-event.ts"],"names":[],"mappings":"AAQA,KAAK,QAAQ,GAAG;IACd,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,KAAK,eAAe,GAAG;IACrB,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,KAAK,mBAAmB,GAAG;IACzB,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,KAAK,mBAAmB,GAAG;IACzB,QAAQ,IAAI,MAAM,CAAC;CACpB,CAAC;AAKF,KAAK,sBAAsB,GAAG,MAAM,GAAG,QAAQ,GAAG,IAAI,CAAC;AAEvD,KAAK,YAAY,GACb,MAAM,GACN,IAAI,GACJ,eAAe,GACf,YAAY,GACZ,mBAAmB,GACnB,mBAAmB,GACnB,IAAI,GACJ,SAAS,CAAC;AAEd,KAAK,kBAAkB,GAAG;IACxB,OAAO,IAAI,gBAAgB,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;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,GAAG,kBAAkB,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,EAAE,EAAE,CAAC;AAEhF,KAAK,YAAY,GAAG;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,mBAAmB,GAAG,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iBACH,MAAM;iBAChB,EACe,OAAO,CAAC,oBAAQ;IAGlC,cAAc,IAAI,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;CAmBtC"}
|
|
@@ -4,23 +4,6 @@ import { pruneJson } from './utils/json-query';
|
|
|
4
4
|
import { SAFE_HEADERS, FORBIDDEN_HEADERS } from './';
|
|
5
5
|
var TEXT_READ_TIMEOUT = 500;
|
|
6
6
|
export var MAXIMUM_ENTRIES = 100;
|
|
7
|
-
/**
|
|
8
|
-
* This class is used to enforce the consumption of headers and body
|
|
9
|
-
* so that 'headers' and 'body' can only be accessed once.
|
|
10
|
-
*/
|
|
11
|
-
var ConsumptionCheck = /** @class */ (function () {
|
|
12
|
-
function ConsumptionCheck() {
|
|
13
|
-
this.headers = false;
|
|
14
|
-
this.body = false;
|
|
15
|
-
}
|
|
16
|
-
ConsumptionCheck.prototype.consume = function (objType) {
|
|
17
|
-
if (this[objType]) {
|
|
18
|
-
throw new TypeError("".concat(objType, " has already been consumed"));
|
|
19
|
-
}
|
|
20
|
-
this[objType] = true;
|
|
21
|
-
};
|
|
22
|
-
return ConsumptionCheck;
|
|
23
|
-
}());
|
|
24
7
|
/**
|
|
25
8
|
* This class encapsulates the RequestInit (https://developer.mozilla.org/en-US/docs/Web/API/RequestInit)
|
|
26
9
|
* object so that the consumer can only get access to the headers, method and body size.
|
|
@@ -42,12 +25,10 @@ var ConsumptionCheck = /** @class */ (function () {
|
|
|
42
25
|
var RequestWrapperFetch = /** @class */ (function () {
|
|
43
26
|
function RequestWrapperFetch(request) {
|
|
44
27
|
this.request = request;
|
|
45
|
-
this.consumptionCheck = new ConsumptionCheck();
|
|
46
28
|
}
|
|
47
29
|
RequestWrapperFetch.prototype.headers = function (allow) {
|
|
48
30
|
var e_1, _a;
|
|
49
31
|
if (allow === void 0) { allow = []; }
|
|
50
|
-
this.consumptionCheck.consume('headers');
|
|
51
32
|
var headersUnsafe = this.request.headers;
|
|
52
33
|
// copy the headers into a new object
|
|
53
34
|
var headersSafeCopy = {};
|
|
@@ -104,7 +85,6 @@ var RequestWrapperFetch = /** @class */ (function () {
|
|
|
104
85
|
});
|
|
105
86
|
Object.defineProperty(RequestWrapperFetch.prototype, "body", {
|
|
106
87
|
get: function () {
|
|
107
|
-
this.consumptionCheck.consume('body');
|
|
108
88
|
if (typeof this.request.body === 'string') {
|
|
109
89
|
return this.request.body;
|
|
110
90
|
}
|
|
@@ -134,11 +114,9 @@ var RequestWrapperXhr = /** @class */ (function () {
|
|
|
134
114
|
function RequestWrapperXhr(bodyRaw, requestHeaders) {
|
|
135
115
|
this.bodyRaw = bodyRaw;
|
|
136
116
|
this.requestHeaders = requestHeaders;
|
|
137
|
-
this.consumptionCheck = new ConsumptionCheck();
|
|
138
117
|
}
|
|
139
118
|
RequestWrapperXhr.prototype.headers = function (allow) {
|
|
140
119
|
if (allow === void 0) { allow = []; }
|
|
141
|
-
this.consumptionCheck.consume('headers');
|
|
142
120
|
return pruneHeaders(this.requestHeaders, { allow: allow });
|
|
143
121
|
};
|
|
144
122
|
Object.defineProperty(RequestWrapperXhr.prototype, "bodySize", {
|
|
@@ -150,7 +128,6 @@ var RequestWrapperXhr = /** @class */ (function () {
|
|
|
150
128
|
});
|
|
151
129
|
Object.defineProperty(RequestWrapperXhr.prototype, "body", {
|
|
152
130
|
get: function () {
|
|
153
|
-
this.consumptionCheck.consume('body');
|
|
154
131
|
if (typeof this.bodyRaw === 'string') {
|
|
155
132
|
return this.bodyRaw;
|
|
156
133
|
}
|
|
@@ -275,12 +252,10 @@ function getBodySize(bodyUnsafe, maxEntries) {
|
|
|
275
252
|
var ResponseWrapperFetch = /** @class */ (function () {
|
|
276
253
|
function ResponseWrapperFetch(response) {
|
|
277
254
|
this.response = response;
|
|
278
|
-
this.consumptionCheck = new ConsumptionCheck();
|
|
279
255
|
}
|
|
280
256
|
ResponseWrapperFetch.prototype.headers = function (allow) {
|
|
281
257
|
var _a;
|
|
282
258
|
if (allow === void 0) { allow = []; }
|
|
283
|
-
this.consumptionCheck.consume('headers');
|
|
284
259
|
if (this.response.headers instanceof Headers) {
|
|
285
260
|
var headersSafe = this.response.headers;
|
|
286
261
|
var headersOut_1 = {};
|
|
@@ -315,16 +290,19 @@ var ResponseWrapperFetch = /** @class */ (function () {
|
|
|
315
290
|
});
|
|
316
291
|
ResponseWrapperFetch.prototype.text = function () {
|
|
317
292
|
return __awaiter(this, void 0, void 0, function () {
|
|
318
|
-
var
|
|
293
|
+
var textPromise, timer, text, error_1;
|
|
319
294
|
return __generator(this, function (_a) {
|
|
320
295
|
switch (_a.label) {
|
|
321
296
|
case 0:
|
|
322
|
-
|
|
323
|
-
|
|
297
|
+
// !!!IMPORTANT: we clone the response to avoid mutating the original response
|
|
298
|
+
// never call .text(), .json(), etc.. on the original response always clone it first
|
|
299
|
+
if (!this.clonedResponse) {
|
|
300
|
+
this.clonedResponse = this.response.clone();
|
|
301
|
+
}
|
|
324
302
|
_a.label = 1;
|
|
325
303
|
case 1:
|
|
326
304
|
_a.trys.push([1, 3, , 4]);
|
|
327
|
-
textPromise = clonedResponse.text();
|
|
305
|
+
textPromise = this.clonedResponse.text();
|
|
328
306
|
timer = new Promise(function (resolve) {
|
|
329
307
|
return setTimeout(
|
|
330
308
|
/* istanbul ignore next */
|
|
@@ -365,12 +343,11 @@ var ResponseWrapperFetch = /** @class */ (function () {
|
|
|
365
343
|
}());
|
|
366
344
|
export { ResponseWrapperFetch };
|
|
367
345
|
var ResponseWrapperXhr = /** @class */ (function () {
|
|
368
|
-
function ResponseWrapperXhr(statusCode, headersString, size,
|
|
346
|
+
function ResponseWrapperXhr(statusCode, headersString, size, getJson) {
|
|
369
347
|
this.statusCode = statusCode;
|
|
370
348
|
this.headersString = headersString;
|
|
371
349
|
this.size = size;
|
|
372
|
-
this.
|
|
373
|
-
this.consumptionCheck = new ConsumptionCheck();
|
|
350
|
+
this.getJson = getJson;
|
|
374
351
|
}
|
|
375
352
|
Object.defineProperty(ResponseWrapperXhr.prototype, "bodySize", {
|
|
376
353
|
get: function () {
|
|
@@ -386,19 +363,9 @@ var ResponseWrapperXhr = /** @class */ (function () {
|
|
|
386
363
|
enumerable: false,
|
|
387
364
|
configurable: true
|
|
388
365
|
});
|
|
389
|
-
ResponseWrapperXhr.prototype.text = function () {
|
|
390
|
-
return __awaiter(this, void 0, void 0, function () {
|
|
391
|
-
return __generator(this, function (_a) {
|
|
392
|
-
// reject if body has already been consumed
|
|
393
|
-
this.consumptionCheck.consume('body');
|
|
394
|
-
return [2 /*return*/, this.responseText];
|
|
395
|
-
});
|
|
396
|
-
});
|
|
397
|
-
};
|
|
398
366
|
ResponseWrapperXhr.prototype.headers = function (allow) {
|
|
399
367
|
var e_3, _a;
|
|
400
368
|
if (allow === void 0) { allow = []; }
|
|
401
|
-
this.consumptionCheck.consume('headers');
|
|
402
369
|
if (!this.headersString) {
|
|
403
370
|
return {};
|
|
404
371
|
}
|
|
@@ -426,18 +393,17 @@ var ResponseWrapperXhr = /** @class */ (function () {
|
|
|
426
393
|
if (allow === void 0) { allow = []; }
|
|
427
394
|
if (exclude === void 0) { exclude = []; }
|
|
428
395
|
return __awaiter(this, void 0, void 0, function () {
|
|
429
|
-
var
|
|
396
|
+
var jsonBody;
|
|
430
397
|
return __generator(this, function (_a) {
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
text = _a.sent();
|
|
439
|
-
return [2 /*return*/, safeParseAndPruneBody(text, allow, exclude)];
|
|
398
|
+
if (allow.length === 0) {
|
|
399
|
+
return [2 /*return*/, null];
|
|
400
|
+
}
|
|
401
|
+
jsonBody = this.getJson();
|
|
402
|
+
if (jsonBody) {
|
|
403
|
+
pruneJson(jsonBody, allow, exclude);
|
|
404
|
+
return [2 /*return*/, jsonBody];
|
|
440
405
|
}
|
|
406
|
+
return [2 /*return*/, null];
|
|
441
407
|
});
|
|
442
408
|
});
|
|
443
409
|
};
|