@amplitude/plugin-autocapture-browser 1.0.1 → 1.0.2
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/track-action-click.d.ts +1 -2
- package/lib/cjs/autocapture/track-action-click.d.ts.map +1 -1
- package/lib/cjs/autocapture/track-action-click.js.map +1 -1
- package/lib/cjs/autocapture/track-change.d.ts +1 -2
- package/lib/cjs/autocapture/track-change.d.ts.map +1 -1
- package/lib/cjs/autocapture/track-change.js.map +1 -1
- package/lib/cjs/autocapture-plugin.d.ts +3 -52
- package/lib/cjs/autocapture-plugin.d.ts.map +1 -1
- package/lib/cjs/autocapture-plugin.js +12 -30
- package/lib/cjs/autocapture-plugin.js.map +1 -1
- package/lib/cjs/helpers.d.ts +3 -4
- package/lib/cjs/helpers.d.ts.map +1 -1
- package/lib/cjs/helpers.js +14 -6
- package/lib/cjs/helpers.js.map +1 -1
- package/lib/cjs/hierarchy.js +6 -6
- package/lib/cjs/hierarchy.js.map +1 -1
- package/lib/cjs/index.d.ts +2 -2
- package/lib/cjs/index.d.ts.map +1 -1
- package/lib/cjs/index.js +1 -3
- package/lib/cjs/index.js.map +1 -1
- package/lib/cjs/libs/messenger.d.ts +1 -6
- package/lib/cjs/libs/messenger.d.ts.map +1 -1
- package/lib/cjs/libs/messenger.js.map +1 -1
- package/lib/cjs/typings/autocapture.d.ts +0 -1
- package/lib/cjs/typings/autocapture.d.ts.map +1 -1
- package/lib/cjs/typings/autocapture.js.map +1 -1
- package/lib/cjs/version.d.ts +1 -1
- package/lib/cjs/version.js +1 -1
- package/lib/cjs/version.js.map +1 -1
- package/lib/esm/autocapture/track-action-click.d.ts +1 -2
- package/lib/esm/autocapture/track-action-click.d.ts.map +1 -1
- package/lib/esm/autocapture/track-action-click.js.map +1 -1
- package/lib/esm/autocapture/track-change.d.ts +1 -2
- package/lib/esm/autocapture/track-change.d.ts.map +1 -1
- package/lib/esm/autocapture/track-change.js.map +1 -1
- package/lib/esm/autocapture-plugin.d.ts +3 -52
- package/lib/esm/autocapture-plugin.d.ts.map +1 -1
- package/lib/esm/autocapture-plugin.js +8 -26
- package/lib/esm/autocapture-plugin.js.map +1 -1
- package/lib/esm/helpers.d.ts +3 -4
- package/lib/esm/helpers.d.ts.map +1 -1
- package/lib/esm/helpers.js +14 -6
- package/lib/esm/helpers.js.map +1 -1
- package/lib/esm/hierarchy.js +6 -6
- package/lib/esm/hierarchy.js.map +1 -1
- package/lib/esm/index.d.ts +2 -2
- package/lib/esm/index.d.ts.map +1 -1
- package/lib/esm/index.js +1 -1
- package/lib/esm/index.js.map +1 -1
- package/lib/esm/libs/messenger.d.ts +1 -6
- package/lib/esm/libs/messenger.d.ts.map +1 -1
- package/lib/esm/libs/messenger.js.map +1 -1
- package/lib/esm/typings/autocapture.d.ts +0 -1
- package/lib/esm/typings/autocapture.d.ts.map +1 -1
- package/lib/esm/typings/autocapture.js.map +1 -1
- package/lib/esm/version.d.ts +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.umd.js +1 -1
- package/lib/scripts/amplitude-min.umd.js.gz +0 -0
- package/lib/scripts/autocapture/track-action-click.d.ts +1 -2
- package/lib/scripts/autocapture/track-action-click.d.ts.map +1 -1
- package/lib/scripts/autocapture/track-change.d.ts +1 -2
- package/lib/scripts/autocapture/track-change.d.ts.map +1 -1
- package/lib/scripts/autocapture-plugin.d.ts +3 -52
- package/lib/scripts/autocapture-plugin.d.ts.map +1 -1
- package/lib/scripts/helpers.d.ts +3 -4
- package/lib/scripts/helpers.d.ts.map +1 -1
- package/lib/scripts/index.d.ts +2 -2
- package/lib/scripts/index.d.ts.map +1 -1
- package/lib/scripts/libs/messenger.d.ts +1 -6
- package/lib/scripts/libs/messenger.d.ts.map +1 -1
- package/lib/scripts/typings/autocapture.d.ts +0 -1
- package/lib/scripts/typings/autocapture.d.ts.map +1 -1
- package/lib/scripts/version.d.ts +1 -1
- package/package.json +2 -2
package/lib/esm/helpers.js
CHANGED
|
@@ -19,7 +19,7 @@ export var createShouldTrackEvent = function (autocaptureOptions, allowlist) {
|
|
|
19
19
|
return false;
|
|
20
20
|
}
|
|
21
21
|
/* istanbul ignore next */
|
|
22
|
-
var elementType = (element === null || element === void 0 ? void 0 : element.type) || '';
|
|
22
|
+
var elementType = String(element === null || element === void 0 ? void 0 : element.getAttribute('type')) || '';
|
|
23
23
|
if (typeof elementType === 'string') {
|
|
24
24
|
switch (elementType.toLowerCase()) {
|
|
25
25
|
case 'hidden':
|
|
@@ -125,11 +125,13 @@ export var getSelector = function (element, logger) {
|
|
|
125
125
|
if (tag) {
|
|
126
126
|
selector = tag;
|
|
127
127
|
}
|
|
128
|
-
|
|
129
|
-
|
|
128
|
+
var id = element.getAttribute('id');
|
|
129
|
+
var className = element.getAttribute('class');
|
|
130
|
+
if (id) {
|
|
131
|
+
selector = "#".concat(id);
|
|
130
132
|
}
|
|
131
|
-
else if (
|
|
132
|
-
var classes =
|
|
133
|
+
else if (className) {
|
|
134
|
+
var classes = className
|
|
133
135
|
.split(' ')
|
|
134
136
|
.filter(function (name) { return name !== constants.AMPLITUDE_VISUAL_TAGGING_HIGHLIGHT_CLASS; })
|
|
135
137
|
.join('.');
|
|
@@ -182,7 +184,13 @@ export var getNearestLabel = function (element) {
|
|
|
182
184
|
if (!parent) {
|
|
183
185
|
return '';
|
|
184
186
|
}
|
|
185
|
-
var labelElement
|
|
187
|
+
var labelElement;
|
|
188
|
+
try {
|
|
189
|
+
labelElement = parent.querySelector(':scope>span,h1,h2,h3,h4,h5,h6');
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
labelElement = null;
|
|
193
|
+
}
|
|
186
194
|
if (labelElement) {
|
|
187
195
|
/* istanbul ignore next */
|
|
188
196
|
var labelText = labelElement.textContent || '';
|
package/lib/esm/helpers.js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AC;SACf;IACH,CAAC,CAAC,CAAC;AACL,CAAC,CAAC;AAEF,MAAM,UAAU,gBAAgB;IAC9B,OAAO,UAAG,IAAI,CAAC,GAAG,EAAE,cAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAE,CAAC;AACpE,CAAC;AAED,MAAM,CAAC,IAAM,2BAA2B,GAAG,UAAC,KAAsD;IAChG,+CAA+C;IAC/C,sEAAsE;IACtE,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,sBAAsB,EAAE;QAChE,OAAO,KAAK,CAAC;KACd;IAED,OAAO,IAAI,CAAC;AACd,CAAC,CAAC","sourcesContent":["/* eslint-disable no-restricted-globals */\nimport { finder } from './libs/finder';\nimport * as constants from './constants';\nimport { Logger } from '@amplitude/analytics-types';\nimport { AutocaptureOptions, ElementBasedEvent, ElementBasedTimestampedEvent } from './autocapture-plugin';\nimport { ActionType } from './typings/autocapture';\n\nexport type JSONValue = string | number | boolean | null | { [x: string]: JSONValue } | Array<JSONValue>;\n\nconst SENSITIVE_TAGS = ['input', 'select', 'textarea'];\n\nexport type shouldTrackEvent = (actionType: ActionType, element: Element) => boolean;\n\nexport const createShouldTrackEvent = (\n autocaptureOptions: AutocaptureOptions,\n allowlist: string[], // this can be any type of css selector allow list\n): shouldTrackEvent => {\n return (actionType: ActionType, element: Element) => {\n const { pageUrlAllowlist, shouldTrackEventResolver } = autocaptureOptions;\n\n /* istanbul ignore next */\n const tag = element?.tagName?.toLowerCase?.();\n // window, document, and Text nodes have no tag\n if (!tag) {\n return false;\n }\n\n if (shouldTrackEventResolver) {\n return shouldTrackEventResolver(actionType, element);\n }\n\n if (!isPageUrlAllowed(window.location.href, pageUrlAllowlist)) {\n return false;\n }\n\n /* istanbul ignore next */\n const elementType = (element as HTMLInputElement)?.type || '';\n if (typeof elementType === 'string') {\n switch (elementType.toLowerCase()) {\n case 'hidden':\n return false;\n case 'password':\n return false;\n }\n }\n\n /* istanbul ignore if */\n if (allowlist) {\n const hasMatchAnyAllowedSelector = allowlist.some((selector) => !!element?.matches?.(selector));\n if (!hasMatchAnyAllowedSelector) {\n return false;\n }\n }\n\n switch (tag) {\n case 'input':\n case 'select':\n case 'textarea':\n return actionType === 'change' || actionType === 'click';\n default: {\n /* istanbul ignore next */\n const computedStyle = window?.getComputedStyle?.(element);\n /* istanbul ignore next */\n if (computedStyle && computedStyle.getPropertyValue('cursor') === 'pointer' && actionType === 'click') {\n return true;\n }\n return actionType === 'click';\n }\n }\n };\n};\n\nexport const isNonSensitiveString = (text: string | null) => {\n if (text == null) {\n return false;\n }\n if (typeof text === 'string') {\n const ccRegex =\n /^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/;\n if (ccRegex.test((text || '').replace(/[- ]/g, ''))) {\n return false;\n }\n const ssnRegex = /(^\\d{3}-?\\d{2}-?\\d{4}$)/;\n if (ssnRegex.test(text)) {\n return false;\n }\n }\n return true;\n};\n\nexport const isTextNode = (node: Node) => {\n return !!node && node.nodeType === 3;\n};\n\nexport const isNonSensitiveElement = (element: Element) => {\n /* istanbul ignore next */\n const tag = element?.tagName?.toLowerCase?.();\n const isContentEditable =\n element instanceof HTMLElement ? element.getAttribute('contenteditable')?.toLowerCase() === 'true' : false;\n\n return !SENSITIVE_TAGS.includes(tag) && !isContentEditable;\n};\n\n// Maybe this can be simplified with element.innerText, keep and manual concatenating for now, more research needed.\nexport const getText = (element: Element): string => {\n let text = '';\n if (isNonSensitiveElement(element) && element.childNodes && element.childNodes.length) {\n element.childNodes.forEach((child) => {\n let childText = '';\n if (isTextNode(child)) {\n if (child.textContent) {\n childText = child.textContent;\n }\n } else {\n childText = getText(child as Element);\n }\n text += childText\n .split(/(\\s+)/)\n .filter(isNonSensitiveString)\n .join('')\n .replace(/[\\r\\n]/g, ' ')\n .replace(/[ ]+/g, ' ')\n .substring(0, 255);\n });\n }\n return text;\n};\n\nexport const getSelector = (element: Element, logger?: Logger): string => {\n let selector = '';\n try {\n selector = finder(element, {\n className: (name: string) => name !== constants.AMPLITUDE_VISUAL_TAGGING_HIGHLIGHT_CLASS,\n maxNumberOfTries: 1000,\n });\n return selector;\n } catch (error) {\n if (logger) {\n const typedError = error as Error;\n logger.warn(`Failed to get selector with finder, use fallback strategy instead: ${typedError.toString()}`);\n }\n }\n // Fall back to use tag, id, and class name, if finder fails.\n /* istanbul ignore next */\n const tag = element?.tagName?.toLowerCase?.();\n if (tag) {\n selector = tag;\n }\n if (element.id) {\n selector = `#${element.id}`;\n } else if (element.className) {\n const classes = element.className\n .split(' ')\n .filter((name) => name !== constants.AMPLITUDE_VISUAL_TAGGING_HIGHLIGHT_CLASS)\n .join('.');\n if (classes) {\n selector = `${selector}.${classes}`;\n }\n }\n return selector;\n};\n\nexport const isPageUrlAllowed = (url: string, pageUrlAllowlist: (string | RegExp)[] | undefined) => {\n if (!pageUrlAllowlist || !pageUrlAllowlist.length) {\n return true;\n }\n return pageUrlAllowlist.some((allowedUrl) => {\n if (typeof allowedUrl === 'string') {\n return url === allowedUrl;\n }\n return url.match(allowedUrl);\n });\n};\n\nexport const getAttributesWithPrefix = (element: Element, prefix: string): { [key: string]: string } => {\n return element.getAttributeNames().reduce((attributes: { [key: string]: string }, attributeName) => {\n if (attributeName.startsWith(prefix)) {\n const attributeKey = attributeName.replace(prefix, '');\n const attributeValue = element.getAttribute(attributeName);\n if (attributeKey) {\n attributes[attributeKey] = attributeValue || '';\n }\n }\n return attributes;\n }, {});\n};\n\nexport const isEmpty = (value: unknown) => {\n return (\n value === undefined ||\n value === null ||\n (typeof value === 'object' && Object.keys(value).length === 0) ||\n (typeof value === 'string' && value.trim().length === 0)\n );\n};\n\nexport const removeEmptyProperties = (properties: { [key: string]: unknown }) => {\n return Object.keys(properties).reduce((filteredProperties: { [key: string]: unknown }, key) => {\n const value = properties[key];\n if (!isEmpty(value)) {\n filteredProperties[key] = value;\n }\n return filteredProperties;\n }, {});\n};\n\nexport const getNearestLabel = (element: Element): string => {\n const parent = element.parentElement;\n if (!parent) {\n return '';\n }\n const labelElement = parent.querySelector(':scope>span,h1,h2,h3,h4,h5,h6');\n if (labelElement) {\n /* istanbul ignore next */\n const labelText = labelElement.textContent || '';\n return isNonSensitiveString(labelText) ? labelText : '';\n }\n return getNearestLabel(parent);\n};\n\nexport const querySelectUniqueElements = (root: Element | Document, selectors: string[]): Element[] => {\n if (root && 'querySelectorAll' in root && typeof root.querySelectorAll === 'function') {\n const elementSet = selectors.reduce((elements: Set<Element>, selector) => {\n if (selector) {\n const selectedElements = Array.from(root.querySelectorAll(selector));\n selectedElements.forEach((element) => {\n elements.add(element);\n });\n }\n return elements;\n }, new Set<Element>());\n return Array.from(elementSet);\n }\n return [];\n};\n\n// Similar as element.closest, but works with multiple selectors\nexport const getClosestElement = (element: Element | null, selectors: string[]): Element | null => {\n if (!element) {\n return null;\n }\n /* istanbul ignore next */\n if (selectors.some((selector) => element?.matches?.(selector))) {\n return element;\n }\n /* istanbul ignore next */\n return getClosestElement(element?.parentElement, selectors);\n};\n\n// Returns the element properties for the given element in Visual Labeling.\nexport const getEventTagProps = (element: Element, logger?: Logger) => {\n if (!element) {\n return {};\n }\n /* istanbul ignore next */\n const tag = element?.tagName?.toLowerCase?.();\n const selector = getSelector(element, logger);\n\n const properties: Record<string, JSONValue> = {\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_TAG]: tag,\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_TEXT]: getText(element),\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_SELECTOR]: selector,\n [constants.AMPLITUDE_EVENT_PROP_PAGE_URL]: window.location.href.split('?')[0],\n };\n return removeEmptyProperties(properties);\n};\n\nexport const asyncLoadScript = (url: string) => {\n return new Promise((resolve, reject) => {\n try {\n const scriptElement = document.createElement('script');\n scriptElement.type = 'text/javascript';\n scriptElement.async = true;\n scriptElement.src = url;\n scriptElement.addEventListener(\n 'load',\n () => {\n resolve({ status: true });\n },\n { once: true },\n );\n scriptElement.addEventListener('error', () => {\n reject({\n status: false,\n message: `Failed to load the script ${url}`,\n });\n });\n /* istanbul ignore next */\n document.head?.appendChild(scriptElement);\n } catch (error) {\n /* istanbul ignore next */\n reject(error);\n }\n });\n};\n\nexport function generateUniqueId(): string {\n return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n}\n\nexport const filterOutNonTrackableEvents = (event: ElementBasedTimestampedEvent<ElementBasedEvent>): boolean => {\n // Filter out changeEvent events with no target\n // This could happen when change events are triggered programmatically\n if (event.event.target === null || !event.closestTrackedAncestor) {\n return false;\n }\n\n return true;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../src/helpers.ts"],"names":[],"mappings":"AAAA,0CAA0C;AAC1C,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACvC,OAAO,KAAK,SAAS,MAAM,aAAa,CAAC;AAMzC,IAAM,cAAc,GAAG,CAAC,OAAO,EAAE,QAAQ,EAAE,UAAU,CAAC,CAAC;AAIvD,MAAM,CAAC,IAAM,sBAAsB,GAAG,UACpC,kBAA8C,EAC9C,SAAmB;IAEnB,OAAO,UAAC,UAAsB,EAAE,OAAgB;;QACtC,IAAA,gBAAgB,GAA+B,kBAAkB,iBAAjD,EAAE,wBAAwB,GAAK,kBAAkB,yBAAvB,CAAwB;QAE1E,0BAA0B;QAC1B,IAAM,GAAG,GAAG,MAAA,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,OAAO,0CAAE,WAAW,kDAAI,CAAC;QAC9C,+CAA+C;QAC/C,IAAI,CAAC,GAAG,EAAE;YACR,OAAO,KAAK,CAAC;SACd;QAED,IAAI,wBAAwB,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int-disable no-restricted-globals */\nimport { finder } from './libs/finder';\nimport * as constants from './constants';\nimport { Logger, ElementInteractionsOptions, ActionType } from '@amplitude/analytics-types';\nimport { ElementBasedEvent, ElementBasedTimestampedEvent } from './autocapture-plugin';\n\nexport type JSONValue = string | number | boolean | null | { [x: string]: JSONValue } | Array<JSONValue>;\n\nconst SENSITIVE_TAGS = ['input', 'select', 'textarea'];\n\nexport type shouldTrackEvent = (actionType: ActionType, element: Element) => boolean;\n\nexport const createShouldTrackEvent = (\n autocaptureOptions: ElementInteractionsOptions,\n allowlist: string[], // this can be any type of css selector allow list\n): shouldTrackEvent => {\n return (actionType: ActionType, element: Element) => {\n const { pageUrlAllowlist, shouldTrackEventResolver } = autocaptureOptions;\n\n /* istanbul ignore next */\n const tag = element?.tagName?.toLowerCase?.();\n // window, document, and Text nodes have no tag\n if (!tag) {\n return false;\n }\n\n if (shouldTrackEventResolver) {\n return shouldTrackEventResolver(actionType, element);\n }\n\n if (!isPageUrlAllowed(window.location.href, pageUrlAllowlist)) {\n return false;\n }\n\n /* istanbul ignore next */\n const elementType = String(element?.getAttribute('type')) || '';\n if (typeof elementType === 'string') {\n switch (elementType.toLowerCase()) {\n case 'hidden':\n return false;\n case 'password':\n return false;\n }\n }\n\n /* istanbul ignore if */\n if (allowlist) {\n const hasMatchAnyAllowedSelector = allowlist.some((selector) => !!element?.matches?.(selector));\n if (!hasMatchAnyAllowedSelector) {\n return false;\n }\n }\n\n switch (tag) {\n case 'input':\n case 'select':\n case 'textarea':\n return actionType === 'change' || actionType === 'click';\n default: {\n /* istanbul ignore next */\n const computedStyle = window?.getComputedStyle?.(element);\n /* istanbul ignore next */\n if (computedStyle && computedStyle.getPropertyValue('cursor') === 'pointer' && actionType === 'click') {\n return true;\n }\n return actionType === 'click';\n }\n }\n };\n};\n\nexport const isNonSensitiveString = (text: string | null) => {\n if (text == null) {\n return false;\n }\n if (typeof text === 'string') {\n const ccRegex =\n /^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/;\n if (ccRegex.test((text || '').replace(/[- ]/g, ''))) {\n return false;\n }\n const ssnRegex = /(^\\d{3}-?\\d{2}-?\\d{4}$)/;\n if (ssnRegex.test(text)) {\n return false;\n }\n }\n return true;\n};\n\nexport const isTextNode = (node: Node) => {\n return !!node && node.nodeType === 3;\n};\n\nexport const isNonSensitiveElement = (element: Element) => {\n /* istanbul ignore next */\n const tag = element?.tagName?.toLowerCase?.();\n const isContentEditable =\n element instanceof HTMLElement ? element.getAttribute('contenteditable')?.toLowerCase() === 'true' : false;\n\n return !SENSITIVE_TAGS.includes(tag) && !isContentEditable;\n};\n\n// Maybe this can be simplified with element.innerText, keep and manual concatenating for now, more research needed.\nexport const getText = (element: Element): string => {\n let text = '';\n if (isNonSensitiveElement(element) && element.childNodes && element.childNodes.length) {\n element.childNodes.forEach((child) => {\n let childText = '';\n if (isTextNode(child)) {\n if (child.textContent) {\n childText = child.textContent;\n }\n } else {\n childText = getText(child as Element);\n }\n text += childText\n .split(/(\\s+)/)\n .filter(isNonSensitiveString)\n .join('')\n .replace(/[\\r\\n]/g, ' ')\n .replace(/[ ]+/g, ' ')\n .substring(0, 255);\n });\n }\n return text;\n};\n\nexport const getSelector = (element: Element, logger?: Logger): string => {\n let selector = '';\n try {\n selector = finder(element, {\n className: (name: string) => name !== constants.AMPLITUDE_VISUAL_TAGGING_HIGHLIGHT_CLASS,\n maxNumberOfTries: 1000,\n });\n return selector;\n } catch (error) {\n if (logger) {\n const typedError = error as Error;\n logger.warn(`Failed to get selector with finder, use fallback strategy instead: ${typedError.toString()}`);\n }\n }\n // Fall back to use tag, id, and class name, if finder fails.\n /* istanbul ignore next */\n const tag = element?.tagName?.toLowerCase?.();\n if (tag) {\n selector = tag;\n }\n const id = element.getAttribute('id');\n const className = element.getAttribute('class');\n if (id) {\n selector = `#${id}`;\n } else if (className) {\n const classes = className\n .split(' ')\n .filter((name) => name !== constants.AMPLITUDE_VISUAL_TAGGING_HIGHLIGHT_CLASS)\n .join('.');\n if (classes) {\n selector = `${selector}.${classes}`;\n }\n }\n return selector;\n};\n\nexport const isPageUrlAllowed = (url: string, pageUrlAllowlist: (string | RegExp)[] | undefined) => {\n if (!pageUrlAllowlist || !pageUrlAllowlist.length) {\n return true;\n }\n return pageUrlAllowlist.some((allowedUrl) => {\n if (typeof allowedUrl === 'string') {\n return url === allowedUrl;\n }\n return url.match(allowedUrl);\n });\n};\n\nexport const getAttributesWithPrefix = (element: Element, prefix: string): { [key: string]: string } => {\n return element.getAttributeNames().reduce((attributes: { [key: string]: string }, attributeName) => {\n if (attributeName.startsWith(prefix)) {\n const attributeKey = attributeName.replace(prefix, '');\n const attributeValue = element.getAttribute(attributeName);\n if (attributeKey) {\n attributes[attributeKey] = attributeValue || '';\n }\n }\n return attributes;\n }, {});\n};\n\nexport const isEmpty = (value: unknown) => {\n return (\n value === undefined ||\n value === null ||\n (typeof value === 'object' && Object.keys(value).length === 0) ||\n (typeof value === 'string' && value.trim().length === 0)\n );\n};\n\nexport const removeEmptyProperties = (properties: { [key: string]: unknown }) => {\n return Object.keys(properties).reduce((filteredProperties: { [key: string]: unknown }, key) => {\n const value = properties[key];\n if (!isEmpty(value)) {\n filteredProperties[key] = value;\n }\n return filteredProperties;\n }, {});\n};\n\nexport const getNearestLabel = (element: Element): string => {\n const parent = element.parentElement;\n if (!parent) {\n return '';\n }\n let labelElement;\n try {\n labelElement = parent.querySelector(':scope>span,h1,h2,h3,h4,h5,h6');\n } catch (error) {\n labelElement = null;\n }\n if (labelElement) {\n /* istanbul ignore next */\n const labelText = labelElement.textContent || '';\n return isNonSensitiveString(labelText) ? labelText : '';\n }\n return getNearestLabel(parent);\n};\n\nexport const querySelectUniqueElements = (root: Element | Document, selectors: string[]): Element[] => {\n if (root && 'querySelectorAll' in root && typeof root.querySelectorAll === 'function') {\n const elementSet = selectors.reduce((elements: Set<Element>, selector) => {\n if (selector) {\n const selectedElements = Array.from(root.querySelectorAll(selector));\n selectedElements.forEach((element) => {\n elements.add(element);\n });\n }\n return elements;\n }, new Set<Element>());\n return Array.from(elementSet);\n }\n return [];\n};\n\n// Similar as element.closest, but works with multiple selectors\nexport const getClosestElement = (element: Element | null, selectors: string[]): Element | null => {\n if (!element) {\n return null;\n }\n /* istanbul ignore next */\n if (selectors.some((selector) => element?.matches?.(selector))) {\n return element;\n }\n /* istanbul ignore next */\n return getClosestElement(element?.parentElement, selectors);\n};\n\n// Returns the element properties for the given element in Visual Labeling.\nexport const getEventTagProps = (element: Element, logger?: Logger) => {\n if (!element) {\n return {};\n }\n /* istanbul ignore next */\n const tag = element?.tagName?.toLowerCase?.();\n const selector = getSelector(element, logger);\n\n const properties: Record<string, JSONValue> = {\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_TAG]: tag,\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_TEXT]: getText(element),\n [constants.AMPLITUDE_EVENT_PROP_ELEMENT_SELECTOR]: selector,\n [constants.AMPLITUDE_EVENT_PROP_PAGE_URL]: window.location.href.split('?')[0],\n };\n return removeEmptyProperties(properties);\n};\n\nexport const asyncLoadScript = (url: string) => {\n return new Promise((resolve, reject) => {\n try {\n const scriptElement = document.createElement('script');\n scriptElement.type = 'text/javascript';\n scriptElement.async = true;\n scriptElement.src = url;\n scriptElement.addEventListener(\n 'load',\n () => {\n resolve({ status: true });\n },\n { once: true },\n );\n scriptElement.addEventListener('error', () => {\n reject({\n status: false,\n message: `Failed to load the script ${url}`,\n });\n });\n /* istanbul ignore next */\n document.head?.appendChild(scriptElement);\n } catch (error) {\n /* istanbul ignore next */\n reject(error);\n }\n });\n};\n\nexport function generateUniqueId(): string {\n return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n}\n\nexport const filterOutNonTrackableEvents = (event: ElementBasedTimestampedEvent<ElementBasedEvent>): boolean => {\n // Filter out changeEvent events with no target\n // This could happen when change events are triggered programmatically\n if (event.event.target === null || !event.closestTrackedAncestor) {\n return false;\n }\n\n return true;\n};\n"]}
|
package/lib/esm/hierarchy.js
CHANGED
|
@@ -34,7 +34,7 @@ export function getElementProperties(element) {
|
|
|
34
34
|
if (element === null) {
|
|
35
35
|
return null;
|
|
36
36
|
}
|
|
37
|
-
var tagName = element.tagName.toLowerCase();
|
|
37
|
+
var tagName = String(element.tagName).toLowerCase();
|
|
38
38
|
var properties = {
|
|
39
39
|
tag: tagName,
|
|
40
40
|
};
|
|
@@ -45,11 +45,11 @@ export function getElementProperties(element) {
|
|
|
45
45
|
}
|
|
46
46
|
var prevSiblingTag = (_e = (_d = element.previousElementSibling) === null || _d === void 0 ? void 0 : _d.tagName) === null || _e === void 0 ? void 0 : _e.toLowerCase();
|
|
47
47
|
if (prevSiblingTag) {
|
|
48
|
-
properties.prevSib = prevSiblingTag;
|
|
48
|
+
properties.prevSib = String(prevSiblingTag);
|
|
49
49
|
}
|
|
50
|
-
var id = element.id;
|
|
50
|
+
var id = element.getAttribute('id');
|
|
51
51
|
if (id) {
|
|
52
|
-
properties.id = id;
|
|
52
|
+
properties.id = String(id);
|
|
53
53
|
}
|
|
54
54
|
var classes = Array.from(element.classList);
|
|
55
55
|
if (classes.length) {
|
|
@@ -60,7 +60,7 @@ export function getElementProperties(element) {
|
|
|
60
60
|
var filteredAttributes = attributesArray.filter(function (attr) { return !BLOCKED_ATTRIBUTES.includes(attr.name); });
|
|
61
61
|
var isSensitiveElement = !isNonSensitiveElement(element);
|
|
62
62
|
// if input is hidden or password or for SVGs, skip attribute collection entirely
|
|
63
|
-
if (!HIGHLY_SENSITIVE_INPUT_TYPES.includes(element.type) && !SVG_TAGS.includes(tagName)) {
|
|
63
|
+
if (!HIGHLY_SENSITIVE_INPUT_TYPES.includes(String(element.getAttribute('type'))) && !SVG_TAGS.includes(tagName)) {
|
|
64
64
|
try {
|
|
65
65
|
for (var filteredAttributes_1 = __values(filteredAttributes), filteredAttributes_1_1 = filteredAttributes_1.next(); !filteredAttributes_1_1.done; filteredAttributes_1_1 = filteredAttributes_1.next()) {
|
|
66
66
|
var attr = filteredAttributes_1_1.value;
|
|
@@ -68,7 +68,7 @@ export function getElementProperties(element) {
|
|
|
68
68
|
if (isSensitiveElement && !SENSITIVE_ELEMENT_ATTRIBUTE_ALLOWLIST.includes(attr.name)) {
|
|
69
69
|
continue;
|
|
70
70
|
}
|
|
71
|
-
// Finally
|
|
71
|
+
// Finally cast attribute value to string and limit attribute value length
|
|
72
72
|
attributes[attr.name] = String(attr.value).substring(0, MAX_ATTRIBUTE_LENGTH);
|
|
73
73
|
}
|
|
74
74
|
}
|
package/lib/esm/hierarchy.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hierarchy.js","sourceRoot":"","sources":["../../src/hierarchy.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,qBAAqB,EAAa,MAAM,WAAW,CAAC;AAG7D,IAAM,kBAAkB,GAAG;IACzB,qDAAqD;IACrD,IAAI;IACJ,OAAO;IAEP,6CAA6C;IAC7C,OAAO;IAEP,+DAA+D;IAC/D,OAAO;IAEP,aAAa;IACb,SAAS;IACT,UAAU;IACV,SAAS;IACT,QAAQ;IACR,UAAU;IACV,SAAS;IACT,WAAW;IACX,SAAS;IACT,YAAY;IAEZ,iBAAiB;IACjB,cAAc;IACd,qBAAqB;IACrB,gBAAgB;CACjB,CAAC;AACF,IAAM,qCAAqC,GAAG,CAAC,MAAM,CAAC,CAAC;AAEvD,IAAM,QAAQ,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;AACtC,IAAM,4BAA4B,GAAG,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;AAC5D,IAAM,oBAAoB,GAAG,GAAG,CAAC;AACjC,IAAM,oBAAoB,GAAG,IAAI,CAAC;AAElC,MAAM,UAAU,oBAAoB,CAAC,OAAuB;;;IAC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AO,WAAI,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,MAAG,CAAC;SACnC;aAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;YACpC,0CAA0C;YAC1C,IAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC;iBAClC,MAAM,CAAC,UAAC,EAAK;oBAAL,KAAA,aAAK,EAAJ,GAAG,QAAA;gBAAM,OAAA,GAAG,IAAI,IAAI;YAAX,CAAW,CAAC,CAAC,uBAAuB;iBACtD,GAAG,CACF,UAAC,EAAU;oBAAV,KAAA,aAAU,EAAT,GAAG,QAAA,EAAE,GAAG,QAAA;gBACR,OAAA,UAAG,MAAM,CAAC,6BAA6B,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,eAAK,MAAM,CAAC,6BAA6B,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAE;YAA1G,CAA0G,CAC7G,CAAC;YACJ,IAAI,MAAM,GAAG,WAAI,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,MAAG,CAAC;YAEvC,+CAA+C;YAC/C,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE;gBAC1B,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;aACzD;YACD,OAAO,MAAM,CAAC;SACf;QACD,2DAA2D;QAC3D,OAAO,KAAK,CAAC,QAAQ,EAAE,CAAC;KACzB;IAAC,OAAO,CAAC,EAAE;QACV,wDAAwD;QACxD,OAAO,IAAI,CAAC;KACb;AACH,CAAC","sourcesContent":["import { isNonSensitiveElement, JSONValue } from './helpers';\nimport { Hierarchy, HierarchyNode } from './typings/autocapture';\n\nconst BLOCKED_ATTRIBUTES = [\n // Already captured elsewhere in the hierarchy object\n 'id',\n 'class',\n\n // non-useful and potentially large attribute\n 'style',\n\n // sensitive as prefilled form data may populate this attribute\n 'value',\n\n // DOM events\n 'onclick',\n 'onchange',\n 'oninput',\n 'onblur',\n 'onsubmit',\n 'onfocus',\n 'onkeydown',\n 'onkeyup',\n 'onkeypress',\n\n // React specific\n 'data-reactid',\n 'data-react-checksum',\n 'data-reactroot',\n];\nconst SENSITIVE_ELEMENT_ATTRIBUTE_ALLOWLIST = ['type'];\n\nconst SVG_TAGS = ['svg', 'path', 'g'];\nconst HIGHLY_SENSITIVE_INPUT_TYPES = ['password', 'hidden'];\nconst MAX_ATTRIBUTE_LENGTH = 128;\nconst MAX_HIERARCHY_LENGTH = 1024;\n\nexport function getElementProperties(element: Element | null): HierarchyNode | null {\n if (element === null) {\n return null;\n }\n\n const tagName = element.tagName.toLowerCase();\n const properties: HierarchyNode = {\n tag: tagName,\n };\n\n const siblings = Array.from(element.parentElement?.children ?? []);\n if (siblings.length) {\n properties.index = siblings.indexOf(element);\n properties.indexOfType = siblings.filter((el) => el.tagName === element.tagName).indexOf(element);\n }\n\n const prevSiblingTag = element.previousElementSibling?.tagName?.toLowerCase();\n if (prevSiblingTag) {\n properties.prevSib = prevSiblingTag;\n }\n\n const id = element.id;\n if (id) {\n properties.id = id;\n }\n\n const classes = Array.from(element.classList);\n if (classes.length) {\n properties.classes = classes;\n }\n\n const attributes: Record<string, string> = {};\n const attributesArray = Array.from(element.attributes);\n const filteredAttributes = attributesArray.filter((attr) => !BLOCKED_ATTRIBUTES.includes(attr.name));\n const isSensitiveElement = !isNonSensitiveElement(element);\n\n // if input is hidden or password or for SVGs, skip attribute collection entirely\n if (!HIGHLY_SENSITIVE_INPUT_TYPES.includes((element as HTMLInputElement).type) && !SVG_TAGS.includes(tagName)) {\n for (const attr of filteredAttributes) {\n // If sensitive element, only allow certain attributes\n if (isSensitiveElement && !SENSITIVE_ELEMENT_ATTRIBUTE_ALLOWLIST.includes(attr.name)) {\n continue;\n }\n\n // Finally limit attribute value length and save it\n attributes[attr.name] = String(attr.value).substring(0, MAX_ATTRIBUTE_LENGTH);\n }\n }\n\n if (Object.keys(attributes).length) {\n properties.attrs = attributes;\n }\n\n return properties;\n}\n\nexport function getAncestors(targetEl: Element | null): Element[] {\n const ancestors: Element[] = [];\n\n if (!targetEl) {\n return ancestors;\n }\n\n // Add self to the list of ancestors\n ancestors.push(targetEl);\n let current = targetEl.parentElement;\n while (current && current.tagName !== 'HTML') {\n ancestors.push(current);\n current = current.parentElement;\n }\n return ancestors;\n}\n\n// Get the DOM hierarchy of the element, starting from the target element to the root element.\nexport const getHierarchy = (element: Element | null): Hierarchy => {\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 hierarchy = ensureListUnderLimit(\n ancestors.map((el) => getElementProperties(el)),\n MAX_HIERARCHY_LENGTH,\n ) as Hierarchy;\n\n return hierarchy;\n};\n\nexport function ensureListUnderLimit(list: Hierarchy | JSONValue[], bytesLimit: number): Hierarchy | JSONValue[] {\n let numChars = 0;\n for (let i = 0; i < list.length; i++) {\n const node = list[i];\n if (node === null) {\n // simulate 'None' in python\n numChars += 4;\n } else {\n const value = ensureUnicodePythonCompatible(node);\n // Using Array.from(string).length instead of string.length\n // to correctly count Unicode characters (including emojis)\n numChars += value ? Array.from(value).length : 4;\n }\n if (numChars > bytesLimit) {\n return list.slice(0, i);\n }\n }\n return list;\n}\n\n/**\n * Converts a JSON-compatible value to a Python-compatible string representation.\n * This function handles various data types and ensures proper escaping and formatting.\n *\n * @param value - The value to be converted (can be any JSON-compatible type)\n * @param nested - Indicates if the value is nested within another structure (default: false)\n * @returns A string representation of the value compatible with Python, or null if conversion fails\n */\nexport function ensureUnicodePythonCompatible(value: HierarchyNode | JSONValue | null, nested = false): string | null {\n try {\n if (value == null) {\n // Handle null values\n if (nested) {\n return 'None'; // Represent null as 'None' in Python when nested\n }\n return null; // Return null for top-level null values\n } else if (typeof value === 'string') {\n if (nested) {\n // Escape special characters in nested strings\n value = value.replace(/\\\\/g, '\\\\\\\\').replace(/\\n/g, '\\\\n').replace(/\\t/g, '\\\\t').replace(/\\r/g, '\\\\r');\n\n // Handle quotes in the string\n if (value.includes('\"')) {\n return `'${value}'`; // Wrap in single quotes if it contains double quotes\n }\n if (value.includes(\"'\")) {\n return `\"${value.replace(/'/g, \"\\\\'\")}\"`; // Wrap in double quotes and escape single quotes\n }\n return `'${value}'`; // Default to wrapping in single quotes\n }\n return value; // Return non-nested strings as-is\n } else if (typeof value === 'boolean') {\n // Convert boolean to Python-style capitalized string\n return value ? 'True' : 'False';\n } else if (Array.isArray(value)) {\n // Handle arrays by recursively converting each element\n const elements = value.map((o) => ensureUnicodePythonCompatible(o, true));\n return `[${elements.join(', ')}]`;\n } else if (typeof value === 'object') {\n // Handle objects (dictionaries in Python)\n const entries = Object.entries(value)\n .filter(([key]) => key != null) // Filter out null keys\n .map(\n ([key, val]) =>\n `${String(ensureUnicodePythonCompatible(key, true))}: ${String(ensureUnicodePythonCompatible(val, true))}`,\n );\n let result = `{${entries.join(', ')}}`;\n\n // Handle single quotes in the resulting string\n if (result.includes(\"\\\\'\")) {\n result = result.replace(/'/g, \"'\").replace(/'/g, \"\\\\'\");\n }\n return result;\n }\n // For any other types, return their string representation;\n return value.toString();\n } catch (e) {\n // Return null if any error occurs during the conversion\n return null;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"hierarchy.js","sourceRoot":"","sources":["../../src/hierarchy.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,qBAAqB,EAAa,MAAM,WAAW,CAAC;AAG7D,IAAM,kBAAkB,GAAG;IACzB,qDAAqD;IACrD,IAAI;IACJ,OAAO;IAEP,6CAA6C;IAC7C,OAAO;IAEP,+DAA+D;IAC/D,OAAO;IAEP,aAAa;IACb,SAAS;IACT,UAAU;IACV,SAAS;IACT,QAAQ;IACR,UAAU;IACV,SAAS;IACT,WAAW;IACX,SAAS;IACT,YAAY;IAEZ,iBAAiB;IACjB,cAAc;IACd,qBAAqB;IACrB,gBAAgB;CACjB,CAAC;AACF,IA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AAE,KAAK,CAAC,CAAC;aACzD;YACD,OAAO,MAAM,CAAC;SACf;QACD,2DAA2D;QAC3D,OAAO,KAAK,CAAC,QAAQ,EAAE,CAAC;KACzB;IAAC,OAAO,CAAC,EAAE;QACV,wDAAwD;QACxD,OAAO,IAAI,CAAC;KACb;AACH,CAAC","sourcesContent":["import { isNonSensitiveElement, JSONValue } from './helpers';\nimport { Hierarchy, HierarchyNode } from './typings/autocapture';\n\nconst BLOCKED_ATTRIBUTES = [\n // Already captured elsewhere in the hierarchy object\n 'id',\n 'class',\n\n // non-useful and potentially large attribute\n 'style',\n\n // sensitive as prefilled form data may populate this attribute\n 'value',\n\n // DOM events\n 'onclick',\n 'onchange',\n 'oninput',\n 'onblur',\n 'onsubmit',\n 'onfocus',\n 'onkeydown',\n 'onkeyup',\n 'onkeypress',\n\n // React specific\n 'data-reactid',\n 'data-react-checksum',\n 'data-reactroot',\n];\nconst SENSITIVE_ELEMENT_ATTRIBUTE_ALLOWLIST = ['type'];\n\nconst SVG_TAGS = ['svg', 'path', 'g'];\nconst HIGHLY_SENSITIVE_INPUT_TYPES = ['password', 'hidden'];\nconst MAX_ATTRIBUTE_LENGTH = 128;\nconst MAX_HIERARCHY_LENGTH = 1024;\n\nexport function getElementProperties(element: Element | null): HierarchyNode | null {\n if (element === null) {\n return null;\n }\n\n const tagName = String(element.tagName).toLowerCase();\n const properties: HierarchyNode = {\n tag: tagName,\n };\n\n const siblings = Array.from(element.parentElement?.children ?? []);\n if (siblings.length) {\n properties.index = siblings.indexOf(element);\n properties.indexOfType = siblings.filter((el) => el.tagName === element.tagName).indexOf(element);\n }\n\n const prevSiblingTag = element.previousElementSibling?.tagName?.toLowerCase();\n if (prevSiblingTag) {\n properties.prevSib = String(prevSiblingTag);\n }\n\n const id = element.getAttribute('id');\n if (id) {\n properties.id = String(id);\n }\n\n const classes = Array.from(element.classList);\n if (classes.length) {\n properties.classes = classes;\n }\n\n const attributes: Record<string, string> = {};\n const attributesArray = Array.from(element.attributes);\n const filteredAttributes = attributesArray.filter((attr) => !BLOCKED_ATTRIBUTES.includes(attr.name));\n const isSensitiveElement = !isNonSensitiveElement(element);\n\n // if input is hidden or password or for SVGs, skip attribute collection entirely\n if (!HIGHLY_SENSITIVE_INPUT_TYPES.includes(String(element.getAttribute('type'))) && !SVG_TAGS.includes(tagName)) {\n for (const attr of filteredAttributes) {\n // If sensitive element, only allow certain attributes\n if (isSensitiveElement && !SENSITIVE_ELEMENT_ATTRIBUTE_ALLOWLIST.includes(attr.name)) {\n continue;\n }\n\n // Finally cast attribute value to string and limit attribute value length\n attributes[attr.name] = String(attr.value).substring(0, MAX_ATTRIBUTE_LENGTH);\n }\n }\n\n if (Object.keys(attributes).length) {\n properties.attrs = attributes;\n }\n\n return properties;\n}\n\nexport function getAncestors(targetEl: Element | null): Element[] {\n const ancestors: Element[] = [];\n\n if (!targetEl) {\n return ancestors;\n }\n\n // Add self to the list of ancestors\n ancestors.push(targetEl);\n let current = targetEl.parentElement;\n while (current && current.tagName !== 'HTML') {\n ancestors.push(current);\n current = current.parentElement;\n }\n return ancestors;\n}\n\n// Get the DOM hierarchy of the element, starting from the target element to the root element.\nexport const getHierarchy = (element: Element | null): Hierarchy => {\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 hierarchy = ensureListUnderLimit(\n ancestors.map((el) => getElementProperties(el)),\n MAX_HIERARCHY_LENGTH,\n ) as Hierarchy;\n\n return hierarchy;\n};\n\nexport function ensureListUnderLimit(list: Hierarchy | JSONValue[], bytesLimit: number): Hierarchy | JSONValue[] {\n let numChars = 0;\n for (let i = 0; i < list.length; i++) {\n const node = list[i];\n if (node === null) {\n // simulate 'None' in python\n numChars += 4;\n } else {\n const value = ensureUnicodePythonCompatible(node);\n // Using Array.from(string).length instead of string.length\n // to correctly count Unicode characters (including emojis)\n numChars += value ? Array.from(value).length : 4;\n }\n if (numChars > bytesLimit) {\n return list.slice(0, i);\n }\n }\n return list;\n}\n\n/**\n * Converts a JSON-compatible value to a Python-compatible string representation.\n * This function handles various data types and ensures proper escaping and formatting.\n *\n * @param value - The value to be converted (can be any JSON-compatible type)\n * @param nested - Indicates if the value is nested within another structure (default: false)\n * @returns A string representation of the value compatible with Python, or null if conversion fails\n */\nexport function ensureUnicodePythonCompatible(value: HierarchyNode | JSONValue | null, nested = false): string | null {\n try {\n if (value == null) {\n // Handle null values\n if (nested) {\n return 'None'; // Represent null as 'None' in Python when nested\n }\n return null; // Return null for top-level null values\n } else if (typeof value === 'string') {\n if (nested) {\n // Escape special characters in nested strings\n value = value.replace(/\\\\/g, '\\\\\\\\').replace(/\\n/g, '\\\\n').replace(/\\t/g, '\\\\t').replace(/\\r/g, '\\\\r');\n\n // Handle quotes in the string\n if (value.includes('\"')) {\n return `'${value}'`; // Wrap in single quotes if it contains double quotes\n }\n if (value.includes(\"'\")) {\n return `\"${value.replace(/'/g, \"\\\\'\")}\"`; // Wrap in double quotes and escape single quotes\n }\n return `'${value}'`; // Default to wrapping in single quotes\n }\n return value; // Return non-nested strings as-is\n } else if (typeof value === 'boolean') {\n // Convert boolean to Python-style capitalized string\n return value ? 'True' : 'False';\n } else if (Array.isArray(value)) {\n // Handle arrays by recursively converting each element\n const elements = value.map((o) => ensureUnicodePythonCompatible(o, true));\n return `[${elements.join(', ')}]`;\n } else if (typeof value === 'object') {\n // Handle objects (dictionaries in Python)\n const entries = Object.entries(value)\n .filter(([key]) => key != null) // Filter out null keys\n .map(\n ([key, val]) =>\n `${String(ensureUnicodePythonCompatible(key, true))}: ${String(ensureUnicodePythonCompatible(val, true))}`,\n );\n let result = `{${entries.join(', ')}}`;\n\n // Handle single quotes in the resulting string\n if (result.includes(\"\\\\'\")) {\n result = result.replace(/'/g, \"'\").replace(/'/g, \"\\\\'\");\n }\n return result;\n }\n // For any other types, return their string representation;\n return value.toString();\n } catch (e) {\n // Return null if any error occurs during the conversion\n return null;\n }\n}\n"]}
|
package/lib/esm/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { autocapturePlugin as plugin, autocapturePlugin
|
|
2
|
-
export {
|
|
1
|
+
export { autocapturePlugin as plugin, autocapturePlugin } from './autocapture-plugin';
|
|
2
|
+
export { Action, ActionData, Message, WindowMessenger } from './libs/messenger';
|
|
3
3
|
//# sourceMappingURL=index.d.ts.map
|
package/lib/esm/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,IAAI,MAAM,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACtF,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC"}
|
package/lib/esm/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { autocapturePlugin as plugin, autocapturePlugin
|
|
1
|
+
export { autocapturePlugin as plugin, autocapturePlugin } from './autocapture-plugin';
|
|
2
2
|
export { WindowMessenger } from './libs/messenger';
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
package/lib/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,IAAI,MAAM,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACtF,OAAO,EAA+B,eAAe,EAAE,MAAM,kBAAkB,CAAC","sourcesContent":["export { autocapturePlugin as plugin, autocapturePlugin } from './autocapture-plugin';\nexport { Action, ActionData, Message, WindowMessenger } from './libs/messenger';\n"]}
|
|
@@ -1,9 +1,4 @@
|
|
|
1
|
-
import { Logger } from '@amplitude/analytics-types';
|
|
2
|
-
import { ActionType } from '../typings/autocapture';
|
|
3
|
-
export interface Messenger {
|
|
4
|
-
logger?: Logger;
|
|
5
|
-
setup: () => void;
|
|
6
|
-
}
|
|
1
|
+
import { Logger, Messenger, ActionType } from '@amplitude/analytics-types';
|
|
7
2
|
export type Action = 'ping' | 'pong' | 'page-loaded' | 'selector-loaded' | 'initialize-visual-tagging-selector' | 'close-visual-tagging-selector' | 'element-selected' | 'track-selector-mode-changed' | 'track-selector-moved';
|
|
8
3
|
interface InitializeVisualTaggingSelectorData {
|
|
9
4
|
actionType: ActionType;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messenger.d.ts","sourceRoot":"","sources":["../../../src/libs/messenger.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,MAAM,EAAE,
|
|
1
|
+
{"version":3,"file":"messenger.d.ts","sourceRoot":"","sources":["../../../src/libs/messenger.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,4BAA4B,CAAC;AAE3E,MAAM,MAAM,MAAM,GACd,MAAM,GACN,MAAM,GACN,aAAa,GACb,iBAAiB,GACjB,oCAAoC,GACpC,+BAA+B,GAC/B,kBAAkB,GAClB,6BAA6B,GAC7B,sBAAsB,CAAC;AAE3B,UAAU,mCAAmC;IAC3C,UAAU,EAAE,UAAU,CAAC;CACxB;AAED,UAAU,mBAAmB;IAC3B,+BAA+B,CAAC,EAAE,MAAM,CAAC;IACzC,yBAAyB,CAAC,EAAE,MAAM,CAAC;IACnC,0BAA0B,CAAC,EAAE,MAAM,CAAC;IACpC,8BAA8B,CAAC,EAAE,MAAM,CAAC;IACxC,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,iBAAiB,CAAC,EAAE,IAAI,CAAC;CAC1B;AAED,UAAU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,EAAE,KAAI,CAAC,OAAO;4BACrB,QAAQ,EAAE,KAAI,CAAC,QAAQ;4BACvB,oBAAoB,EAAE,wCAAwC;4BAC9D,SAAS,EAAE,KAAI;4BACf,oBAAoB,sBAAA;4BACpB,oBAAoB,sBAAA;yBACrB,CAAC,CAAC;wBACH,KAAI,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,iBAAiB,EAAE,CAAC,CAAC;oBAC7C,CAAC,CAAC;yBACD,KAAK,CAAC;;wBACL,MAAA,KAAI,CAAC,MAAM,0CAAE,IAAI,CAAC,8CAA8C,CAAC,CAAC;oBACpE,CAAC,CAAC,CAAC;iBACN;qBAAM,IAAI,MAAM,KAAK,+BAA+B,EAAE;oBACrD,2BAA2B;oBAC3B,MAAA,sCAAsC,aAAtC,sCAAsC,uBAAtC,sCAAsC,CAAE,KAAK,sFAAI,CAAC;iBACnD;aACF;QACH,CAAC,CAAC,CAAC;QAEH,oDAAoD;QACpD,IAAI,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,aAAa,EAAE,CAAC,CAAC;IACzC,CAAC;IAaH,sBAAC;AAAD,CAAC,AAxJD,IAwJC","sourcesContent":["/* istanbul ignore file */\n/* eslint-disable no-restricted-globals */\nimport {\n AMPLITUDE_ORIGIN,\n AMPLITUDE_VISUAL_TAGGING_SELECTOR_SCRIPT_URL,\n AMPLITUDE_VISUAL_TAGGING_HIGHLIGHT_CLASS,\n} from '../constants';\nimport { asyncLoadScript, generateUniqueId, getEventTagProps } from '../helpers';\nimport { Logger } from '@amplitude/analytics-types';\nimport { ActionType } from '../typings/autocapture';\n\nexport interface Messenger {\n logger?: Logger;\n setup: () => void;\n}\n\nexport type Action =\n | 'ping'\n | 'pong'\n | 'page-loaded'\n | 'selector-loaded'\n | 'initialize-visual-tagging-selector'\n | 'close-visual-tagging-selector'\n | 'element-selected'\n | 'track-selector-mode-changed'\n | 'track-selector-moved';\n\ninterface InitializeVisualTaggingSelectorData {\n actionType: ActionType;\n}\n\ninterface ElementSelectedData {\n '[Amplitude] Element Hierarchy'?: string;\n '[Amplitude] Element Tag'?: string;\n '[Amplitude] Element Text'?: string;\n '[Amplitude] Element Selector'?: string;\n '[Amplitude] Page URL'?: string;\n elementScreenshot?: Blob;\n}\n\ninterface TrackSelectorModeChangedData {\n newMode: string;\n pageUrl?: string;\n}\n\ninterface TrackSelectorMovedData {\n newEditorLocation: string;\n pageUrl?: string;\n}\n\nexport type ActionData = {\n ping: null | undefined;\n pong: null | undefined;\n 'page-loaded': null | undefined;\n 'selector-loaded': null | undefined;\n 'initialize-visual-tagging-selector': InitializeVisualTaggingSelectorData | null | undefined;\n 'close-visual-tagging-selector': null | undefined;\n 'element-selected': ElementSelectedData;\n 'track-selector-mode-changed': TrackSelectorModeChangedData;\n 'track-selector-moved': TrackSelectorMovedData;\n};\n\nexport interface Message<A extends Action> {\n action: A;\n data?: ActionData[A];\n}\n\ntype MessageRequest = {\n id: string;\n action: string;\n args: Record<string, any>;\n};\n\ntype MessageResponse = {\n id: string;\n action: string;\n responseData: any;\n};\n\n// TODO: use MessageChannel instead of window.postMessage\nexport class WindowMessenger implements Messenger {\n endpoint = AMPLITUDE_ORIGIN;\n logger?: Logger;\n requestCallbacks: {\n [id: string]: {\n resolve: (data: any) => void;\n reject: (data: any) => void;\n };\n } = {};\n\n constructor({ origin = AMPLITUDE_ORIGIN }: { origin?: string } = {}) {\n this.endpoint = origin;\n }\n\n private notify(message: Message<Action> | MessageRequest) {\n this.logger?.debug?.('Message sent: ', JSON.stringify(message));\n (window.opener as WindowProxy)?.postMessage?.(message, this.endpoint);\n }\n\n // Send an async request to the parent window\n public sendRequest(action: string, args: Record<string, any>, options = { timeout: 15_000 }): Promise<any> {\n // Create Request ID\n const id = generateUniqueId();\n const request = {\n id,\n action,\n args,\n };\n\n // Create a Promise that will be resolved when the response is received\n const promise = new Promise((resolve, reject) => {\n this.requestCallbacks[id] = { resolve, reject };\n\n // Send the request\n this.notify(request);\n\n // Handle request timeouts\n if (options?.timeout > 0) {\n setTimeout(() => {\n reject(new Error(`${action} timed out (id: ${id})`));\n delete this.requestCallbacks[id];\n }, options.timeout);\n }\n });\n\n return promise;\n }\n\n // Handle messages from the parent window\n private handleResponse(response: MessageResponse) {\n if (!this.requestCallbacks[response.id]) {\n this.logger?.warn(`No callback found for request id: ${response.id}`);\n return;\n }\n\n this.requestCallbacks[response.id].resolve(response.responseData);\n delete this.requestCallbacks[response.id];\n }\n\n setup({\n logger,\n endpoint,\n isElementSelectable,\n cssSelectorAllowlist,\n actionClickAllowlist,\n }: {\n logger?: Logger;\n endpoint?: string;\n isElementSelectable?: (action: InitializeVisualTaggingSelectorData['actionType'], element: Element) => boolean;\n cssSelectorAllowlist?: string[];\n actionClickAllowlist?: string[];\n } = {}) {\n this.logger = logger;\n // If endpoint is customized, don't override it.\n if (endpoint && this.endpoint === AMPLITUDE_ORIGIN) {\n this.endpoint = endpoint;\n }\n let amplitudeVisualTaggingSelectorInstance: any = null;\n\n // Attach Event Listener to listen for messages from the parent window\n window.addEventListener('message', (event) => {\n this.logger?.debug?.('Message received: ', JSON.stringify(event));\n\n // Only accept messages from the specified origin\n if (this.endpoint !== event.origin) {\n return;\n }\n\n const eventData = event?.data as Message<Action> | MessageResponse;\n const action = eventData?.action;\n\n // Ignore messages without action\n if (!action) {\n return;\n }\n\n // If id exists, handle responses to previous requests\n if ('id' in eventData) {\n this.logger?.debug?.('Received Response to previous request: ', JSON.stringify(event));\n this.handleResponse(eventData);\n\n // If action exists, handle the action using existing handlers\n } else {\n if (action === 'ping') {\n this.notify({ action: 'pong' });\n } else if (action === 'initialize-visual-tagging-selector') {\n const actionData = eventData?.data as InitializeVisualTaggingSelectorData;\n asyncLoadScript(AMPLITUDE_VISUAL_TAGGING_SELECTOR_SCRIPT_URL)\n .then(() => {\n // eslint-disable-next-line\n amplitudeVisualTaggingSelectorInstance = (window as any)?.amplitudeVisualTaggingSelector?.({\n getEventTagProps,\n isElementSelectable: (element: Element) => {\n if (isElementSelectable) {\n return isElementSelectable(actionData?.actionType || 'click', element);\n }\n return true;\n },\n onTrack: this.onTrack,\n onSelect: this.onSelect,\n visualHighlightClass: AMPLITUDE_VISUAL_TAGGING_HIGHLIGHT_CLASS,\n messenger: this,\n cssSelectorAllowlist,\n actionClickAllowlist,\n });\n this.notify({ action: 'selector-loaded' });\n })\n .catch(() => {\n this.logger?.warn('Failed to initialize visual tagging selector');\n });\n } else if (action === 'close-visual-tagging-selector') {\n // eslint-disable-next-line\n amplitudeVisualTaggingSelectorInstance?.close?.();\n }\n }\n });\n\n // Notify the parent window that the page has loaded\n this.notify({ action: 'page-loaded' });\n }\n\n private onSelect = (data: ElementSelectedData) => {\n this.notify({ action: 'element-selected', data });\n };\n\n private onTrack = (type: string, properties: { [key: string]: string | null }) => {\n if (type === 'selector-mode-changed') {\n this.notify({ action: 'track-selector-mode-changed', data: properties });\n } else if (type === 'selector-moved') {\n this.notify({ action: 'track-selector-moved', data: properties });\n }\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"messenger.js","sourceRoot":"","sources":["../../../src/libs/messenger.ts"],"names":[],"mappings":"AAAA,0BAA0B;AAC1B,0CAA0C;AAC1C,OAAO,EACL,gBAAgB,EAChB,4CAA4C,EAC5C,wCAAwC,GACzC,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAkEjF,yDAAyD;AACzD;IAUE,yBAAY,EAAuD;YAAvD,qBAAqD,EAAE,KAAA,EAArD,cAAyB,EAAzB,MAAM,mBAAG,gBAAgB,KAAA;QAAvC,iBAEC;QAXD,aAAQ,GAAG,gBAAgB,CAAC;QAE5B,qBAAgB,GAKZ,EAAE,CAAC;QAqIC,aAAQ,GAAG,UAAC,IAAyB;YAC3C,KAAI,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,kBAAkB,EAAE,IAAI,MAAA,EAAE,CAAC,CAAC;QACpD,CAAC,CAAC;QAEM,YAAO,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O,CAAC,CAAC;iCACxE;gCACD,OAAO,IAAI,CAAC;4BACd,CAAC;4BACD,OAAO,EAAE,KAAI,CAAC,OAAO;4BACrB,QAAQ,EAAE,KAAI,CAAC,QAAQ;4BACvB,oBAAoB,EAAE,wCAAwC;4BAC9D,SAAS,EAAE,KAAI;4BACf,oBAAoB,sBAAA;4BACpB,oBAAoB,sBAAA;yBACrB,CAAC,CAAC;wBACH,KAAI,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,iBAAiB,EAAE,CAAC,CAAC;oBAC7C,CAAC,CAAC;yBACD,KAAK,CAAC;;wBACL,MAAA,KAAI,CAAC,MAAM,0CAAE,IAAI,CAAC,8CAA8C,CAAC,CAAC;oBACpE,CAAC,CAAC,CAAC;iBACN;qBAAM,IAAI,MAAM,KAAK,+BAA+B,EAAE;oBACrD,2BAA2B;oBAC3B,MAAA,sCAAsC,aAAtC,sCAAsC,uBAAtC,sCAAsC,CAAE,KAAK,sFAAI,CAAC;iBACnD;aACF;QACH,CAAC,CAAC,CAAC;QAEH,oDAAoD;QACpD,IAAI,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,aAAa,EAAE,CAAC,CAAC;IACzC,CAAC;IAaH,sBAAC;AAAD,CAAC,AAxJD,IAwJC","sourcesContent":["/* istanbul ignore file */\n/* eslint-disable no-restricted-globals */\nimport {\n AMPLITUDE_ORIGIN,\n AMPLITUDE_VISUAL_TAGGING_SELECTOR_SCRIPT_URL,\n AMPLITUDE_VISUAL_TAGGING_HIGHLIGHT_CLASS,\n} from '../constants';\nimport { asyncLoadScript, generateUniqueId, getEventTagProps } from '../helpers';\nimport { Logger, Messenger, ActionType } from '@amplitude/analytics-types';\n\nexport type Action =\n | 'ping'\n | 'pong'\n | 'page-loaded'\n | 'selector-loaded'\n | 'initialize-visual-tagging-selector'\n | 'close-visual-tagging-selector'\n | 'element-selected'\n | 'track-selector-mode-changed'\n | 'track-selector-moved';\n\ninterface InitializeVisualTaggingSelectorData {\n actionType: ActionType;\n}\n\ninterface ElementSelectedData {\n '[Amplitude] Element Hierarchy'?: string;\n '[Amplitude] Element Tag'?: string;\n '[Amplitude] Element Text'?: string;\n '[Amplitude] Element Selector'?: string;\n '[Amplitude] Page URL'?: string;\n elementScreenshot?: Blob;\n}\n\ninterface TrackSelectorModeChangedData {\n newMode: string;\n pageUrl?: string;\n}\n\ninterface TrackSelectorMovedData {\n newEditorLocation: string;\n pageUrl?: string;\n}\n\nexport type ActionData = {\n ping: null | undefined;\n pong: null | undefined;\n 'page-loaded': null | undefined;\n 'selector-loaded': null | undefined;\n 'initialize-visual-tagging-selector': InitializeVisualTaggingSelectorData | null | undefined;\n 'close-visual-tagging-selector': null | undefined;\n 'element-selected': ElementSelectedData;\n 'track-selector-mode-changed': TrackSelectorModeChangedData;\n 'track-selector-moved': TrackSelectorMovedData;\n};\n\nexport interface Message<A extends Action> {\n action: A;\n data?: ActionData[A];\n}\n\ntype MessageRequest = {\n id: string;\n action: string;\n args: Record<string, any>;\n};\n\ntype MessageResponse = {\n id: string;\n action: string;\n responseData: any;\n};\n\n// TODO: use MessageChannel instead of window.postMessage\nexport class WindowMessenger implements Messenger {\n endpoint = AMPLITUDE_ORIGIN;\n logger?: Logger;\n requestCallbacks: {\n [id: string]: {\n resolve: (data: any) => void;\n reject: (data: any) => void;\n };\n } = {};\n\n constructor({ origin = AMPLITUDE_ORIGIN }: { origin?: string } = {}) {\n this.endpoint = origin;\n }\n\n private notify(message: Message<Action> | MessageRequest) {\n this.logger?.debug?.('Message sent: ', JSON.stringify(message));\n (window.opener as WindowProxy)?.postMessage?.(message, this.endpoint);\n }\n\n // Send an async request to the parent window\n public sendRequest(action: string, args: Record<string, any>, options = { timeout: 15_000 }): Promise<any> {\n // Create Request ID\n const id = generateUniqueId();\n const request = {\n id,\n action,\n args,\n };\n\n // Create a Promise that will be resolved when the response is received\n const promise = new Promise((resolve, reject) => {\n this.requestCallbacks[id] = { resolve, reject };\n\n // Send the request\n this.notify(request);\n\n // Handle request timeouts\n if (options?.timeout > 0) {\n setTimeout(() => {\n reject(new Error(`${action} timed out (id: ${id})`));\n delete this.requestCallbacks[id];\n }, options.timeout);\n }\n });\n\n return promise;\n }\n\n // Handle messages from the parent window\n private handleResponse(response: MessageResponse) {\n if (!this.requestCallbacks[response.id]) {\n this.logger?.warn(`No callback found for request id: ${response.id}`);\n return;\n }\n\n this.requestCallbacks[response.id].resolve(response.responseData);\n delete this.requestCallbacks[response.id];\n }\n\n setup({\n logger,\n endpoint,\n isElementSelectable,\n cssSelectorAllowlist,\n actionClickAllowlist,\n }: {\n logger?: Logger;\n endpoint?: string;\n isElementSelectable?: (action: InitializeVisualTaggingSelectorData['actionType'], element: Element) => boolean;\n cssSelectorAllowlist?: string[];\n actionClickAllowlist?: string[];\n } = {}) {\n this.logger = logger;\n // If endpoint is customized, don't override it.\n if (endpoint && this.endpoint === AMPLITUDE_ORIGIN) {\n this.endpoint = endpoint;\n }\n let amplitudeVisualTaggingSelectorInstance: any = null;\n\n // Attach Event Listener to listen for messages from the parent window\n window.addEventListener('message', (event) => {\n this.logger?.debug?.('Message received: ', JSON.stringify(event));\n\n // Only accept messages from the specified origin\n if (this.endpoint !== event.origin) {\n return;\n }\n\n const eventData = event?.data as Message<Action> | MessageResponse;\n const action = eventData?.action;\n\n // Ignore messages without action\n if (!action) {\n return;\n }\n\n // If id exists, handle responses to previous requests\n if ('id' in eventData) {\n this.logger?.debug?.('Received Response to previous request: ', JSON.stringify(event));\n this.handleResponse(eventData);\n\n // If action exists, handle the action using existing handlers\n } else {\n if (action === 'ping') {\n this.notify({ action: 'pong' });\n } else if (action === 'initialize-visual-tagging-selector') {\n const actionData = eventData?.data as InitializeVisualTaggingSelectorData;\n asyncLoadScript(AMPLITUDE_VISUAL_TAGGING_SELECTOR_SCRIPT_URL)\n .then(() => {\n // eslint-disable-next-line\n amplitudeVisualTaggingSelectorInstance = (window as any)?.amplitudeVisualTaggingSelector?.({\n getEventTagProps,\n isElementSelectable: (element: Element) => {\n if (isElementSelectable) {\n return isElementSelectable(actionData?.actionType || 'click', element);\n }\n return true;\n },\n onTrack: this.onTrack,\n onSelect: this.onSelect,\n visualHighlightClass: AMPLITUDE_VISUAL_TAGGING_HIGHLIGHT_CLASS,\n messenger: this,\n cssSelectorAllowlist,\n actionClickAllowlist,\n });\n this.notify({ action: 'selector-loaded' });\n })\n .catch(() => {\n this.logger?.warn('Failed to initialize visual tagging selector');\n });\n } else if (action === 'close-visual-tagging-selector') {\n // eslint-disable-next-line\n amplitudeVisualTaggingSelectorInstance?.close?.();\n }\n }\n });\n\n // Notify the parent window that the page has loaded\n this.notify({ action: 'page-loaded' });\n }\n\n private onSelect = (data: ElementSelectedData) => {\n this.notify({ action: 'element-selected', data });\n };\n\n private onTrack = (type: string, properties: { [key: string]: string | null }) => {\n if (type === 'selector-mode-changed') {\n this.notify({ action: 'track-selector-mode-changed', data: properties });\n } else if (type === 'selector-moved') {\n this.notify({ action: 'track-selector-moved', data: properties });\n }\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"autocapture.d.ts","sourceRoot":"","sources":["../../../src/typings/autocapture.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,
|
|
1
|
+
{"version":3,"file":"autocapture.d.ts","sourceRoot":"","sources":["../../../src/typings/autocapture.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,aAAa,GAAG;IAC1B,GAAG,EAAE,MAAM,CAAC;IACZ,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,KAAK,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,CAAC;IAClC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,MAAM,MAAM,SAAS,GAAG,CAAC,aAAa,GAAG,IAAI,CAAC,EAAE,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"autocapture.js","sourceRoot":"","sources":["../../../src/typings/autocapture.ts"],"names":[],"mappings":"","sourcesContent":["export type
|
|
1
|
+
{"version":3,"file":"autocapture.js","sourceRoot":"","sources":["../../../src/typings/autocapture.ts"],"names":[],"mappings":"","sourcesContent":["export type HierarchyNode = {\n tag: string;\n id?: string;\n classes?: string[];\n attrs?: { [key: string]: string };\n index?: number;\n indexOfType?: number;\n prevSib?: string;\n};\n\nexport type Hierarchy = (HierarchyNode | null)[];\n"]}
|
package/lib/esm/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const VERSION = "1.0.
|
|
1
|
+
export declare const VERSION = "1.0.1";
|
|
2
2
|
//# sourceMappingURL=version.d.ts.map
|
package/lib/esm/version.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export var VERSION = '1.0.
|
|
1
|
+
export var VERSION = '1.0.1';
|
|
2
2
|
//# sourceMappingURL=version.js.map
|
package/lib/esm/version.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,IAAM,OAAO,GAAG,OAAO,CAAC","sourcesContent":["export const VERSION = '1.0.
|
|
1
|
+
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,IAAM,OAAO,GAAG,OAAO,CAAC","sourcesContent":["export const VERSION = '1.0.1';\n"]}
|