@amplitude/plugin-autocapture-browser 1.27.4 → 1.28.0-featelement-selector-v1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/autocapture-plugin.d.ts.map +1 -1
- package/lib/cjs/autocapture-plugin.js +66 -2
- package/lib/cjs/autocapture-plugin.js.map +1 -1
- package/lib/cjs/data-extractor.d.ts +21 -0
- package/lib/cjs/data-extractor.d.ts.map +1 -1
- package/lib/cjs/data-extractor.js +26 -4
- package/lib/cjs/data-extractor.js.map +1 -1
- package/lib/cjs/libs/element-path.d.ts +23 -1
- package/lib/cjs/libs/element-path.d.ts.map +1 -1
- package/lib/cjs/libs/element-path.js +28 -173
- package/lib/cjs/libs/element-path.js.map +1 -1
- package/lib/cjs/version.d.ts +1 -1
- package/lib/cjs/version.d.ts.map +1 -1
- package/lib/cjs/version.js +1 -1
- package/lib/cjs/version.js.map +1 -1
- package/lib/esm/autocapture-plugin.d.ts.map +1 -1
- package/lib/esm/autocapture-plugin.js +66 -2
- package/lib/esm/autocapture-plugin.js.map +1 -1
- package/lib/esm/data-extractor.d.ts +21 -0
- package/lib/esm/data-extractor.d.ts.map +1 -1
- package/lib/esm/data-extractor.js +26 -4
- package/lib/esm/data-extractor.js.map +1 -1
- package/lib/esm/libs/element-path.d.ts +23 -1
- package/lib/esm/libs/element-path.d.ts.map +1 -1
- package/lib/esm/libs/element-path.js +27 -172
- package/lib/esm/libs/element-path.js.map +1 -1
- package/lib/esm/version.d.ts +1 -1
- package/lib/esm/version.d.ts.map +1 -1
- package/lib/esm/version.js +1 -1
- package/lib/esm/version.js.map +1 -1
- package/lib/scripts/amplitude-min.js +1 -1
- package/lib/scripts/amplitude-min.js.gz +0 -0
- package/lib/scripts/amplitude-min.js.map +1 -1
- package/lib/scripts/amplitude-min.umd.js +1 -1
- package/lib/scripts/amplitude-min.umd.js.gz +0 -0
- package/lib/scripts/autocapture-plugin.d.ts.map +1 -1
- package/lib/scripts/data-extractor.d.ts +21 -0
- package/lib/scripts/data-extractor.d.ts.map +1 -1
- package/lib/scripts/libs/element-path.d.ts +23 -1
- package/lib/scripts/libs/element-path.d.ts.map +1 -1
- package/lib/scripts/version.d.ts +1 -1
- package/lib/scripts/version.d.ts.map +1 -1
- package/package.json +3 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"autocapture-plugin.d.ts","sourceRoot":"","sources":["../../src/autocapture-plugin.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,aAAa,EAClB,KAAK,aAAa,EAClB,KAAK,gBAAgB,EACrB,KAAK,0BAA0B,EAK/B,kBAAkB,EAKnB,MAAM,2BAA2B,CAAC;AAGnC,OAAO,EAEL,KAAK,4BAA4B,EACjC,KAAK,gBAAgB,EACrB,KAAK,aAAa,EACnB,MAAM,WAAW,CAAC;AAoBnB,OAAO,EAAE,UAAU,EAAkB,MAAM,2BAA2B,CAAC;
|
|
1
|
+
{"version":3,"file":"autocapture-plugin.d.ts","sourceRoot":"","sources":["../../src/autocapture-plugin.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,aAAa,EAClB,KAAK,aAAa,EAClB,KAAK,gBAAgB,EACrB,KAAK,0BAA0B,EAK/B,kBAAkB,EAKnB,MAAM,2BAA2B,CAAC;AAGnC,OAAO,EAEL,KAAK,4BAA4B,EACjC,KAAK,gBAAgB,EACrB,KAAK,aAAa,EACnB,MAAM,WAAW,CAAC;AAoBnB,OAAO,EAAE,UAAU,EAAkB,MAAM,2BAA2B,CAAC;AAWvE,KAAK,cAAc,GAAG;IACpB,gBAAgB,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,kCAAkC,KAAK,IAAI,CAAC;IACvF,mBAAmB,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,kCAAkC,KAAK,IAAI,CAAC;CAC3F,CAAC;AAEF,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,MAAM;QACd,U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CAAC"}
|
|
@@ -16,8 +16,68 @@ var observables_1 = require("./observables");
|
|
|
16
16
|
var triggers_1 = require("./pageActions/triggers");
|
|
17
17
|
var data_extractor_1 = require("./data-extractor");
|
|
18
18
|
var analytics_core_2 = require("@amplitude/analytics-core");
|
|
19
|
+
var element_selector_1 = require("@amplitude/element-selector");
|
|
19
20
|
var track_exposure_1 = require("./autocapture/track-exposure");
|
|
20
21
|
var track_viewport_content_updated_1 = require("./autocapture/track-viewport-content-updated");
|
|
22
|
+
var subscribeRemoteConfig = function (config, key, callback) {
|
|
23
|
+
var remoteConfigClient = config.remoteConfigClient;
|
|
24
|
+
if (!remoteConfigClient) {
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
var subscriptionId = remoteConfigClient.subscribe(key, 'all', callback);
|
|
28
|
+
return {
|
|
29
|
+
unsubscribe: function () {
|
|
30
|
+
remoteConfigClient.unsubscribe(subscriptionId);
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
};
|
|
34
|
+
var attachElementSelectorSurface = function (amplitude, selectorEngine) {
|
|
35
|
+
// Expose a narrowed, read-only surface of the engine on the customer's
|
|
36
|
+
// BrowserClient instance so downstream consumers can use the same engine the
|
|
37
|
+
// SDK is running. Attach to the instance, not window.amplitude, so custom
|
|
38
|
+
// global names and multiple SDK instances do not clobber each other.
|
|
39
|
+
var elementSelectorClient = amplitude;
|
|
40
|
+
var hadPreviousElementSelector = Object.prototype.hasOwnProperty.call(elementSelectorClient, 'elementSelector');
|
|
41
|
+
var previousElementSelector = elementSelectorClient.elementSelector;
|
|
42
|
+
var elementSelectorSurface = {
|
|
43
|
+
generate: function (el) { return selectorEngine.generate(el); },
|
|
44
|
+
getConfig: function () { return selectorEngine.getConfig(); },
|
|
45
|
+
onConfigChange: function (cb) { return selectorEngine.onConfigChange(cb); },
|
|
46
|
+
};
|
|
47
|
+
/* istanbul ignore next */
|
|
48
|
+
elementSelectorClient.elementSelector = elementSelectorSurface;
|
|
49
|
+
return {
|
|
50
|
+
unsubscribe: function () {
|
|
51
|
+
if (hadPreviousElementSelector) {
|
|
52
|
+
elementSelectorClient.elementSelector = previousElementSelector;
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
delete elementSelectorClient.elementSelector;
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
var setupElementSelector = function (config, amplitude, dataExtractor) {
|
|
61
|
+
var subscriptions = [];
|
|
62
|
+
// Construct the engine eagerly with defaults so `dataExtractor.getElementPath`
|
|
63
|
+
// can route through it from the first emission. When `enabled` is false in
|
|
64
|
+
// the resolved config (the default), `getElementPath` falls back to the
|
|
65
|
+
// legacy `cssPath` algorithm.
|
|
66
|
+
var initialSelectorConfig = (0, element_selector_1.resolveSelectorConfig)(undefined, config.loggerProvider);
|
|
67
|
+
var selectorEngine = (0, element_selector_1.createSelectorEngine)(initialSelectorConfig, { logger: config.loggerProvider });
|
|
68
|
+
dataExtractor.setSelectorEngine(selectorEngine);
|
|
69
|
+
subscriptions.push(attachElementSelectorSurface(amplitude, selectorEngine));
|
|
70
|
+
if (config.fetchRemoteConfig) {
|
|
71
|
+
var elementSelectorSubscription = subscribeRemoteConfig(config, 'configs.analyticsSDK.autocapture.elementSelector', function (remoteSelectorConfig) {
|
|
72
|
+
var nextResolved = (0, element_selector_1.resolveSelectorConfig)(remoteSelectorConfig, config.loggerProvider);
|
|
73
|
+
selectorEngine.updateConfig(nextResolved);
|
|
74
|
+
});
|
|
75
|
+
if (elementSelectorSubscription) {
|
|
76
|
+
subscriptions.push(elementSelectorSubscription);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return subscriptions;
|
|
80
|
+
};
|
|
21
81
|
var ObservablesEnum;
|
|
22
82
|
(function (ObservablesEnum) {
|
|
23
83
|
ObservablesEnum["ClickObservable"] = "clickObservable";
|
|
@@ -138,7 +198,7 @@ var autocapturePlugin = function (options, context) {
|
|
|
138
198
|
}
|
|
139
199
|
};
|
|
140
200
|
var setup = function (config, amplitude) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
|
|
141
|
-
var pageViewEndFired, lastScroll, shouldTrackEvent, shouldTrackActionClick, allObservables, clickTrackingSubscription, changeSubscription, actionClickSubscription, scrollTracker, trackers, globalScope, handleViewportContentUpdated, handleExposure, beforeUnloadHandler_1, navigateObservable, popstateHandler_1, originalPushState_1, allowlist, actionClickAllowlist, messenger;
|
|
201
|
+
var pageViewEndFired, lastScroll, pageActionsSubscription, shouldTrackEvent, shouldTrackActionClick, allObservables, clickTrackingSubscription, changeSubscription, actionClickSubscription, scrollTracker, trackers, globalScope, handleViewportContentUpdated, handleExposure, beforeUnloadHandler_1, navigateObservable, popstateHandler_1, originalPushState_1, allowlist, actionClickAllowlist, messenger;
|
|
142
202
|
var _a;
|
|
143
203
|
return tslib_1.__generator(this, function (_b) {
|
|
144
204
|
/* istanbul ignore if */
|
|
@@ -154,11 +214,15 @@ var autocapturePlugin = function (options, context) {
|
|
|
154
214
|
config.loggerProvider.debug('Remote config client is not provided, skipping remote config fetch');
|
|
155
215
|
}
|
|
156
216
|
else {
|
|
157
|
-
config
|
|
217
|
+
pageActionsSubscription = subscribeRemoteConfig(config, 'configs.analyticsSDK.pageActions', function (remoteConfig) {
|
|
158
218
|
recomputePageActionsData(remoteConfig);
|
|
159
219
|
});
|
|
220
|
+
if (pageActionsSubscription) {
|
|
221
|
+
subscriptions.push(pageActionsSubscription);
|
|
222
|
+
}
|
|
160
223
|
}
|
|
161
224
|
}
|
|
225
|
+
subscriptions.push.apply(subscriptions, tslib_1.__spreadArray([], tslib_1.__read(setupElementSelector(config, amplitude, dataExtractor)), false));
|
|
162
226
|
shouldTrackEvent = (0, helpers_1.createShouldTrackEvent)(options, options.cssSelectorAllowlist);
|
|
163
227
|
shouldTrackActionClick = (0, helpers_1.createShouldTrackEvent)(options, options.actionClickAllowlist);
|
|
164
228
|
allObservables = createObservables();
|
|
@@ -1 +1 @@
|
|
|
1
|
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CAAuB,EAAC,SAAS,CAAC,CAAC;gBACnC,0BAA0B;gBAC1B,SAAS,CAAC,KAAK,oBACb,MAAM,EAAE,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,cAAc,IAC3B,CAAC,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,UAAU,KAAI,EAAE,QAAQ,EAAE,SAAS,CAAC,qBAAqB,CAAC,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC,EAC3F,CAAC;aACJ;;;SACF,CAAC;IAEF,IAAM,OAAO,GAAuC,UAAO,KAAK;;YAC9D,sBAAO,KAAK,EAAC;;SACd,CAAC;IAEF,IAAM,QAAQ,GAAG;;;;;gBACf,KAA2B,kBAAA,iBAAA,aAAa,CAAA,mHAAE;oBAA/B,YAAY;oBACrB,YAAY,CAAC,WAAW,EAAE,CAAC;iBAC5B;;;;;;;;;;;SACF,CAAC;IAEF,OAAO;QACL,IAAI,MAAA;QACJ,IAAI,MAAA;QACJ,KAAK,OAAA;QACL,OAAO,SAAA;QACP,QAAQ,UAAA;KACT,CAAC;AACJ,CAAC,CAAC;AAnYW,QAAA,iBAAiB,qBAmY5B","sourcesContent":["/* eslint-disable no-restricted-globals */\nimport {\n type BrowserClient,\n type BrowserConfig,\n type EnrichmentPlugin,\n type ElementInteractionsOptions,\n DEFAULT_EXPOSURE_DURATION,\n DEFAULT_CSS_SELECTOR_ALLOWLIST,\n DEFAULT_ACTION_CLICK_ALLOWLIST,\n DEFAULT_DATA_ATTRIBUTE_PREFIX,\n IDiagnosticsClient,\n getGlobalScope,\n getOrCreateWindowMessenger,\n enableBackgroundCapture,\n multicast,\n} from '@amplitude/analytics-core';\nimport { VERSION } from './version';\nimport * as constants from './constants';\nimport {\n createShouldTrackEvent,\n type ElementBasedTimestampedEvent,\n type TimestampedEvent,\n type NavigateEvent,\n} from './helpers';\nimport { enableVisualTagging } from './libs/messenger';\nimport { trackClicks } from './autocapture/track-click';\nimport { trackChange } from './autocapture/track-change';\nimport { trackActionClick } from './autocapture/track-action-click';\nimport { trackScroll } from './autocapture/track-scroll';\n\nimport {\n createClickObservable,\n createScrollObservable,\n createExposureObservable,\n createMutationObservable,\n} from './observables';\n\nimport {\n createLabeledEventToTriggerMap,\n createTriggerEvaluator,\n groupLabeledEventIdsByEventType,\n} from './pageActions/triggers';\nimport { DataExtractor } from './data-extractor';\nimport { Observable, Unsubscribable } from '@amplitude/analytics-core';\nimport { trackExposure } from './autocapture/track-exposure';\nimport { fireViewportContentUpdated, onExposure, ExposureTracker } from './autocapture/track-viewport-content-updated';\n\ntype NavigationType = {\n addEventListener: (type: string, listener: EventListenerOrEventListenerObject) => void;\n removeEventListener: (type: string, listener: EventListenerOrEventListenerObject) => void;\n};\n\ndeclare global {\n interface Window {\n navigation: NavigationType;\n }\n}\n\ntype BrowserEnrichmentPlugin = EnrichmentPlugin<BrowserClient, BrowserConfig>;\n\nexport type AutoCaptureOptionsWithDefaults = Required<\n Pick<ElementInteractionsOptions, 'debounceTime' | 'cssSelectorAllowlist' | 'actionClickAllowlist'>\n> &\n ElementInteractionsOptions;\n\nexport enum ObservablesEnum {\n ClickObservable = 'clickObservable',\n ChangeObservable = 'changeObservable',\n NavigateObservable = 'navigateObservable',\n MutationObservable = 'mutationObservable',\n ScrollObservable = 'scrollObservable',\n ExposureObservable = 'exposureObservable',\n BrowserErrorObservable = 'browserErrorObservable',\n SelectionObservable = 'selectionObservable',\n MouseMoveObservable = 'mouseMoveObservable',\n}\n\nexport interface AllWindowObservables {\n [ObservablesEnum.ChangeObservable]: Observable<ElementBasedTimestampedEvent<Event>>;\n // [ObservablesEnum.ErrorObservable]: Observable<TimestampedEvent<ErrorEvent>>;\n [ObservablesEnum.ClickObservable]: Observable<ElementBasedTimestampedEvent<MouseEvent>>;\n [ObservablesEnum.MutationObservable]: Observable<TimestampedEvent<MutationRecord[]>>;\n [ObservablesEnum.NavigateObservable]?: Observable<TimestampedEvent<NavigateEvent>>;\n [ObservablesEnum.ScrollObservable]: Observable<Event>; // TODO: add type for scroll event\n [ObservablesEnum.ExposureObservable]: Observable<Event>;\n [ObservablesEnum.SelectionObservable]?: Observable<void>;\n}\n\nexport const autocapturePlugin = (\n options: ElementInteractionsOptions = {},\n context?: { diagnosticsClient: IDiagnosticsClient },\n): BrowserEnrichmentPlugin => {\n // Set the plugin version tag\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n context?.diagnosticsClient.setTag('plugin.autocapture.version', VERSION);\n\n const {\n dataAttributePrefix = DEFAULT_DATA_ATTRIBUTE_PREFIX,\n visualTaggingOptions = {\n enabled: true,\n },\n } = options;\n\n options.cssSelectorAllowlist = options.cssSelectorAllowlist ?? DEFAULT_CSS_SELECTOR_ALLOWLIST;\n options.actionClickAllowlist = options.actionClickAllowlist ?? DEFAULT_ACTION_CLICK_ALLOWLIST;\n options.debounceTime = options.debounceTime ?? 0;\n const isViewportContentUpdatedEnabled = options.viewportContentUpdated?.enabled !== false;\n const resolvedExposureDuration =\n options.viewportContentUpdated?.exposureDuration ?? options.exposureDuration ?? DEFAULT_EXPOSURE_DURATION;\n options.viewportContentUpdated = {\n ...options.viewportContentUpdated,\n exposureDuration: resolvedExposureDuration,\n };\n\n options.pageUrlExcludelist = options.pageUrlExcludelist?.reduce(\n (acc: (string | RegExp | { pattern: string })[], excludePattern) => {\n if (typeof excludePattern === 'string') {\n acc.push(excludePattern);\n }\n if (excludePattern instanceof RegExp) {\n acc.push(excludePattern);\n }\n if (typeof excludePattern === 'object' && excludePattern !== null && 'pattern' in excludePattern) {\n try {\n acc.push(new RegExp(excludePattern.pattern));\n } catch (regexError) {\n console.warn(`Invalid regex pattern: ${excludePattern.pattern}`, regexError);\n return acc;\n }\n }\n return acc;\n },\n [],\n );\n\n const name = constants.PLUGIN_NAME;\n const type = 'enrichment';\n\n const subscriptions: Unsubscribable[] = [];\n\n const dataExtractor = new DataExtractor(options, context);\n\n // Page-level state shared across trackers, emitted in a single Page View End event on beforeunload\n // elementExposedForPage holds the total set of elements seen during the entire page view lifetime\n const elementExposedForPage = new Set<string>();\n // currentElementExposed only holds the set of elements that will be flushed during the next [Amplitude] Viewport Content Updated event\n const currentElementExposed = new Set<string>();\n\n let beforeUnloadCleanup: () => void;\n\n const createObservables = (): AllWindowObservables => {\n const clickObservable = multicast(\n createClickObservable().map(\n (click) =>\n dataExtractor.addAdditionalEventProperties(\n click,\n 'click',\n (options as AutoCaptureOptionsWithDefaults).cssSelectorAllowlist,\n dataAttributePrefix,\n ) as ElementBasedTimestampedEvent<MouseEvent>,\n ),\n );\n\n const changeObservable = multicast(\n new Observable<ElementBasedTimestampedEvent<Event>>((observer) => {\n const handler = (changeEvent: Event) => {\n const enrichedChangeEvent = dataExtractor.addAdditionalEventProperties(\n changeEvent,\n 'change',\n (options as AutoCaptureOptionsWithDefaults).cssSelectorAllowlist,\n dataAttributePrefix,\n ) as ElementBasedTimestampedEvent<Event>;\n observer.next(enrichedChangeEvent);\n };\n /* istanbul ignore next */\n getGlobalScope()?.document.addEventListener('change', handler, { capture: true });\n /* istanbul ignore next */\n return () => getGlobalScope()?.document.removeEventListener('change', handler);\n }),\n );\n\n // Create observable for URL changes\n let navigateObservable: Observable<TimestampedEvent<NavigateEvent>> | undefined;\n\n /* istanbul ignore next */\n if (window.navigation) {\n navigateObservable = multicast(\n new Observable<TimestampedEvent<NavigateEvent>>((observer) => {\n const handler = (navigateEvent: NavigateEvent) => {\n const enrichedNavigateEvent = dataExtractor.addAdditionalEventProperties(\n navigateEvent,\n 'navigate',\n (options as AutoCaptureOptionsWithDefaults).cssSelectorAllowlist,\n dataAttributePrefix,\n );\n observer.next(enrichedNavigateEvent);\n };\n window.navigation.addEventListener('navigate', handler as EventListener);\n return () => {\n window.navigation.removeEventListener('navigate', handler as EventListener);\n };\n }),\n );\n }\n\n const mutationObservable = multicast(\n createMutationObservable().map((mutation) =>\n dataExtractor.addAdditionalEventProperties(\n mutation,\n 'mutation',\n (options as AutoCaptureOptionsWithDefaults).cssSelectorAllowlist,\n dataAttributePrefix,\n ),\n ),\n );\n\n const scrollObservable = createScrollObservable();\n\n const exposureObservable = createExposureObservable(\n mutationObservable,\n (options as AutoCaptureOptionsWithDefaults).cssSelectorAllowlist,\n );\n\n return {\n [ObservablesEnum.ChangeObservable]: changeObservable,\n // [ObservablesEnum.ErrorObservable]: errorObservable,\n [ObservablesEnum.ClickObservable]: clickObservable,\n [ObservablesEnum.MutationObservable]: mutationObservable,\n [ObservablesEnum.NavigateObservable]: navigateObservable,\n [ObservablesEnum.ScrollObservable]: scrollObservable,\n [ObservablesEnum.ExposureObservable]: exposureObservable,\n };\n };\n\n // Group labeled events by event type (eg. click, change)\n let groupedLabeledEvents = groupLabeledEventIdsByEventType(Object.values(options.pageActions?.labeledEvents ?? {}));\n\n let labeledEventToTriggerMap = createLabeledEventToTriggerMap(options.pageActions?.triggers ?? []);\n\n // Evaluate triggers for the given event by running the actions associated with the matching triggers\n const evaluateTriggers = createTriggerEvaluator(\n groupedLabeledEvents,\n labeledEventToTriggerMap,\n dataExtractor,\n options,\n );\n\n // Function to recalculate internal variables when remote config is updated\n const recomputePageActionsData = (remotePageActions: ElementInteractionsOptions['pageActions']) => {\n if (remotePageActions) {\n // Merge remote config with local options\n options.pageActions = {\n ...options.pageActions,\n ...remotePageActions,\n };\n\n // Recalculate internal variables\n groupedLabeledEvents = groupLabeledEventIdsByEventType(Object.values(options.pageActions.labeledEvents ?? {}));\n labeledEventToTriggerMap = createLabeledEventToTriggerMap(options.pageActions.triggers ?? []);\n\n // Update evaluateTriggers function\n evaluateTriggers.update(groupedLabeledEvents, labeledEventToTriggerMap, options);\n }\n };\n\n const setup: BrowserEnrichmentPlugin['setup'] = async (config, amplitude) => {\n /* istanbul ignore if */\n if (typeof document === 'undefined') {\n return;\n }\n\n let pageViewEndFired = false;\n const lastScroll: { maxX: undefined | number; maxY: undefined | number } = { maxX: undefined, maxY: undefined };\n\n // Fetch remote config for pageActions in a non-blocking manner\n if (config.fetchRemoteConfig) {\n if (!config.remoteConfigClient) {\n // TODO(xinyi): Diagnostics.recordEvent\n config.loggerProvider.debug('Remote config client is not provided, skipping remote config fetch');\n } else {\n config.remoteConfigClient.subscribe('configs.analyticsSDK.pageActions', 'all', (remoteConfig) => {\n recomputePageActionsData(remoteConfig as ElementInteractionsOptions['pageActions']);\n });\n }\n }\n\n // Create should track event functions the different allowlists\n const shouldTrackEvent = createShouldTrackEvent(\n options,\n (options as AutoCaptureOptionsWithDefaults).cssSelectorAllowlist,\n );\n const shouldTrackActionClick = createShouldTrackEvent(\n options,\n (options as AutoCaptureOptionsWithDefaults).actionClickAllowlist,\n );\n\n // Create observables for events on the window\n const allObservables = createObservables();\n\n // Create subscriptions\n const clickTrackingSubscription = trackClicks({\n allObservables,\n amplitude,\n shouldTrackEvent: shouldTrackEvent,\n evaluateTriggers: evaluateTriggers.evaluate.bind(evaluateTriggers),\n });\n\n subscriptions.push(clickTrackingSubscription);\n\n const changeSubscription = trackChange({\n allObservables,\n getEventProperties: (...args) => dataExtractor.getEventProperties(...args, dataAttributePrefix),\n amplitude,\n shouldTrackEvent: shouldTrackEvent,\n evaluateTriggers: evaluateTriggers.evaluate.bind(evaluateTriggers),\n });\n subscriptions.push(changeSubscription);\n\n const actionClickSubscription = trackActionClick({\n allObservables,\n options: options as AutoCaptureOptionsWithDefaults,\n getEventProperties: (...args) => dataExtractor.getEventProperties(...args, dataAttributePrefix),\n amplitude,\n shouldTrackEvent,\n shouldTrackActionClick: shouldTrackActionClick,\n });\n if (actionClickSubscription) {\n subscriptions.push(actionClickSubscription);\n }\n\n const scrollTracker = trackScroll({\n allObservables,\n amplitude,\n });\n subscriptions.push(scrollTracker);\n\n const trackers: { exposure?: ExposureTracker & Unsubscribable } = {};\n\n const globalScope = getGlobalScope();\n\n const handleViewportContentUpdated = (isPageEnd: boolean) => {\n if (isPageEnd && pageViewEndFired) {\n return;\n }\n setTimeout(() => {\n pageViewEndFired = false;\n }, 100);\n\n pageViewEndFired = true;\n fireViewportContentUpdated({\n amplitude,\n scrollTracker,\n currentElementExposed,\n elementExposedForPage,\n exposureTracker: trackers.exposure,\n isPageEnd,\n lastScroll,\n });\n };\n\n const handleExposure = (elementPath: string) => {\n onExposure(elementPath, elementExposedForPage, currentElementExposed, handleViewportContentUpdated);\n };\n\n if (isViewportContentUpdatedEnabled) {\n trackers.exposure = trackExposure({\n allObservables,\n onExposure: handleExposure,\n dataExtractor,\n exposureDuration: resolvedExposureDuration,\n });\n if (trackers.exposure) {\n subscriptions.push(trackers.exposure);\n }\n\n const beforeUnloadHandler = () => {\n handleViewportContentUpdated(true);\n };\n /* istanbul ignore next */\n globalScope?.addEventListener('beforeunload', beforeUnloadHandler);\n beforeUnloadCleanup = () => {\n /* istanbul ignore next */\n globalScope?.removeEventListener('beforeunload', beforeUnloadHandler);\n };\n // Ensure cleanup on teardown as well\n subscriptions.push({ unsubscribe: () => beforeUnloadCleanup() });\n\n // Also track on navigation (SPA)\n const navigateObservable = allObservables[ObservablesEnum.NavigateObservable];\n if (navigateObservable) {\n subscriptions.push(\n navigateObservable.subscribe(() => {\n handleViewportContentUpdated(true);\n }),\n );\n } else if (globalScope) {\n const popstateHandler = () => {\n handleViewportContentUpdated(true);\n };\n /* istanbul ignore next */\n // Fallback for SPA tracking when Navigation API is not available\n globalScope.addEventListener('popstate', popstateHandler);\n\n /* istanbul ignore next */\n // There is no global browser listener for changes to history, so we have\n // to modify pushState directly.\n // https://stackoverflow.com/a/64927639\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalPushState = globalScope.history.pushState;\n if (globalScope.history && originalPushState) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n globalScope.history.pushState = new Proxy(originalPushState, {\n apply: (target, thisArg, [state, unused, url]) => {\n target.apply(thisArg, [state, unused, url]);\n handleViewportContentUpdated(true);\n },\n });\n }\n\n subscriptions.push({\n unsubscribe: () => {\n /* istanbul ignore next */\n globalScope.removeEventListener('popstate', popstateHandler);\n /* istanbul ignore next */\n if (globalScope.history && originalPushState) {\n globalScope.history.pushState = originalPushState;\n }\n },\n });\n }\n }\n\n /* istanbul ignore next */\n config?.loggerProvider?.log(`${name} has been successfully added.`);\n\n // Setup visual tagging and background capture on the shared messenger singleton.\n // Using the singleton ensures a single message listener per page, even when\n // session-replay is also loaded.\n if (window.opener && visualTaggingOptions.enabled) {\n const allowlist = (options as AutoCaptureOptionsWithDefaults).cssSelectorAllowlist;\n const actionClickAllowlist = (options as AutoCaptureOptionsWithDefaults).actionClickAllowlist;\n\n const messenger = getOrCreateWindowMessenger();\n enableVisualTagging(messenger, {\n dataExtractor,\n isElementSelectable: createShouldTrackEvent(options, [...allowlist, ...actionClickAllowlist]),\n cssSelectorAllowlist: allowlist,\n actionClickAllowlist,\n });\n enableBackgroundCapture(messenger);\n /* istanbul ignore next */\n messenger.setup({\n logger: config?.loggerProvider,\n ...(config?.serverZone && { endpoint: constants.AMPLITUDE_ORIGINS_MAP[config.serverZone] }),\n });\n }\n };\n\n const execute: BrowserEnrichmentPlugin['execute'] = async (event) => {\n return event;\n };\n\n const teardown = async () => {\n for (const subscription of subscriptions) {\n subscription.unsubscribe();\n }\n };\n\n return {\n name,\n type,\n setup,\n execute,\n teardown,\n };\n};\n"]}
|
|
1
|
+
{"version":3,"file":"autocapture-plugin.js","sourceRoot":"","sources":["../../src/autocapture-plugin.ts"],"names":[],"mappings":";;;;AAAA,0CAA0C;AAC1C,4DAcmC;AACnC,qCAAoC;AACpC,6DAAyC;AACzC,qCAKmB;AACnB,8CAAuD;AACvD,yDAAwD;AACxD,2DAAyD;AACzD,uEAAoE;AACpE,2DAAyD;AAEzD,6CAKuB;AAEvB,mDAIgC;AAChC,mDAAiD;AACjD,4DAAuE;AACvE,gEAMqC;AACrC,+DAA6D;AAC7D,+FAAuH;AAsBvH,IAAM,qBAAqB,GAAG,UAC5B,MAAqB,EACrB,GAAW,EACX,QAA8B;IAE9B,IAAM,kBAAkB,GAAG,MAAM,CAAC,kBAAkB,CAAC;IACrD,IAAI,CAAC,kBAAkB,EAAE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QACL,IAAI,MAAA;QACJ,IAAI,MAAA;QACJ,KAAK,OAAA;QACL,OAAO,SAAA;QACP,QAAQ,UAAA;KACT,CAAC;AACJ,CAAC,CAAC;AA5YW,QAAA,iBAAiB,qBA4Y5B","sourcesContent":["/* eslint-disable no-restricted-globals */\nimport {\n type BrowserClient,\n type BrowserConfig,\n type EnrichmentPlugin,\n type ElementInteractionsOptions,\n DEFAULT_EXPOSURE_DURATION,\n DEFAULT_CSS_SELECTOR_ALLOWLIST,\n DEFAULT_ACTION_CLICK_ALLOWLIST,\n DEFAULT_DATA_ATTRIBUTE_PREFIX,\n IDiagnosticsClient,\n getGlobalScope,\n getOrCreateWindowMessenger,\n enableBackgroundCapture,\n multicast,\n} from '@amplitude/analytics-core';\nimport { VERSION } from './version';\nimport * as constants from './constants';\nimport {\n createShouldTrackEvent,\n type ElementBasedTimestampedEvent,\n type TimestampedEvent,\n type NavigateEvent,\n} from './helpers';\nimport { enableVisualTagging } from './libs/messenger';\nimport { trackClicks } from './autocapture/track-click';\nimport { trackChange } from './autocapture/track-change';\nimport { trackActionClick } from './autocapture/track-action-click';\nimport { trackScroll } from './autocapture/track-scroll';\n\nimport {\n createClickObservable,\n createScrollObservable,\n createExposureObservable,\n createMutationObservable,\n} from './observables';\n\nimport {\n createLabeledEventToTriggerMap,\n createTriggerEvaluator,\n groupLabeledEventIdsByEventType,\n} from './pageActions/triggers';\nimport { DataExtractor } from './data-extractor';\nimport { Observable, Unsubscribable } from '@amplitude/analytics-core';\nimport {\n createSelectorEngine,\n resolveSelectorConfig,\n type ElementSelectorRemoteConfig,\n type ResolvedSelectorConfig,\n type SelectorEngine,\n} from '@amplitude/element-selector';\nimport { trackExposure } from './autocapture/track-exposure';\nimport { fireViewportContentUpdated, onExposure, ExposureTracker } from './autocapture/track-viewport-content-updated';\n\ntype NavigationType = {\n addEventListener: (type: string, listener: EventListenerOrEventListenerObject) => void;\n removeEventListener: (type: string, listener: EventListenerOrEventListenerObject) => void;\n};\n\ndeclare global {\n interface Window {\n navigation: NavigationType;\n }\n}\n\ntype BrowserEnrichmentPlugin = EnrichmentPlugin<BrowserClient, BrowserConfig>;\ntype ElementSelectorPublicSurface = {\n generate: (el: Element) => string;\n getConfig: () => Readonly<ResolvedSelectorConfig>;\n onConfigChange: (cb: (config: ResolvedSelectorConfig) => void) => () => void;\n};\ntype BrowserClientWithElementSelector = BrowserClient & { elementSelector?: unknown };\ntype RemoteConfigCallback = Parameters<NonNullable<BrowserConfig['remoteConfigClient']>['subscribe']>[2];\n\nconst subscribeRemoteConfig = (\n config: BrowserConfig,\n key: string,\n callback: RemoteConfigCallback,\n): Unsubscribable | undefined => {\n const remoteConfigClient = config.remoteConfigClient;\n if (!remoteConfigClient) {\n return undefined;\n }\n const subscriptionId = remoteConfigClient.subscribe(key, 'all', callback);\n return {\n unsubscribe: () => {\n remoteConfigClient.unsubscribe(subscriptionId);\n },\n };\n};\n\nconst attachElementSelectorSurface = (amplitude: BrowserClient, selectorEngine: SelectorEngine): Unsubscribable => {\n // Expose a narrowed, read-only surface of the engine on the customer's\n // BrowserClient instance so downstream consumers can use the same engine the\n // SDK is running. Attach to the instance, not window.amplitude, so custom\n // global names and multiple SDK instances do not clobber each other.\n const elementSelectorClient = amplitude as BrowserClientWithElementSelector;\n const hadPreviousElementSelector = Object.prototype.hasOwnProperty.call(elementSelectorClient, 'elementSelector');\n const previousElementSelector = elementSelectorClient.elementSelector;\n const elementSelectorSurface: ElementSelectorPublicSurface = {\n generate: (el: Element): string => selectorEngine.generate(el),\n getConfig: () => selectorEngine.getConfig(),\n onConfigChange: (cb: (config: ResolvedSelectorConfig) => void): (() => void) => selectorEngine.onConfigChange(cb),\n };\n /* istanbul ignore next */\n elementSelectorClient.elementSelector = elementSelectorSurface;\n\n return {\n unsubscribe: () => {\n if (hadPreviousElementSelector) {\n elementSelectorClient.elementSelector = previousElementSelector;\n } else {\n delete elementSelectorClient.elementSelector;\n }\n },\n };\n};\n\nconst setupElementSelector = (\n config: BrowserConfig,\n amplitude: BrowserClient,\n dataExtractor: DataExtractor,\n): Unsubscribable[] => {\n const subscriptions: Unsubscribable[] = [];\n\n // Construct the engine eagerly with defaults so `dataExtractor.getElementPath`\n // can route through it from the first emission. When `enabled` is false in\n // the resolved config (the default), `getElementPath` falls back to the\n // legacy `cssPath` algorithm.\n const initialSelectorConfig = resolveSelectorConfig(undefined, config.loggerProvider);\n const selectorEngine = createSelectorEngine(initialSelectorConfig, { logger: config.loggerProvider });\n dataExtractor.setSelectorEngine(selectorEngine);\n\n subscriptions.push(attachElementSelectorSurface(amplitude, selectorEngine));\n\n if (config.fetchRemoteConfig) {\n const elementSelectorSubscription = subscribeRemoteConfig(\n config,\n 'configs.analyticsSDK.autocapture.elementSelector',\n (remoteSelectorConfig) => {\n const nextResolved = resolveSelectorConfig(\n remoteSelectorConfig as ElementSelectorRemoteConfig | undefined,\n config.loggerProvider,\n );\n selectorEngine.updateConfig(nextResolved);\n },\n );\n if (elementSelectorSubscription) {\n subscriptions.push(elementSelectorSubscription);\n }\n }\n\n return subscriptions;\n};\n\nexport type AutoCaptureOptionsWithDefaults = Required<\n Pick<ElementInteractionsOptions, 'debounceTime' | 'cssSelectorAllowlist' | 'actionClickAllowlist'>\n> &\n ElementInteractionsOptions;\n\nexport enum ObservablesEnum {\n ClickObservable = 'clickObservable',\n ChangeObservable = 'changeObservable',\n NavigateObservable = 'navigateObservable',\n MutationObservable = 'mutationObservable',\n ScrollObservable = 'scrollObservable',\n ExposureObservable = 'exposureObservable',\n BrowserErrorObservable = 'browserErrorObservable',\n SelectionObservable = 'selectionObservable',\n MouseMoveObservable = 'mouseMoveObservable',\n}\n\nexport interface AllWindowObservables {\n [ObservablesEnum.ChangeObservable]: Observable<ElementBasedTimestampedEvent<Event>>;\n // [ObservablesEnum.ErrorObservable]: Observable<TimestampedEvent<ErrorEvent>>;\n [ObservablesEnum.ClickObservable]: Observable<ElementBasedTimestampedEvent<MouseEvent>>;\n [ObservablesEnum.MutationObservable]: Observable<TimestampedEvent<MutationRecord[]>>;\n [ObservablesEnum.NavigateObservable]?: Observable<TimestampedEvent<NavigateEvent>>;\n [ObservablesEnum.ScrollObservable]: Observable<Event>; // TODO: add type for scroll event\n [ObservablesEnum.ExposureObservable]: Observable<Event>;\n [ObservablesEnum.SelectionObservable]?: Observable<void>;\n}\n\nexport const autocapturePlugin = (\n options: ElementInteractionsOptions = {},\n context?: { diagnosticsClient: IDiagnosticsClient },\n): BrowserEnrichmentPlugin => {\n // Set the plugin version tag\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n context?.diagnosticsClient.setTag('plugin.autocapture.version', VERSION);\n\n const {\n dataAttributePrefix = DEFAULT_DATA_ATTRIBUTE_PREFIX,\n visualTaggingOptions = {\n enabled: true,\n },\n } = options;\n\n options.cssSelectorAllowlist = options.cssSelectorAllowlist ?? DEFAULT_CSS_SELECTOR_ALLOWLIST;\n options.actionClickAllowlist = options.actionClickAllowlist ?? DEFAULT_ACTION_CLICK_ALLOWLIST;\n options.debounceTime = options.debounceTime ?? 0;\n const isViewportContentUpdatedEnabled = options.viewportContentUpdated?.enabled !== false;\n const resolvedExposureDuration =\n options.viewportContentUpdated?.exposureDuration ?? options.exposureDuration ?? DEFAULT_EXPOSURE_DURATION;\n options.viewportContentUpdated = {\n ...options.viewportContentUpdated,\n exposureDuration: resolvedExposureDuration,\n };\n\n options.pageUrlExcludelist = options.pageUrlExcludelist?.reduce(\n (acc: (string | RegExp | { pattern: string })[], excludePattern) => {\n if (typeof excludePattern === 'string') {\n acc.push(excludePattern);\n }\n if (excludePattern instanceof RegExp) {\n acc.push(excludePattern);\n }\n if (typeof excludePattern === 'object' && excludePattern !== null && 'pattern' in excludePattern) {\n try {\n acc.push(new RegExp(excludePattern.pattern));\n } catch (regexError) {\n console.warn(`Invalid regex pattern: ${excludePattern.pattern}`, regexError);\n return acc;\n }\n }\n return acc;\n },\n [],\n );\n\n const name = constants.PLUGIN_NAME;\n const type = 'enrichment';\n\n const subscriptions: Unsubscribable[] = [];\n\n const dataExtractor = new DataExtractor(options, context);\n\n // Page-level state shared across trackers, emitted in a single Page View End event on beforeunload\n // elementExposedForPage holds the total set of elements seen during the entire page view lifetime\n const elementExposedForPage = new Set<string>();\n // currentElementExposed only holds the set of elements that will be flushed during the next [Amplitude] Viewport Content Updated event\n const currentElementExposed = new Set<string>();\n\n let beforeUnloadCleanup: () => void;\n\n const createObservables = (): AllWindowObservables => {\n const clickObservable = multicast(\n createClickObservable().map(\n (click) =>\n dataExtractor.addAdditionalEventProperties(\n click,\n 'click',\n (options as AutoCaptureOptionsWithDefaults).cssSelectorAllowlist,\n dataAttributePrefix,\n ) as ElementBasedTimestampedEvent<MouseEvent>,\n ),\n );\n\n const changeObservable = multicast(\n new Observable<ElementBasedTimestampedEvent<Event>>((observer) => {\n const handler = (changeEvent: Event) => {\n const enrichedChangeEvent = dataExtractor.addAdditionalEventProperties(\n changeEvent,\n 'change',\n (options as AutoCaptureOptionsWithDefaults).cssSelectorAllowlist,\n dataAttributePrefix,\n ) as ElementBasedTimestampedEvent<Event>;\n observer.next(enrichedChangeEvent);\n };\n /* istanbul ignore next */\n getGlobalScope()?.document.addEventListener('change', handler, { capture: true });\n /* istanbul ignore next */\n return () => getGlobalScope()?.document.removeEventListener('change', handler);\n }),\n );\n\n // Create observable for URL changes\n let navigateObservable: Observable<TimestampedEvent<NavigateEvent>> | undefined;\n\n /* istanbul ignore next */\n if (window.navigation) {\n navigateObservable = multicast(\n new Observable<TimestampedEvent<NavigateEvent>>((observer) => {\n const handler = (navigateEvent: NavigateEvent) => {\n const enrichedNavigateEvent = dataExtractor.addAdditionalEventProperties(\n navigateEvent,\n 'navigate',\n (options as AutoCaptureOptionsWithDefaults).cssSelectorAllowlist,\n dataAttributePrefix,\n );\n observer.next(enrichedNavigateEvent);\n };\n window.navigation.addEventListener('navigate', handler as EventListener);\n return () => {\n window.navigation.removeEventListener('navigate', handler as EventListener);\n };\n }),\n );\n }\n\n const mutationObservable = multicast(\n createMutationObservable().map((mutation) =>\n dataExtractor.addAdditionalEventProperties(\n mutation,\n 'mutation',\n (options as AutoCaptureOptionsWithDefaults).cssSelectorAllowlist,\n dataAttributePrefix,\n ),\n ),\n );\n\n const scrollObservable = createScrollObservable();\n\n const exposureObservable = createExposureObservable(\n mutationObservable,\n (options as AutoCaptureOptionsWithDefaults).cssSelectorAllowlist,\n );\n\n return {\n [ObservablesEnum.ChangeObservable]: changeObservable,\n // [ObservablesEnum.ErrorObservable]: errorObservable,\n [ObservablesEnum.ClickObservable]: clickObservable,\n [ObservablesEnum.MutationObservable]: mutationObservable,\n [ObservablesEnum.NavigateObservable]: navigateObservable,\n [ObservablesEnum.ScrollObservable]: scrollObservable,\n [ObservablesEnum.ExposureObservable]: exposureObservable,\n };\n };\n\n // Group labeled events by event type (eg. click, change)\n let groupedLabeledEvents = groupLabeledEventIdsByEventType(Object.values(options.pageActions?.labeledEvents ?? {}));\n\n let labeledEventToTriggerMap = createLabeledEventToTriggerMap(options.pageActions?.triggers ?? []);\n\n // Evaluate triggers for the given event by running the actions associated with the matching triggers\n const evaluateTriggers = createTriggerEvaluator(\n groupedLabeledEvents,\n labeledEventToTriggerMap,\n dataExtractor,\n options,\n );\n\n // Function to recalculate internal variables when remote config is updated\n const recomputePageActionsData = (remotePageActions: ElementInteractionsOptions['pageActions']) => {\n if (remotePageActions) {\n // Merge remote config with local options\n options.pageActions = {\n ...options.pageActions,\n ...remotePageActions,\n };\n\n // Recalculate internal variables\n groupedLabeledEvents = groupLabeledEventIdsByEventType(Object.values(options.pageActions.labeledEvents ?? {}));\n labeledEventToTriggerMap = createLabeledEventToTriggerMap(options.pageActions.triggers ?? []);\n\n // Update evaluateTriggers function\n evaluateTriggers.update(groupedLabeledEvents, labeledEventToTriggerMap, options);\n }\n };\n\n const setup: BrowserEnrichmentPlugin['setup'] = async (config, amplitude) => {\n /* istanbul ignore if */\n if (typeof document === 'undefined') {\n return;\n }\n\n let pageViewEndFired = false;\n const lastScroll: { maxX: undefined | number; maxY: undefined | number } = { maxX: undefined, maxY: undefined };\n\n // Fetch remote config for pageActions in a non-blocking manner\n if (config.fetchRemoteConfig) {\n if (!config.remoteConfigClient) {\n // TODO(xinyi): Diagnostics.recordEvent\n config.loggerProvider.debug('Remote config client is not provided, skipping remote config fetch');\n } else {\n const pageActionsSubscription = subscribeRemoteConfig(\n config,\n 'configs.analyticsSDK.pageActions',\n (remoteConfig) => {\n recomputePageActionsData(remoteConfig as ElementInteractionsOptions['pageActions']);\n },\n );\n if (pageActionsSubscription) {\n subscriptions.push(pageActionsSubscription);\n }\n }\n }\n\n subscriptions.push(...setupElementSelector(config, amplitude, dataExtractor));\n\n // Create should track event functions the different allowlists\n const shouldTrackEvent = createShouldTrackEvent(\n options,\n (options as AutoCaptureOptionsWithDefaults).cssSelectorAllowlist,\n );\n const shouldTrackActionClick = createShouldTrackEvent(\n options,\n (options as AutoCaptureOptionsWithDefaults).actionClickAllowlist,\n );\n\n // Create observables for events on the window\n const allObservables = createObservables();\n\n // Create subscriptions\n const clickTrackingSubscription = trackClicks({\n allObservables,\n amplitude,\n shouldTrackEvent: shouldTrackEvent,\n evaluateTriggers: evaluateTriggers.evaluate.bind(evaluateTriggers),\n });\n\n subscriptions.push(clickTrackingSubscription);\n\n const changeSubscription = trackChange({\n allObservables,\n getEventProperties: (...args) => dataExtractor.getEventProperties(...args, dataAttributePrefix),\n amplitude,\n shouldTrackEvent: shouldTrackEvent,\n evaluateTriggers: evaluateTriggers.evaluate.bind(evaluateTriggers),\n });\n subscriptions.push(changeSubscription);\n\n const actionClickSubscription = trackActionClick({\n allObservables,\n options: options as AutoCaptureOptionsWithDefaults,\n getEventProperties: (...args) => dataExtractor.getEventProperties(...args, dataAttributePrefix),\n amplitude,\n shouldTrackEvent,\n shouldTrackActionClick: shouldTrackActionClick,\n });\n if (actionClickSubscription) {\n subscriptions.push(actionClickSubscription);\n }\n\n const scrollTracker = trackScroll({\n allObservables,\n amplitude,\n });\n subscriptions.push(scrollTracker);\n\n const trackers: { exposure?: ExposureTracker & Unsubscribable } = {};\n\n const globalScope = getGlobalScope();\n\n const handleViewportContentUpdated = (isPageEnd: boolean) => {\n if (isPageEnd && pageViewEndFired) {\n return;\n }\n setTimeout(() => {\n pageViewEndFired = false;\n }, 100);\n\n pageViewEndFired = true;\n fireViewportContentUpdated({\n amplitude,\n scrollTracker,\n currentElementExposed,\n elementExposedForPage,\n exposureTracker: trackers.exposure,\n isPageEnd,\n lastScroll,\n });\n };\n\n const handleExposure = (elementPath: string) => {\n onExposure(elementPath, elementExposedForPage, currentElementExposed, handleViewportContentUpdated);\n };\n\n if (isViewportContentUpdatedEnabled) {\n trackers.exposure = trackExposure({\n allObservables,\n onExposure: handleExposure,\n dataExtractor,\n exposureDuration: resolvedExposureDuration,\n });\n if (trackers.exposure) {\n subscriptions.push(trackers.exposure);\n }\n\n const beforeUnloadHandler = () => {\n handleViewportContentUpdated(true);\n };\n /* istanbul ignore next */\n globalScope?.addEventListener('beforeunload', beforeUnloadHandler);\n beforeUnloadCleanup = () => {\n /* istanbul ignore next */\n globalScope?.removeEventListener('beforeunload', beforeUnloadHandler);\n };\n // Ensure cleanup on teardown as well\n subscriptions.push({ unsubscribe: () => beforeUnloadCleanup() });\n\n // Also track on navigation (SPA)\n const navigateObservable = allObservables[ObservablesEnum.NavigateObservable];\n if (navigateObservable) {\n subscriptions.push(\n navigateObservable.subscribe(() => {\n handleViewportContentUpdated(true);\n }),\n );\n } else if (globalScope) {\n const popstateHandler = () => {\n handleViewportContentUpdated(true);\n };\n /* istanbul ignore next */\n // Fallback for SPA tracking when Navigation API is not available\n globalScope.addEventListener('popstate', popstateHandler);\n\n /* istanbul ignore next */\n // There is no global browser listener for changes to history, so we have\n // to modify pushState directly.\n // https://stackoverflow.com/a/64927639\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalPushState = globalScope.history.pushState;\n if (globalScope.history && originalPushState) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n globalScope.history.pushState = new Proxy(originalPushState, {\n apply: (target, thisArg, [state, unused, url]) => {\n target.apply(thisArg, [state, unused, url]);\n handleViewportContentUpdated(true);\n },\n });\n }\n\n subscriptions.push({\n unsubscribe: () => {\n /* istanbul ignore next */\n globalScope.removeEventListener('popstate', popstateHandler);\n /* istanbul ignore next */\n if (globalScope.history && originalPushState) {\n globalScope.history.pushState = originalPushState;\n }\n },\n });\n }\n }\n\n /* istanbul ignore next */\n config?.loggerProvider?.log(`${name} has been successfully added.`);\n\n // Setup visual tagging and background capture on the shared messenger singleton.\n // Using the singleton ensures a single message listener per page, even when\n // session-replay is also loaded.\n if (window.opener && visualTaggingOptions.enabled) {\n const allowlist = (options as AutoCaptureOptionsWithDefaults).cssSelectorAllowlist;\n const actionClickAllowlist = (options as AutoCaptureOptionsWithDefaults).actionClickAllowlist;\n\n const messenger = getOrCreateWindowMessenger();\n enableVisualTagging(messenger, {\n dataExtractor,\n isElementSelectable: createShouldTrackEvent(options, [...allowlist, ...actionClickAllowlist]),\n cssSelectorAllowlist: allowlist,\n actionClickAllowlist,\n });\n enableBackgroundCapture(messenger);\n /* istanbul ignore next */\n messenger.setup({\n logger: config?.loggerProvider,\n ...(config?.serverZone && { endpoint: constants.AMPLITUDE_ORIGINS_MAP[config.serverZone] }),\n });\n }\n };\n\n const execute: BrowserEnrichmentPlugin['execute'] = async (event) => {\n return event;\n };\n\n const teardown = async () => {\n for (const subscription of subscriptions) {\n subscription.unsubscribe();\n }\n };\n\n return {\n name,\n type,\n setup,\n execute,\n teardown,\n };\n};\n"]}
|
|
@@ -1,10 +1,23 @@
|
|
|
1
1
|
import { ElementInteractionsOptions, ActionType, IDiagnosticsClient } from '@amplitude/analytics-core';
|
|
2
2
|
import type { DataSource } from '@amplitude/analytics-core/lib/esm/types/element-interactions';
|
|
3
|
+
import type { SelectorEngine } from '@amplitude/element-selector';
|
|
3
4
|
import type { BaseTimestampedEvent, ElementBasedTimestampedEvent, TimestampedEvent, JSONValue } from './helpers';
|
|
4
5
|
import { Hierarchy } from './typings/autocapture';
|
|
5
6
|
export declare class DataExtractor {
|
|
6
7
|
private readonly additionalMaskTextPatterns;
|
|
7
8
|
diagnosticsClient?: IDiagnosticsClient;
|
|
9
|
+
/**
|
|
10
|
+
* Optional v1 selector engine. When set AND `engine.getConfig().enabled` is
|
|
11
|
+
* true, `getElementPath()` routes through the v1 engine instead of the
|
|
12
|
+
* legacy positional `cssPath`. When the engine is absent or its `enabled`
|
|
13
|
+
* flag is false, this is a no-op and selector emission is byte-identical to
|
|
14
|
+
* pre-integration behavior.
|
|
15
|
+
*
|
|
16
|
+
* The engine is set after construction (via `setSelectorEngine`) because
|
|
17
|
+
* it depends on `config.loggerProvider` and `config.remoteConfigClient`,
|
|
18
|
+
* which only become available in the plugin's async `setup()` flow.
|
|
19
|
+
*/
|
|
20
|
+
private selectorEngine?;
|
|
8
21
|
constructor(options: ElementInteractionsOptions, context?: {
|
|
9
22
|
diagnosticsClient: IDiagnosticsClient;
|
|
10
23
|
});
|
|
@@ -16,6 +29,14 @@ export declare class DataExtractor {
|
|
|
16
29
|
replaceSensitiveString: (text: string | null) => string;
|
|
17
30
|
getHierarchy: (element: Element | null) => Hierarchy;
|
|
18
31
|
getNearestLabel: (element: Element) => string;
|
|
32
|
+
/**
|
|
33
|
+
* Attach (or replace) the v1 selector engine. Called by the autocapture
|
|
34
|
+
* plugin's `setup()` once `config.loggerProvider` / `remoteConfigClient`
|
|
35
|
+
* are available; the engine is shared (not copied) so subsequent
|
|
36
|
+
* `engine.updateConfig(...)` calls driven by remote config take effect on
|
|
37
|
+
* the very next selector emission with no additional plumbing.
|
|
38
|
+
*/
|
|
39
|
+
setSelectorEngine: (engine: SelectorEngine | undefined) => void;
|
|
19
40
|
getElementPath: (element: Element | null) => string;
|
|
20
41
|
getEventProperties: (actionType: ActionType, element: Element, dataAttributePrefix: string) => {
|
|
21
42
|
[key: string]: unknown;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"data-extractor.d.ts","sourceRoot":"","sources":["../../src/data-extractor.ts"],"names":[],"mappings":"AACA,OAAO,EACL,0BAA0B,EAC1B,UAAU,EAEV,kBAAkB,EAKnB,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,8DAA8D,CAAC;
|
|
1
|
+
{"version":3,"file":"data-extractor.d.ts","sourceRoot":"","sources":["../../src/data-extractor.ts"],"names":[],"mappings":"AACA,OAAO,EACL,0BAA0B,EAC1B,UAAU,EAEV,kBAAkB,EAKnB,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,8DAA8D,CAAC;AAC/F,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAWlE,OAAO,KAAK,EAAE,oBAAoB,EAAE,4BAA4B,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAGjH,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAGlD,qBAAa,aAAa;IACxB,OAAO,CAAC,QAAQ,CAAC,0BAA0B,CAAW;IACtD,iBAAiB,CAAC,EAAE,kBAAkB,CAAC;IAEvC;;;;;;;;;;OAUG;IACH,OAAO,CAAC,cAAc,CAAC,CAAiB;gBAE5B,OAAO,EAAE,0BAA0B,EAAE,OAAO,CAAC,EAAE;QAAE,iBAAiB,EAAE,kBAAkB,CAAA;KAAE;IAuBpG;;;;OAIG;IACH,sBAAsB,SAAU,MAAM,GAAG,IAAI,KAAG,MAAM,CAEpD;IAGF,YAAY,YAAa,OAAO,GAAG,IAAI,eA4CrC;IAEF,eAAe,YAAa,OAAO,KAAG,MAAM,CAiB1C;IAEF;;;;;;OAMG;IACH,iBAAiB,WAAY,cAAc,GAAG,SAAS,KAAG,IAAI,CAE5D;IAEF,cAAc,YAAa,OAAO,GAAG,IAAI,KAAG,MAAM,CAwBhD;IAGF,kBAAkB,eAAgB,UAAU,WAAW,OAAO,uBAAuB,MAAM;;MAmDzF;IAEF,mBAAmB,oJASjB;IAEF,4BAA4B,0GAGP,MAAM,EAAE,uBACN,MAAM,6DAmC3B;IAEF,yBAAyB,eAAgB,UAAU,kBAAkB,WAAW,+BAkB9E;IAIF,OAAO,CAAC,4BAA4B,CA2BlC;IAEF,OAAO,YAAa,OAAO,KAAG,MAAM,CAalC;IAGF,gBAAgB,YAAa,OAAO,KAAG,OAAO,MAAM,EAAE,SAAS,CAAC,CAa9D;CACH"}
|
|
@@ -8,7 +8,7 @@ var constants = tslib_1.__importStar(require("./constants"));
|
|
|
8
8
|
var helpers_1 = require("./helpers");
|
|
9
9
|
var hierarchy_1 = require("./hierarchy");
|
|
10
10
|
var actions_1 = require("./pageActions/actions");
|
|
11
|
-
var
|
|
11
|
+
var element_selector_1 = require("@amplitude/element-selector");
|
|
12
12
|
var DataExtractor = /** @class */ (function () {
|
|
13
13
|
function DataExtractor(options, context) {
|
|
14
14
|
var e_1, _a;
|
|
@@ -92,15 +92,37 @@ var DataExtractor = /** @class */ (function () {
|
|
|
92
92
|
}
|
|
93
93
|
return _this.getNearestLabel(parent);
|
|
94
94
|
};
|
|
95
|
+
/**
|
|
96
|
+
* Attach (or replace) the v1 selector engine. Called by the autocapture
|
|
97
|
+
* plugin's `setup()` once `config.loggerProvider` / `remoteConfigClient`
|
|
98
|
+
* are available; the engine is shared (not copied) so subsequent
|
|
99
|
+
* `engine.updateConfig(...)` calls driven by remote config take effect on
|
|
100
|
+
* the very next selector emission with no additional plumbing.
|
|
101
|
+
*/
|
|
102
|
+
this.setSelectorEngine = function (engine) {
|
|
103
|
+
_this.selectorEngine = engine;
|
|
104
|
+
};
|
|
95
105
|
this.getElementPath = function (element) {
|
|
96
|
-
var _a;
|
|
106
|
+
var _a, _b;
|
|
97
107
|
if (!element) {
|
|
98
108
|
return '';
|
|
99
109
|
}
|
|
100
110
|
var startTime = performance.now();
|
|
101
|
-
|
|
111
|
+
// All routing — engine vs. legacy `cssPath`, plus the strategy-chain
|
|
112
|
+
// safety net — lives inside `@amplitude/element-selector` now. We pass
|
|
113
|
+
// the engine if we have one (any value of `getConfig().enabled`; the
|
|
114
|
+
// engine itself handles the kill switch internally) and `null` when
|
|
115
|
+
// we don't (frustration-plugin code path, pre-setup, remote-config
|
|
116
|
+
// never loaded). In the null branch, `generateSelector` calls
|
|
117
|
+
// `legacyCssPath` directly, byte-identical to the pre-integration
|
|
118
|
+
// behavior.
|
|
119
|
+
//
|
|
120
|
+
// The `DEFAULT_RESOLVED_CONFIG` passed here is only consulted on the
|
|
121
|
+
// null-engine branch where it functions as a placeholder; when the
|
|
122
|
+
// engine is present, the engine's own internal config wins.
|
|
123
|
+
var elementPath = (0, element_selector_1.generateSelector)(element, (_a = _this.selectorEngine) !== null && _a !== void 0 ? _a : null, element_selector_1.DEFAULT_RESOLVED_CONFIG);
|
|
102
124
|
var endTime = performance.now();
|
|
103
|
-
(
|
|
125
|
+
(_b = _this.diagnosticsClient) === null || _b === void 0 ? void 0 : _b.recordHistogram('autocapturePlugin.getElementPath', endTime - startTime);
|
|
104
126
|
return elementPath;
|
|
105
127
|
};
|
|
106
128
|
// Returns the Amplitude event properties for the given element.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"data-extractor.js","sourceRoot":"","sources":["../../src/data-extractor.ts"],"names":[],"mappings":";;;;AAAA,0CAA0C;AAC1C,4DASmC;AAEnC,6DAAyC;AACzC,qCAQmB;AAEnB,yCAAiE;AACjE,iDAAsD;AAEtD,oDAA8C;AAE9C;IAIE,uBAAY,OAAmC,EAAE,OAAmD;;QAApG,iBAqBC;;QAED;;;;WAIG;QACH,2BAAsB,GAAG,UAAC,IAAmB;YAC3C,OAAO,IAAA,uCAAsB,EAAC,IAAI,EAAE,KAAI,CAAC,0BAA0B,CAAC,CAAC;QACvE,CAAC,CAAC;QAEF,8FAA8F;QAC9F,iBAAY,GAAG,UAAC,OAAuB;;;YACrC,IAAM,SAAS,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;YAEpC,IAA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EAAE;oBAC3B,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;iBACtB;qBAAM,IAAI,SAAS,IAAI,KAAK,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,EAAE;oBAClE,IAAI;wBACF,QAAQ,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC;qBAC/C;oBAAC,WAAM;wBACN,iCAAiC;qBAClC;iBACF;aACF;;;;;;;;;QACD,IAAI,CAAC,0BAA0B,GAAG,QAAQ,CAAC;IAC7C,CAAC;IAsRH,oBAAC;AAAD,CAAC,AA/SD,IA+SC;AA/SY,sCAAa","sourcesContent":["/* eslint-disable no-restricted-globals */\nimport {\n ElementInteractionsOptions,\n ActionType,\n getDecodeURI,\n IDiagnosticsClient,\n MASKED_TEXT_VALUE,\n TEXT_MASK_ATTRIBUTE,\n getPageTitle,\n replaceSensitiveString,\n} from '@amplitude/analytics-core';\nimport type { DataSource } from '@amplitude/analytics-core/lib/esm/types/element-interactions';\nimport * as constants from './constants';\nimport {\n removeEmptyProperties,\n extractPrefixedAttributes,\n isElementPointerCursor,\n getClosestElement,\n isElementBasedEvent,\n parseAttributesToMask,\n getCurrentPageViewId,\n} from './helpers';\nimport type { BaseTimestampedEvent, ElementBasedTimestampedEvent, TimestampedEvent, JSONValue } from './helpers';\nimport { getAncestors, getElementProperties } from './hierarchy';\nimport { getDataSource } from './pageActions/actions';\nimport { Hierarchy } from './typings/autocapture';\nimport { cssPath } from './libs/element-path';\n\nexport class DataExtractor {\n private readonly additionalMaskTextPatterns: RegExp[];\n diagnosticsClient?: IDiagnosticsClient;\n\n constructor(options: ElementInteractionsOptions, context?: { diagnosticsClient: IDiagnosticsClient }) {\n this.diagnosticsClient = context?.diagnosticsClient;\n\n const rawPatterns = options.maskTextRegex ?? [];\n\n const compiled: RegExp[] = [];\n for (const entry of rawPatterns) {\n if (compiled.length >= constants.MAX_MASK_TEXT_PATTERNS) {\n break;\n }\n if (entry instanceof RegExp) {\n compiled.push(entry);\n } else if ('pattern' in entry && typeof entry.pattern === 'string') {\n try {\n compiled.push(new RegExp(entry.pattern, 'i'));\n } catch {\n // ignore invalid pattern strings\n }\n }\n }\n this.additionalMaskTextPatterns = compiled;\n }\n\n /**\n * Wrapper method to replace sensitive strings using the helper function\n * @param text - The text to search for sensitive data\n * @returns The text with sensitive data replaced by masked text\n */\n replaceSensitiveString = (text: string | null): string => {\n return replaceSensitiveString(text, this.additionalMaskTextPatterns);\n };\n\n // Get the DOM hierarchy of the element, starting from the target element to the root element.\n getHierarchy = (element: Element | null): Hierarchy => {\n const startTime = performance.now();\n\n let hierarchy: Hierarchy = [];\n if (!element) {\n return [];\n }\n\n // Get list of ancestors including itself and get properties at each level in the hierarchy\n const ancestors = getAncestors(element);\n\n // Build attributes to mask map\n const elementToAttributesToMaskMap = new Map<Element, Set<string>>();\n\n for (let i = ancestors.length - 1; i >= 0; i--) {\n const node = ancestors[i];\n if (node) {\n const attributesToMask = parseAttributesToMask(node.getAttribute(constants.DATA_AMP_MASK_ATTRIBUTES));\n const ancestorAttributesToMask =\n i === ancestors.length - 1 ? [] : elementToAttributesToMaskMap.get(ancestors[i + 1]) ?? new Set<string>();\n const combinedAttributesToMask = new Set([...ancestorAttributesToMask, ...attributesToMask]);\n elementToAttributesToMaskMap.set(node, combinedAttributesToMask);\n }\n }\n\n hierarchy = ancestors.map((el) =>\n getElementProperties(el, elementToAttributesToMaskMap.get(el) ?? new Set<string>()),\n );\n\n // Search for and mask any sensitive attribute values\n for (const hierarchyNode of hierarchy) {\n if (hierarchyNode?.attrs) {\n Object.entries(hierarchyNode.attrs).forEach(([key, value]) => {\n if (hierarchyNode.attrs) {\n hierarchyNode.attrs[key] = this.replaceSensitiveString(value);\n }\n });\n }\n }\n\n const endTime = performance.now();\n this.diagnosticsClient?.recordHistogram('autocapturePlugin.getHierarchy', endTime - startTime);\n\n return hierarchy;\n };\n\n getNearestLabel = (element: Element): string => {\n const parent = element.parentElement;\n if (!parent) {\n return '';\n }\n let labelElement: Element | null;\n try {\n labelElement = parent.querySelector(':scope>span,h1,h2,h3,h4,h5,h6');\n } catch {\n /* istanbul ignore next */\n labelElement = null;\n }\n if (labelElement) {\n /* istanbul ignore next */\n return this.getText(labelElement);\n }\n return this.getNearestLabel(parent);\n };\n\n getElementPath = (element: Element | null): string => {\n if (!element) {\n return '';\n }\n const startTime = performance.now();\n\n const elementPath = cssPath(element);\n\n const endTime = performance.now();\n this.diagnosticsClient?.recordHistogram('autocapturePlugin.getElementPath', endTime - startTime);\n\n return elementPath;\n };\n\n // Returns the Amplitude event properties for the given element.\n getEventProperties = (actionType: ActionType, element: Element, dataAttributePrefix: string) => {\n /* istanbul ignore next */\n const tag = element?.tagName?.toLowerCase?.();\n /* istanbul ignore next */\n const rect =\n typeof element.getBoundingClientRect === 'function' ? element.getBoundingClientRect() : { left: null, top: null };\n\n const hierarchy = this.getHierarchy(element);\n const currentElementAttributes = hierarchy[0]?.attrs;\n const nearestLabel = this.getNearestLabel(element);\n const attributes = extractPrefixedAttributes(currentElementAttributes ?? {}, dataAttributePrefix);\n\n /* istanbul ignore next */\n const properties: Record<string, any> = {\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_HIERARCHY]: hierarchy,\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_TAG]: tag,\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_TEXT]: this.getText(element),\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_POSITION_LEFT]: rect.left == null ? null : Math.round(rect.left),\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_POSITION_TOP]: rect.top == null ? null : Math.round(rect.top),\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_ATTRIBUTES]: attributes,\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_PATH]: this.getElementPath(element),\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_PARENT_LABEL]: nearestLabel,\n [constants.AMPLITUDE_EVENT_PROP_PAGE_URL]: getDecodeURI(window.location.href.split('?')[0]),\n [constants.AMPLITUDE_EVENT_PROP_PAGE_TITLE]: (\n getPageTitle as (parseTitleFunction: (title: string) => string) => string\n )(this.replaceSensitiveString),\n [constants.AMPLITUDE_EVENT_PROP_VIEWPORT_HEIGHT]: window.innerHeight,\n [constants.AMPLITUDE_EVENT_PROP_VIEWPORT_WIDTH]: window.innerWidth,\n };\n\n const pageViewId = getCurrentPageViewId();\n /* istanbul ignore next */\n if (pageViewId) {\n /* istanbul ignore next */\n properties[constants.AMPLITUDE_EVENT_PROP_PAGE_VIEW_ID] = pageViewId;\n }\n\n // id is never masked, so always include it\n properties[constants.AMPLITUDE_EVENT_PROP_ELEMENT_ID] = element.getAttribute('id') || '';\n\n // class is never masked, so always include it\n properties[constants.AMPLITUDE_EVENT_PROP_ELEMENT_CLASS] = element.getAttribute('class');\n\n properties[constants.AMPLITUDE_EVENT_PROP_ELEMENT_ARIA_LABEL] = currentElementAttributes?.['aria-label'];\n\n if (tag === 'a' && actionType === 'click' && element instanceof HTMLAnchorElement) {\n const href = element.href.substring(0, constants.MAX_ATTRIBUTE_LENGTH);\n properties[constants.AMPLITUDE_EVENT_PROP_ELEMENT_HREF] = this.replaceSensitiveString(href); // we don't use hierarchy here because we don't want href value to be changed\n }\n\n return removeEmptyProperties(properties);\n };\n\n addTypeAndTimestamp = <T>(\n event: T,\n type: BaseTimestampedEvent<T>['type'] | ElementBasedTimestampedEvent<T>['type'],\n ): BaseTimestampedEvent<T> | ElementBasedTimestampedEvent<T> => {\n return {\n event,\n timestamp: Date.now(),\n type,\n };\n };\n\n addAdditionalEventProperties = <T>(\n event: T,\n type: TimestampedEvent<T>['type'],\n selectorAllowlist: string[],\n dataAttributePrefix: string,\n // capture the event if the cursor is a \"pointer\" when this element is clicked on\n // reason: a \"pointer\" cursor indicates that an element should be interactable\n // regardless of the element's tag name\n isCapturingCursorPointer = false,\n ): TimestampedEvent<T> | ElementBasedTimestampedEvent<T> => {\n const baseEvent = this.addTypeAndTimestamp(event, type);\n\n if (isElementBasedEvent(baseEvent) && baseEvent.event.target !== null) {\n if (isCapturingCursorPointer) {\n const isCursorPointer = isElementPointerCursor(baseEvent.event.target as Element, baseEvent.type);\n if (isCursorPointer) {\n baseEvent.closestTrackedAncestor = baseEvent.event.target as HTMLElement;\n baseEvent.targetElementProperties = this.getEventProperties(\n baseEvent.type,\n baseEvent.closestTrackedAncestor,\n dataAttributePrefix,\n );\n return baseEvent;\n }\n }\n // Retrieve additional event properties from the target element\n const closestTrackedAncestor = getClosestElement(baseEvent.event.target as HTMLElement, selectorAllowlist);\n if (closestTrackedAncestor) {\n baseEvent.closestTrackedAncestor = closestTrackedAncestor;\n baseEvent.targetElementProperties = this.getEventProperties(\n baseEvent.type,\n closestTrackedAncestor,\n dataAttributePrefix,\n );\n }\n return baseEvent;\n }\n\n return baseEvent;\n };\n\n extractDataFromDataSource = (dataSource: DataSource, contextElement: HTMLElement) => {\n // Extract from DOM Element\n if (dataSource.sourceType === 'DOM_ELEMENT') {\n const sourceElement = getDataSource(dataSource, contextElement);\n if (!sourceElement) {\n return undefined;\n }\n\n if (dataSource.elementExtractType === 'TEXT') {\n return this.getText(sourceElement);\n } else if (dataSource.elementExtractType === 'ATTRIBUTE' && dataSource.attribute) {\n return sourceElement.getAttribute(dataSource.attribute);\n }\n return undefined;\n }\n\n // TODO: Extract from other source types\n return undefined;\n };\n\n // Traverse text content without cloning DOM nodes, which avoids media/network side effects\n // from recreating nested elements such as <video>, <audio>, or <img>.\n private getTextWithMaskedDescendants = (element: Element): string => {\n const maskedSelector = `[${TEXT_MASK_ATTRIBUTE}], [contenteditable]`;\n // Fast path: if no masked descendants exist, rely on native text extraction.\n if (!element.querySelector(maskedSelector)) {\n return (element as HTMLElement).innerText;\n }\n\n let output = '';\n const childNodes = Array.from(element.childNodes);\n for (const childNode of childNodes) {\n if (childNode.nodeType === Node.TEXT_NODE) {\n output += childNode.textContent || '';\n continue;\n }\n\n if (!(childNode instanceof Element)) {\n continue;\n }\n\n // Replace entire masked/contenteditable subtrees with the mask token.\n if (childNode.hasAttribute(TEXT_MASK_ATTRIBUTE) || childNode.hasAttribute('contenteditable')) {\n output += MASKED_TEXT_VALUE;\n continue;\n }\n output += this.getTextWithMaskedDescendants(childNode);\n }\n return output;\n };\n\n getText = (element: Element): string => {\n // Check if element or any parent has data-amp-mask attribute\n const hasMaskAttribute = element.closest(`[${TEXT_MASK_ATTRIBUTE}]`) !== null;\n if (hasMaskAttribute) {\n return MASKED_TEXT_VALUE;\n }\n let output = '';\n if (!element.querySelector(`[${TEXT_MASK_ATTRIBUTE}], [contenteditable]`)) {\n output = (element as HTMLElement).innerText || '';\n } else {\n output = this.getTextWithMaskedDescendants(element);\n }\n return this.replaceSensitiveString(output.substring(0, 255)).replace(/\\s+/g, ' ').trim();\n };\n\n // Returns the element properties for the given element in Visual Labeling.\n getEventTagProps = (element: Element): Record<string, JSONValue> => {\n if (!element) {\n return {};\n }\n /* istanbul ignore next */\n const tag = element?.tagName?.toLowerCase?.();\n\n const properties = {\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_TAG]: tag,\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_TEXT]: this.getText(element),\n [constants.AMPLITUDE_EVENT_PROP_PAGE_URL]: window.location.href.split('?')[0],\n };\n return removeEmptyProperties(properties) as Record<string, JSONValue>;\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"data-extractor.js","sourceRoot":"","sources":["../../src/data-extractor.ts"],"names":[],"mappings":";;;;AAAA,0CAA0C;AAC1C,4DASmC;AAGnC,6DAAyC;AACzC,qCAQmB;AAEnB,yCAAiE;AACjE,iDAAsD;AAEtD,gEAAwF;AAExF;IAiBE,uBAAY,OAAmC,EAAE,OAAmD;;QAApG,iBAqBC;;QAED;;;;WAIG;QACH,2BAAsB,GAAG,UAAC,IAAmB;YAC3C,OAAO,IAAA,uCAAsB,EAAC,IAAI,EAAE,KAAI,CAAC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CAAC,CAAC,CAAC;mBAC9E,CAAC;YACF,OAAO,IAAA,+BAAqB,EAAC,UAAU,CAA8B,CAAC;QACxE,CAAC,CAAC;QAhUA,IAAI,CAAC,iBAAiB,GAAG,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,iBAAiB,CAAC;QAEpD,IAAM,WAAW,GAAG,MAAA,OAAO,CAAC,aAAa,mCAAI,EAAE,CAAC;QAEhD,IAAM,QAAQ,GAAa,EAAE,CAAC;;YAC9B,KAAoB,IAAA,gBAAA,iBAAA,WAAW,CAAA,wCAAA,iEAAE;gBAA5B,IAAM,KAAK,wBAAA;gBACd,IAAI,QAAQ,CAAC,MAAM,IAAI,SAAS,CAAC,sBAAsB,EAAE;oBACvD,MAAM;iBACP;gBACD,IAAI,KAAK,YAAY,MAAM,EAAE;oBAC3B,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;iBACtB;qBAAM,IAAI,SAAS,IAAI,KAAK,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,EAAE;oBAClE,IAAI;wBACF,QAAQ,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC;qBAC/C;oBAAC,WAAM;wBACN,iCAAiC;qBAClC;iBACF;aACF;;;;;;;;;QACD,IAAI,CAAC,0BAA0B,GAAG,QAAQ,CAAC;IAC7C,CAAC;IA6SH,oBAAC;AAAD,CAAC,AAnVD,IAmVC;AAnVY,sCAAa","sourcesContent":["/* eslint-disable no-restricted-globals */\nimport {\n ElementInteractionsOptions,\n ActionType,\n getDecodeURI,\n IDiagnosticsClient,\n MASKED_TEXT_VALUE,\n TEXT_MASK_ATTRIBUTE,\n getPageTitle,\n replaceSensitiveString,\n} from '@amplitude/analytics-core';\nimport type { DataSource } from '@amplitude/analytics-core/lib/esm/types/element-interactions';\nimport type { SelectorEngine } from '@amplitude/element-selector';\nimport * as constants from './constants';\nimport {\n removeEmptyProperties,\n extractPrefixedAttributes,\n isElementPointerCursor,\n getClosestElement,\n isElementBasedEvent,\n parseAttributesToMask,\n getCurrentPageViewId,\n} from './helpers';\nimport type { BaseTimestampedEvent, ElementBasedTimestampedEvent, TimestampedEvent, JSONValue } from './helpers';\nimport { getAncestors, getElementProperties } from './hierarchy';\nimport { getDataSource } from './pageActions/actions';\nimport { Hierarchy } from './typings/autocapture';\nimport { DEFAULT_RESOLVED_CONFIG, generateSelector } from '@amplitude/element-selector';\n\nexport class DataExtractor {\n private readonly additionalMaskTextPatterns: RegExp[];\n diagnosticsClient?: IDiagnosticsClient;\n\n /**\n * Optional v1 selector engine. When set AND `engine.getConfig().enabled` is\n * true, `getElementPath()` routes through the v1 engine instead of the\n * legacy positional `cssPath`. When the engine is absent or its `enabled`\n * flag is false, this is a no-op and selector emission is byte-identical to\n * pre-integration behavior.\n *\n * The engine is set after construction (via `setSelectorEngine`) because\n * it depends on `config.loggerProvider` and `config.remoteConfigClient`,\n * which only become available in the plugin's async `setup()` flow.\n */\n private selectorEngine?: SelectorEngine;\n\n constructor(options: ElementInteractionsOptions, context?: { diagnosticsClient: IDiagnosticsClient }) {\n this.diagnosticsClient = context?.diagnosticsClient;\n\n const rawPatterns = options.maskTextRegex ?? [];\n\n const compiled: RegExp[] = [];\n for (const entry of rawPatterns) {\n if (compiled.length >= constants.MAX_MASK_TEXT_PATTERNS) {\n break;\n }\n if (entry instanceof RegExp) {\n compiled.push(entry);\n } else if ('pattern' in entry && typeof entry.pattern === 'string') {\n try {\n compiled.push(new RegExp(entry.pattern, 'i'));\n } catch {\n // ignore invalid pattern strings\n }\n }\n }\n this.additionalMaskTextPatterns = compiled;\n }\n\n /**\n * Wrapper method to replace sensitive strings using the helper function\n * @param text - The text to search for sensitive data\n * @returns The text with sensitive data replaced by masked text\n */\n replaceSensitiveString = (text: string | null): string => {\n return replaceSensitiveString(text, this.additionalMaskTextPatterns);\n };\n\n // Get the DOM hierarchy of the element, starting from the target element to the root element.\n getHierarchy = (element: Element | null): Hierarchy => {\n const startTime = performance.now();\n\n let hierarchy: Hierarchy = [];\n if (!element) {\n return [];\n }\n\n // Get list of ancestors including itself and get properties at each level in the hierarchy\n const ancestors = getAncestors(element);\n\n // Build attributes to mask map\n const elementToAttributesToMaskMap = new Map<Element, Set<string>>();\n\n for (let i = ancestors.length - 1; i >= 0; i--) {\n const node = ancestors[i];\n if (node) {\n const attributesToMask = parseAttributesToMask(node.getAttribute(constants.DATA_AMP_MASK_ATTRIBUTES));\n const ancestorAttributesToMask =\n i === ancestors.length - 1 ? [] : elementToAttributesToMaskMap.get(ancestors[i + 1]) ?? new Set<string>();\n const combinedAttributesToMask = new Set([...ancestorAttributesToMask, ...attributesToMask]);\n elementToAttributesToMaskMap.set(node, combinedAttributesToMask);\n }\n }\n\n hierarchy = ancestors.map((el) =>\n getElementProperties(el, elementToAttributesToMaskMap.get(el) ?? new Set<string>()),\n );\n\n // Search for and mask any sensitive attribute values\n for (const hierarchyNode of hierarchy) {\n if (hierarchyNode?.attrs) {\n Object.entries(hierarchyNode.attrs).forEach(([key, value]) => {\n if (hierarchyNode.attrs) {\n hierarchyNode.attrs[key] = this.replaceSensitiveString(value);\n }\n });\n }\n }\n\n const endTime = performance.now();\n this.diagnosticsClient?.recordHistogram('autocapturePlugin.getHierarchy', endTime - startTime);\n\n return hierarchy;\n };\n\n getNearestLabel = (element: Element): string => {\n const parent = element.parentElement;\n if (!parent) {\n return '';\n }\n let labelElement: Element | null;\n try {\n labelElement = parent.querySelector(':scope>span,h1,h2,h3,h4,h5,h6');\n } catch {\n /* istanbul ignore next */\n labelElement = null;\n }\n if (labelElement) {\n /* istanbul ignore next */\n return this.getText(labelElement);\n }\n return this.getNearestLabel(parent);\n };\n\n /**\n * Attach (or replace) the v1 selector engine. Called by the autocapture\n * plugin's `setup()` once `config.loggerProvider` / `remoteConfigClient`\n * are available; the engine is shared (not copied) so subsequent\n * `engine.updateConfig(...)` calls driven by remote config take effect on\n * the very next selector emission with no additional plumbing.\n */\n setSelectorEngine = (engine: SelectorEngine | undefined): void => {\n this.selectorEngine = engine;\n };\n\n getElementPath = (element: Element | null): string => {\n if (!element) {\n return '';\n }\n const startTime = performance.now();\n\n // All routing — engine vs. legacy `cssPath`, plus the strategy-chain\n // safety net — lives inside `@amplitude/element-selector` now. We pass\n // the engine if we have one (any value of `getConfig().enabled`; the\n // engine itself handles the kill switch internally) and `null` when\n // we don't (frustration-plugin code path, pre-setup, remote-config\n // never loaded). In the null branch, `generateSelector` calls\n // `legacyCssPath` directly, byte-identical to the pre-integration\n // behavior.\n //\n // The `DEFAULT_RESOLVED_CONFIG` passed here is only consulted on the\n // null-engine branch where it functions as a placeholder; when the\n // engine is present, the engine's own internal config wins.\n const elementPath = generateSelector(element, this.selectorEngine ?? null, DEFAULT_RESOLVED_CONFIG);\n\n const endTime = performance.now();\n this.diagnosticsClient?.recordHistogram('autocapturePlugin.getElementPath', endTime - startTime);\n\n return elementPath;\n };\n\n // Returns the Amplitude event properties for the given element.\n getEventProperties = (actionType: ActionType, element: Element, dataAttributePrefix: string) => {\n /* istanbul ignore next */\n const tag = element?.tagName?.toLowerCase?.();\n /* istanbul ignore next */\n const rect =\n typeof element.getBoundingClientRect === 'function' ? element.getBoundingClientRect() : { left: null, top: null };\n\n const hierarchy = this.getHierarchy(element);\n const currentElementAttributes = hierarchy[0]?.attrs;\n const nearestLabel = this.getNearestLabel(element);\n const attributes = extractPrefixedAttributes(currentElementAttributes ?? {}, dataAttributePrefix);\n\n /* istanbul ignore next */\n const properties: Record<string, any> = {\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_HIERARCHY]: hierarchy,\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_TAG]: tag,\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_TEXT]: this.getText(element),\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_POSITION_LEFT]: rect.left == null ? null : Math.round(rect.left),\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_POSITION_TOP]: rect.top == null ? null : Math.round(rect.top),\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_ATTRIBUTES]: attributes,\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_PATH]: this.getElementPath(element),\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_PARENT_LABEL]: nearestLabel,\n [constants.AMPLITUDE_EVENT_PROP_PAGE_URL]: getDecodeURI(window.location.href.split('?')[0]),\n [constants.AMPLITUDE_EVENT_PROP_PAGE_TITLE]: (\n getPageTitle as (parseTitleFunction: (title: string) => string) => string\n )(this.replaceSensitiveString),\n [constants.AMPLITUDE_EVENT_PROP_VIEWPORT_HEIGHT]: window.innerHeight,\n [constants.AMPLITUDE_EVENT_PROP_VIEWPORT_WIDTH]: window.innerWidth,\n };\n\n const pageViewId = getCurrentPageViewId();\n /* istanbul ignore next */\n if (pageViewId) {\n /* istanbul ignore next */\n properties[constants.AMPLITUDE_EVENT_PROP_PAGE_VIEW_ID] = pageViewId;\n }\n\n // id is never masked, so always include it\n properties[constants.AMPLITUDE_EVENT_PROP_ELEMENT_ID] = element.getAttribute('id') || '';\n\n // class is never masked, so always include it\n properties[constants.AMPLITUDE_EVENT_PROP_ELEMENT_CLASS] = element.getAttribute('class');\n\n properties[constants.AMPLITUDE_EVENT_PROP_ELEMENT_ARIA_LABEL] = currentElementAttributes?.['aria-label'];\n\n if (tag === 'a' && actionType === 'click' && element instanceof HTMLAnchorElement) {\n const href = element.href.substring(0, constants.MAX_ATTRIBUTE_LENGTH);\n properties[constants.AMPLITUDE_EVENT_PROP_ELEMENT_HREF] = this.replaceSensitiveString(href); // we don't use hierarchy here because we don't want href value to be changed\n }\n\n return removeEmptyProperties(properties);\n };\n\n addTypeAndTimestamp = <T>(\n event: T,\n type: BaseTimestampedEvent<T>['type'] | ElementBasedTimestampedEvent<T>['type'],\n ): BaseTimestampedEvent<T> | ElementBasedTimestampedEvent<T> => {\n return {\n event,\n timestamp: Date.now(),\n type,\n };\n };\n\n addAdditionalEventProperties = <T>(\n event: T,\n type: TimestampedEvent<T>['type'],\n selectorAllowlist: string[],\n dataAttributePrefix: string,\n // capture the event if the cursor is a \"pointer\" when this element is clicked on\n // reason: a \"pointer\" cursor indicates that an element should be interactable\n // regardless of the element's tag name\n isCapturingCursorPointer = false,\n ): TimestampedEvent<T> | ElementBasedTimestampedEvent<T> => {\n const baseEvent = this.addTypeAndTimestamp(event, type);\n\n if (isElementBasedEvent(baseEvent) && baseEvent.event.target !== null) {\n if (isCapturingCursorPointer) {\n const isCursorPointer = isElementPointerCursor(baseEvent.event.target as Element, baseEvent.type);\n if (isCursorPointer) {\n baseEvent.closestTrackedAncestor = baseEvent.event.target as HTMLElement;\n baseEvent.targetElementProperties = this.getEventProperties(\n baseEvent.type,\n baseEvent.closestTrackedAncestor,\n dataAttributePrefix,\n );\n return baseEvent;\n }\n }\n // Retrieve additional event properties from the target element\n const closestTrackedAncestor = getClosestElement(baseEvent.event.target as HTMLElement, selectorAllowlist);\n if (closestTrackedAncestor) {\n baseEvent.closestTrackedAncestor = closestTrackedAncestor;\n baseEvent.targetElementProperties = this.getEventProperties(\n baseEvent.type,\n closestTrackedAncestor,\n dataAttributePrefix,\n );\n }\n return baseEvent;\n }\n\n return baseEvent;\n };\n\n extractDataFromDataSource = (dataSource: DataSource, contextElement: HTMLElement) => {\n // Extract from DOM Element\n if (dataSource.sourceType === 'DOM_ELEMENT') {\n const sourceElement = getDataSource(dataSource, contextElement);\n if (!sourceElement) {\n return undefined;\n }\n\n if (dataSource.elementExtractType === 'TEXT') {\n return this.getText(sourceElement);\n } else if (dataSource.elementExtractType === 'ATTRIBUTE' && dataSource.attribute) {\n return sourceElement.getAttribute(dataSource.attribute);\n }\n return undefined;\n }\n\n // TODO: Extract from other source types\n return undefined;\n };\n\n // Traverse text content without cloning DOM nodes, which avoids media/network side effects\n // from recreating nested elements such as <video>, <audio>, or <img>.\n private getTextWithMaskedDescendants = (element: Element): string => {\n const maskedSelector = `[${TEXT_MASK_ATTRIBUTE}], [contenteditable]`;\n // Fast path: if no masked descendants exist, rely on native text extraction.\n if (!element.querySelector(maskedSelector)) {\n return (element as HTMLElement).innerText;\n }\n\n let output = '';\n const childNodes = Array.from(element.childNodes);\n for (const childNode of childNodes) {\n if (childNode.nodeType === Node.TEXT_NODE) {\n output += childNode.textContent || '';\n continue;\n }\n\n if (!(childNode instanceof Element)) {\n continue;\n }\n\n // Replace entire masked/contenteditable subtrees with the mask token.\n if (childNode.hasAttribute(TEXT_MASK_ATTRIBUTE) || childNode.hasAttribute('contenteditable')) {\n output += MASKED_TEXT_VALUE;\n continue;\n }\n output += this.getTextWithMaskedDescendants(childNode);\n }\n return output;\n };\n\n getText = (element: Element): string => {\n // Check if element or any parent has data-amp-mask attribute\n const hasMaskAttribute = element.closest(`[${TEXT_MASK_ATTRIBUTE}]`) !== null;\n if (hasMaskAttribute) {\n return MASKED_TEXT_VALUE;\n }\n let output = '';\n if (!element.querySelector(`[${TEXT_MASK_ATTRIBUTE}], [contenteditable]`)) {\n output = (element as HTMLElement).innerText || '';\n } else {\n output = this.getTextWithMaskedDescendants(element);\n }\n return this.replaceSensitiveString(output.substring(0, 255)).replace(/\\s+/g, ' ').trim();\n };\n\n // Returns the element properties for the given element in Visual Labeling.\n getEventTagProps = (element: Element): Record<string, JSONValue> => {\n if (!element) {\n return {};\n }\n /* istanbul ignore next */\n const tag = element?.tagName?.toLowerCase?.();\n\n const properties = {\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_TAG]: tag,\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_TEXT]: this.getText(element),\n [constants.AMPLITUDE_EVENT_PROP_PAGE_URL]: window.location.href.split('?')[0],\n };\n return removeEmptyProperties(properties) as Record<string, JSONValue>;\n };\n}\n"]}
|
|
@@ -1,2 +1,24 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Backward-compat re-export.
|
|
3
|
+
*
|
|
4
|
+
* The Chromium-DevTools-derived `cssPath` walker that lived here for years
|
|
5
|
+
* has moved to `@amplitude/element-selector` as `legacyCssPath`. That's now
|
|
6
|
+
* the canonical home — the SDK and the dashboard both import from there,
|
|
7
|
+
* so the two can never drift again.
|
|
8
|
+
*
|
|
9
|
+
* This file stays around as a thin re-export so:
|
|
10
|
+
*
|
|
11
|
+
* - any third-party consumer that historically deep-imported `cssPath` from
|
|
12
|
+
* `@amplitude/plugin-autocapture-browser/src/libs/element-path` continues
|
|
13
|
+
* to work without code changes;
|
|
14
|
+
* - the autocapture plugin's own internals don't have to special-case the
|
|
15
|
+
* rename mid-PR (although `data-extractor` no longer uses it — all
|
|
16
|
+
* routing happens via `generateSelector` from the package).
|
|
17
|
+
*
|
|
18
|
+
* Slated for deletion in a future major once we've audited and confirmed no
|
|
19
|
+
* external imports remain.
|
|
20
|
+
*
|
|
21
|
+
* @deprecated Import `legacyCssPath` from `@amplitude/element-selector` directly.
|
|
22
|
+
*/
|
|
23
|
+
export { legacyCssPath as cssPath } from '@amplitude/element-selector';
|
|
2
24
|
//# sourceMappingURL=element-path.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"element-path.d.ts","sourceRoot":"","sources":["../../../src/libs/element-path.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"element-path.d.ts","sourceRoot":"","sources":["../../../src/libs/element-path.ts"],"names":[],"mappings":"AAKA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAE,aAAa,IAAI,OAAO,EAAE,MAAM,6BAA6B,CAAC"}
|