@adyen/adyen-web 6.18.1 → 6.20.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/README.md +1 -1
- package/dist/cjs/adyen.css +11 -8
- package/dist/cjs/adyen.css.map +1 -1
- package/dist/cjs/index.cjs +2 -2
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +43 -65
- package/dist/es/adyen.css +11 -8
- package/dist/es/adyen.css.map +1 -1
- package/dist/es/components/Ach/components/AchComponent.js +1 -1
- package/dist/es/components/Ach/components/AchComponent.js.map +1 -1
- package/dist/es/components/Ach/components/useSRPanelForACHErrors.js.map +1 -1
- package/dist/es/components/BankTransfer/BankTransfer.js +1 -1
- package/dist/es/components/BankTransfer/BankTransfer.js.map +1 -1
- package/dist/es/components/BankTransfer/components/BankTransferInput/BankTransferInput.js +1 -1
- package/dist/es/components/BankTransfer/components/BankTransferInput/BankTransferInput.js.map +1 -1
- package/dist/es/components/BankTransfer/components/BankTransferInput/validationRule.js +2 -0
- package/dist/es/components/BankTransfer/components/BankTransferInput/validationRule.js.map +1 -0
- package/dist/es/components/BankTransfer/components/BankTransferResult/BankTransferResult.js +1 -1
- package/dist/es/components/BankTransfer/components/BankTransferResult/BankTransferResult.js.map +1 -1
- package/dist/es/components/BankTransfer/components/BankTransferResult/BankTransferResultInstructions.js +2 -0
- package/dist/es/components/BankTransfer/components/BankTransferResult/BankTransferResultInstructions.js.map +1 -0
- package/dist/es/components/BankTransfer/components/BankTransferResult/BankTransferVoucher.js +2 -0
- package/dist/es/components/BankTransfer/components/BankTransferResult/BankTransferVoucher.js.map +1 -0
- package/dist/es/components/Card/components/CardInput/components/CardFieldsWrapper.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/components/Installments/Installments.js +1 -1
- package/dist/es/components/Card/components/CardInput/components/Installments/Installments.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/handlers.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/useSRPanelForCardInputErrors.js.map +1 -1
- package/dist/es/components/Dropin/Dropin.js +1 -1
- package/dist/es/components/Dropin/Dropin.js.map +1 -1
- package/dist/es/components/Dropin/components/PaymentMethod/PaymentMethodItem/PaymentMethodItem.js +1 -1
- package/dist/es/components/Dropin/components/PaymentMethod/PaymentMethodItem/PaymentMethodItem.js.map +1 -1
- package/dist/es/components/Giftcard/components/useSRPanelForGiftcardErrors.js.map +1 -1
- package/dist/es/components/PayPal/utils/get-paypal-styles.js.map +1 -1
- package/dist/es/components/PayPalFastlane/FastlaneSDK.js.map +1 -1
- package/dist/es/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.js.map +1 -1
- package/dist/es/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.js.map +1 -1
- package/dist/es/components/UPI/UPI.js +1 -1
- package/dist/es/components/UPI/UPI.js.map +1 -1
- package/dist/es/components/UPI/components/UPIComponent/UPIComponent.js +1 -1
- package/dist/es/components/UPI/components/UPIComponent/UPIComponent.js.map +1 -1
- package/dist/es/components/UPI/components/UPIIntentAppList/UPIIntentAppItem/UPIIntentAppItem.js +1 -1
- package/dist/es/components/UPI/components/UPIIntentAppList/UPIIntentAppItem/UPIIntentAppItem.js.map +1 -1
- package/dist/es/components/UPI/components/UPIIntentAppList/UPIIntentAppList.js +1 -1
- package/dist/es/components/UPI/components/UPIIntentAppList/UPIIntentAppList.js.map +1 -1
- package/dist/es/components/UPI/constants.js +2 -0
- package/dist/es/components/UPI/constants.js.map +1 -0
- package/dist/es/components/internal/Address/Address.js.map +1 -1
- package/dist/es/components/internal/Alert/Alert.js +1 -1
- package/dist/es/components/internal/Alert/Alert.js.map +1 -1
- package/dist/es/components/internal/Button/Button.js +1 -1
- package/dist/es/components/internal/Button/Button.js.map +1 -1
- package/dist/es/components/internal/Button/CopyIconButton.js +2 -0
- package/dist/es/components/internal/Button/CopyIconButton.js.map +1 -0
- package/dist/es/components/internal/ClickToPay/models/ShopperCard.js +1 -1
- package/dist/es/components/internal/ClickToPay/models/ShopperCard.js.map +1 -1
- package/dist/es/components/internal/DetailsTable/DetailsTable.js +1 -1
- package/dist/es/components/internal/DetailsTable/DetailsTable.js.map +1 -1
- package/dist/es/components/internal/FormFields/RadioGroupExtended/RadioGroupExtended.js.map +1 -1
- package/dist/es/components/internal/IbanInput/IbanInput.js.map +1 -1
- package/dist/es/components/internal/OpenInvoice/useSRPanelForOpenInvoiceErrors.js.map +1 -1
- package/dist/es/components/internal/QRLoader/QRLoader.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/SFP/SecuredFieldsProvider.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/binLookup/extensions.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/binLookup/triggerBinLookUp.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/lib/CSF/extensions/handleIOSTouchEvents.js.map +1 -1
- package/dist/es/components/internal/SegmentedControl/SegmentedControl.js.map +1 -1
- package/dist/es/components/internal/Tooltip/SingletonTooltipProvider.js +2 -0
- package/dist/es/components/internal/Tooltip/SingletonTooltipProvider.js.map +1 -0
- package/dist/es/components/internal/Tooltip/Tooltip.js +2 -0
- package/dist/es/components/internal/Tooltip/Tooltip.js.map +1 -0
- package/dist/es/components/internal/Tooltip/TooltipController.js +2 -0
- package/dist/es/components/internal/Tooltip/TooltipController.js.map +1 -0
- package/dist/es/components/internal/UIElement/UIElement.js +1 -1
- package/dist/es/components/internal/UIElement/UIElement.js.map +1 -1
- package/dist/es/components/internal/UIElement/utils.js.map +1 -1
- package/dist/es/components/internal/Voucher/Voucher.js.map +1 -1
- package/dist/es/core/Analytics/utils.js.map +1 -1
- package/dist/es/core/Errors/SRPanel.js.map +1 -1
- package/dist/es/core/Errors/utils.js.map +1 -1
- package/dist/es/core/Services/analytics/collect-id.js +1 -1
- package/dist/es/core/core.js +1 -1
- package/dist/es/core/core.registry.js.map +1 -1
- package/dist/es/core/utils.js.map +1 -1
- package/dist/es/external/preact/compat/dist/compat.js +2 -0
- package/dist/es/external/preact/compat/dist/compat.js.map +1 -0
- package/dist/es/external/preact/dist/preact.js.map +1 -1
- package/dist/es/index.d.ts +43 -65
- package/dist/es/language/utils.js.map +1 -1
- package/dist/es/utils/clipboard.js +1 -1
- package/dist/es/utils/clipboard.js.map +1 -1
- package/dist/es/utils/setFocus.js.map +1 -1
- package/dist/es/utils/useForm/reducer.js.map +1 -1
- package/dist/es-legacy/adyen.css +11 -8
- package/dist/es-legacy/adyen.css.map +1 -1
- package/dist/es-legacy/components/Ach/components/AchComponent.js +1 -1
- package/dist/es-legacy/components/Ach/components/AchComponent.js.map +1 -1
- package/dist/es-legacy/components/Ach/components/useSRPanelForACHErrors.js.map +1 -1
- package/dist/es-legacy/components/BankTransfer/BankTransfer.js +1 -1
- package/dist/es-legacy/components/BankTransfer/BankTransfer.js.map +1 -1
- package/dist/es-legacy/components/BankTransfer/components/BankTransferInput/BankTransferInput.js +1 -1
- package/dist/es-legacy/components/BankTransfer/components/BankTransferInput/BankTransferInput.js.map +1 -1
- package/dist/es-legacy/components/BankTransfer/components/BankTransferInput/validationRule.js +2 -0
- package/dist/es-legacy/components/BankTransfer/components/BankTransferInput/validationRule.js.map +1 -0
- package/dist/es-legacy/components/BankTransfer/components/BankTransferResult/BankTransferResult.js +1 -1
- package/dist/es-legacy/components/BankTransfer/components/BankTransferResult/BankTransferResult.js.map +1 -1
- package/dist/es-legacy/components/BankTransfer/components/BankTransferResult/BankTransferResultInstructions.js +2 -0
- package/dist/es-legacy/components/BankTransfer/components/BankTransferResult/BankTransferResultInstructions.js.map +1 -0
- package/dist/es-legacy/components/BankTransfer/components/BankTransferResult/BankTransferVoucher.js +2 -0
- package/dist/es-legacy/components/BankTransfer/components/BankTransferResult/BankTransferVoucher.js.map +1 -0
- package/dist/es-legacy/components/Card/components/CardInput/components/CardFieldsWrapper.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/Installments/Installments.js +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/components/Installments/Installments.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/handlers.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/useSRPanelForCardInputErrors.js.map +1 -1
- package/dist/es-legacy/components/Dropin/Dropin.js +1 -1
- package/dist/es-legacy/components/Dropin/Dropin.js.map +1 -1
- package/dist/es-legacy/components/Dropin/components/PaymentMethod/PaymentMethodItem/PaymentMethodItem.js +1 -1
- package/dist/es-legacy/components/Dropin/components/PaymentMethod/PaymentMethodItem/PaymentMethodItem.js.map +1 -1
- package/dist/es-legacy/components/Giftcard/components/useSRPanelForGiftcardErrors.js.map +1 -1
- package/dist/es-legacy/components/PayPal/utils/get-paypal-styles.js.map +1 -1
- package/dist/es-legacy/components/PayPalFastlane/FastlaneSDK.js.map +1 -1
- package/dist/es-legacy/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.js.map +1 -1
- package/dist/es-legacy/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.js.map +1 -1
- package/dist/es-legacy/components/UPI/UPI.js +1 -1
- package/dist/es-legacy/components/UPI/UPI.js.map +1 -1
- package/dist/es-legacy/components/UPI/components/UPIComponent/UPIComponent.js +1 -1
- package/dist/es-legacy/components/UPI/components/UPIComponent/UPIComponent.js.map +1 -1
- package/dist/es-legacy/components/UPI/components/UPIIntentAppList/UPIIntentAppItem/UPIIntentAppItem.js +1 -1
- package/dist/es-legacy/components/UPI/components/UPIIntentAppList/UPIIntentAppItem/UPIIntentAppItem.js.map +1 -1
- package/dist/es-legacy/components/UPI/components/UPIIntentAppList/UPIIntentAppList.js +1 -1
- package/dist/es-legacy/components/UPI/components/UPIIntentAppList/UPIIntentAppList.js.map +1 -1
- package/dist/es-legacy/components/UPI/constants.js +2 -0
- package/dist/es-legacy/components/UPI/constants.js.map +1 -0
- package/dist/es-legacy/components/internal/Address/Address.js.map +1 -1
- package/dist/es-legacy/components/internal/Alert/Alert.js +1 -1
- package/dist/es-legacy/components/internal/Alert/Alert.js.map +1 -1
- package/dist/es-legacy/components/internal/Button/Button.js +1 -1
- package/dist/es-legacy/components/internal/Button/Button.js.map +1 -1
- package/dist/es-legacy/components/internal/Button/CopyIconButton.js +2 -0
- package/dist/es-legacy/components/internal/Button/CopyIconButton.js.map +1 -0
- package/dist/es-legacy/components/internal/ClickToPay/models/ShopperCard.js +1 -1
- package/dist/es-legacy/components/internal/ClickToPay/models/ShopperCard.js.map +1 -1
- package/dist/es-legacy/components/internal/DetailsTable/DetailsTable.js +1 -1
- package/dist/es-legacy/components/internal/DetailsTable/DetailsTable.js.map +1 -1
- package/dist/es-legacy/components/internal/FormFields/RadioGroupExtended/RadioGroupExtended.js.map +1 -1
- package/dist/es-legacy/components/internal/IbanInput/IbanInput.js.map +1 -1
- package/dist/es-legacy/components/internal/OpenInvoice/useSRPanelForOpenInvoiceErrors.js.map +1 -1
- package/dist/es-legacy/components/internal/QRLoader/QRLoader.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/SFP/SecuredFieldsProvider.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/binLookup/extensions.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/binLookup/triggerBinLookUp.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/extensions/handleIOSTouchEvents.js.map +1 -1
- package/dist/es-legacy/components/internal/SegmentedControl/SegmentedControl.js.map +1 -1
- package/dist/es-legacy/components/internal/Tooltip/SingletonTooltipProvider.js +2 -0
- package/dist/es-legacy/components/internal/Tooltip/SingletonTooltipProvider.js.map +1 -0
- package/dist/es-legacy/components/internal/Tooltip/Tooltip.js +2 -0
- package/dist/es-legacy/components/internal/Tooltip/Tooltip.js.map +1 -0
- package/dist/es-legacy/components/internal/Tooltip/TooltipController.js +2 -0
- package/dist/es-legacy/components/internal/Tooltip/TooltipController.js.map +1 -0
- package/dist/es-legacy/components/internal/UIElement/UIElement.js +1 -1
- package/dist/es-legacy/components/internal/UIElement/UIElement.js.map +1 -1
- package/dist/es-legacy/components/internal/UIElement/utils.js.map +1 -1
- package/dist/es-legacy/components/internal/Voucher/Voucher.js.map +1 -1
- package/dist/es-legacy/core/Analytics/utils.js.map +1 -1
- package/dist/es-legacy/core/Errors/SRPanel.js.map +1 -1
- package/dist/es-legacy/core/Errors/utils.js.map +1 -1
- package/dist/es-legacy/core/Services/analytics/collect-id.js +1 -1
- package/dist/es-legacy/core/core.js +1 -1
- package/dist/es-legacy/core/core.registry.js.map +1 -1
- package/dist/es-legacy/core/utils.js.map +1 -1
- package/dist/es-legacy/external/preact/compat/dist/compat.js +2 -0
- package/dist/es-legacy/external/preact/compat/dist/compat.js.map +1 -0
- package/dist/es-legacy/external/preact/dist/preact.js.map +1 -1
- package/dist/es-legacy/language/utils.js.map +1 -1
- package/dist/es-legacy/utils/clipboard.js +1 -1
- package/dist/es-legacy/utils/clipboard.js.map +1 -1
- package/dist/es-legacy/utils/setFocus.js.map +1 -1
- package/dist/es-legacy/utils/useForm/reducer.js.map +1 -1
- package/package.json +159 -159
- package/styles/adyen.css +11 -8
- package/dist/es/components/UPI/components/UPIComponent/constants.js +0 -2
- package/dist/es/components/UPI/components/UPIComponent/constants.js.map +0 -1
- package/dist/es/components/UPI/components/UPIComponent/useUpiSegmentedControlOptions.js +0 -2
- package/dist/es/components/UPI/components/UPIComponent/useUpiSegmentedControlOptions.js.map +0 -1
- package/dist/es-legacy/components/UPI/components/UPIComponent/constants.js +0 -2
- package/dist/es-legacy/components/UPI/components/UPIComponent/constants.js.map +0 -1
- package/dist/es-legacy/components/UPI/components/UPIComponent/useUpiSegmentedControlOptions.js +0 -2
- package/dist/es-legacy/components/UPI/components/UPIComponent/useUpiSegmentedControlOptions.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SegmentedControl.js","sources":["../../../../../src/components/internal/SegmentedControl/SegmentedControl.tsx"],"sourcesContent":["import { h } from 'preact';\nimport cx from 'classnames';\nimport './SegmentedControl.scss';\n\
|
|
1
|
+
{"version":3,"file":"SegmentedControl.js","sources":["../../../../../src/components/internal/SegmentedControl/SegmentedControl.tsx"],"sourcesContent":["import { h } from 'preact';\nimport cx from 'classnames';\nimport './SegmentedControl.scss';\n\nexport interface SegmentedControlOption<T> {\n label: string;\n value: T;\n id: string;\n controls: string;\n htmlProps?: {};\n}\n\nexport type SegmentedControlOptions<T> = Array<SegmentedControlOption<T>>;\n\nexport interface SegmentedControlProps<T> {\n classNameModifiers?: string[];\n selectedValue: T;\n disabled?: boolean;\n options: SegmentedControlOptions<T>;\n onChange(value: T, event: MouseEvent): void;\n}\n\n/**\n *\n * example:\n * <SegmentedControl\n * onChange={(value) = setMode(value)}\n * selectedValue={mode}\n * disabled={status === 'loading'}\n * classNameModifiers={['css-class']}\n * options={segmentedControlOptions}\n * />\n *\n * @param classNameModifiers\n * @param selectedValue\n * @param disabled\n * @param options\n * @param onChange\n * @constructor\n */\nfunction SegmentedControl<T>({ classNameModifiers = [], selectedValue, disabled = false, options, onChange }: SegmentedControlProps<T>) {\n if (!options || options.length === 0) {\n return null;\n }\n\n return (\n <div\n className={cx(\n 'adyen-checkout__segmented-control',\n { 'adyen-checkout__segmented-control--disabled': disabled },\n ...classNameModifiers.map(modifier => `adyen-checkout__segmented-control--${modifier}`)\n )}\n role=\"group\"\n >\n {options.map(({ label, value, controls, htmlProps }: SegmentedControlOption<T>) => (\n <button\n disabled={disabled}\n key={value}\n onClick={(event: MouseEvent) => onChange(value, event)}\n className={cx('adyen-checkout__segmented-control-segment', {\n 'adyen-checkout__segmented-control-segment--selected': selectedValue === value\n })}\n aria-controls={controls}\n aria-expanded={selectedValue === value}\n type=\"button\"\n {...htmlProps}\n >\n {selectedValue === value && <span className=\"adyen-checkout-checkmark\"></span>}\n {label}\n </button>\n ))}\n </div>\n );\n}\n\nexport default SegmentedControl;\n"],"names":["SegmentedControl","classNameModifiers","selectedValue","disabled","options","onChange","length","h","div","className","cx","map","modifier","role","label","value","controls","htmlProps","button","key","onClick","event","aria-controls","aria-expanded","type","span"],"mappings":"0OAwCA,SAASA,GAAoBC,mBAAEA,EAAqB,GAAEC,cAAEA,EAAaC,SAAEA,GAAW,EAAKC,QAAEA,EAAOC,SAAEA,IAC9F,OAAKD,GAA8B,IAAnBA,EAAQE,OAKpBC,EAACC,MAAAA,CACGC,UAAWC,EACP,oCACA,CAAE,8CAA+CP,MAC9CF,EAAmBU,IAAIC,GAAY,sCAAsCA,MAEhFC,KAAK,SAEJT,EAAQO,IAAI,EAAGG,QAAOC,QAAOC,WAAUC,eACpCV,EAACW,2UAAAA,CAAAA,CACGf,SAAUA,EACVgB,IAAKJ,EACLK,QAAUC,GAAsBhB,EAASU,EAAOM,GAChDZ,UAAWC,EAAG,4CAA6C,CACvD,sDAAuDR,IAAkBa,IAE7EO,gBAAeN,EACfO,gBAAerB,IAAkBa,EACjCS,KAAK,UACDP,GAEHf,IAAkBa,GAASR,EAACkB,OAAAA,CAAKhB,UAAU,6BAC3CK,KA1BN,IA+Bf"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createContext as e,createElement as t}from"../../../external/preact/dist/preact.js";import{useState as r,useRef as o,useEffect as n,useMemo as i,useContext as s}from"../../../external/preact/hooks/dist/hooks.js";import{Tooltip as c}from"./Tooltip.js";import{TooltipController as l}from"./TooltipController.js";function u(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}const a=e(null),p=({children:e})=>{const[s,p]=r(null),f=o(l.tooltipId),m=o(!1),[,d]=r(0);n(()=>{const e=()=>{l.canRegisterTooltipHandler()?(l.registerTooltipHandler(p),m.current=!0,d(e=>e+1)):(m.current=!1,d(e=>e+1))};e();const t=l.onPrimaryReset(()=>{e()});return()=>{t(),m.current&&l.reset()}},[]);const b=i(()=>({showTooltip:e=>l.showTooltip(e),hideTooltip:e=>l.hideTooltip(e),id:f.current}),[]);return t(a.Provider,{value:b},e,m.current&&t(c,function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{},o=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(o=o.concat(Object.getOwnPropertySymbols(r).filter(function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable}))),o.forEach(function(t){u(e,t,r[t])})}return e}({id:f.current},s)))},f=()=>{const e=s(a);if(!e)throw new Error("useTooltip must be used within a TooltipProvider");return e};export{p as SingletonTooltipProvider,f as useTooltip};
|
|
2
|
+
//# sourceMappingURL=SingletonTooltipProvider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SingletonTooltipProvider.js","sources":["../../../../../src/components/internal/Tooltip/SingletonTooltipProvider.tsx"],"sourcesContent":["import { createContext, h, ComponentChildren } from 'preact';\nimport { useState, useEffect, useContext, useRef, useMemo } from 'preact/hooks';\nimport { Tooltip } from './Tooltip';\nimport { TooltipProps } from './types';\nimport { TooltipController } from './TooltipController';\n\ntype TooltipContextValue = {\n id: string;\n showTooltip: (state?: TooltipProps) => void;\n hideTooltip: () => void;\n};\n\nconst TooltipContext = createContext<TooltipContextValue | null>(null);\n\nconst SingletonTooltipProvider = ({ children }: { children?: ComponentChildren }) => {\n const [tooltipProps, setTooltipProps] = useState<TooltipProps | null>(null);\n const tooltipId = useRef(TooltipController.tooltipId);\n /**\n * We use `useRef` instead of `useState` to avoid triggering the `useEffect` again\n * (which would happen if `isPrimary` were a state value in the `useEffect` dependency list).\n * Because we need `TooltipController.onPrimaryReset` to add an event listener ONCE, we don't want\n * to re-run `useEffect` and register it again on every state update.\n *\n * However, we do need a way to re-render, hence added `forceUpdate`.\n */\n const isPrimaryInstanceRef = useRef(false);\n const [, forceUpdate] = useState(0);\n\n useEffect(() => {\n const tryRegister = () => {\n if (TooltipController.canRegisterTooltipHandler()) {\n TooltipController.registerTooltipHandler(setTooltipProps);\n isPrimaryInstanceRef.current = true;\n forceUpdate(r => r + 1);\n } else {\n isPrimaryInstanceRef.current = false;\n forceUpdate(r => r + 1);\n }\n };\n\n tryRegister();\n\n const unsubscribe = TooltipController.onPrimaryReset(() => {\n tryRegister();\n });\n\n return () => {\n // When the primary instance is unmounted, the only tooltip component is gone.\n // So we need to notify other instances, one of the instances should\n // become the primary instance to mount the tooltip component again.\n unsubscribe();\n if (isPrimaryInstanceRef.current) {\n TooltipController.reset();\n }\n };\n }, []);\n\n const contextValue = useMemo(\n () => ({\n showTooltip: (state?: TooltipProps) => TooltipController.showTooltip(state),\n hideTooltip: (state?: TooltipProps) => TooltipController.hideTooltip(state),\n id: tooltipId.current\n }),\n []\n );\n\n return (\n <TooltipContext.Provider value={contextValue}>\n {children}\n {isPrimaryInstanceRef.current && <Tooltip id={tooltipId.current} {...tooltipProps} />}\n </TooltipContext.Provider>\n );\n};\n\nconst useTooltip = () => {\n const ctx = useContext(TooltipContext);\n if (!ctx) {\n throw new Error('useTooltip must be used within a TooltipProvider');\n }\n return ctx;\n};\n\nexport { SingletonTooltipProvider, useTooltip };\n"],"names":["TooltipContext","createContext","SingletonTooltipProvider","children","tooltipProps","setTooltipProps","useState","tooltipId","useRef","TooltipController","isPrimaryInstanceRef","forceUpdate","useEffect","tryRegister","canRegisterTooltipHandler","registerTooltipHandler","current","r","unsubscribe","onPrimaryReset","reset","contextValue","useMemo","showTooltip","state","hideTooltip","id","h","Provider","value","Tooltip","useTooltip","ctx","useContext","Error"],"mappings":"qbAYA,MAAMA,EAAiBC,EAA0C,MAE3DC,EAA2B,EAAGC,eAChC,MAAOC,EAAcC,GAAmBC,EAA8B,MAChEC,EAAYC,EAAOC,EAAkBF,WASrCG,EAAuBF,GAAO,KAC3BG,GAAeL,EAAS,GAEjCM,EAAU,KACN,MAAMC,EAAc,KACZJ,EAAkBK,6BAClBL,EAAkBM,uBAAuBV,GACzCK,EAAqBM,SAAU,EAC/BL,EAAYM,GAAKA,EAAI,KAErBP,EAAqBM,SAAU,EAC/BL,EAAYM,GAAKA,EAAI,KAI7BJ,IAEA,MAAMK,EAAcT,EAAkBU,eAAe,KACjDN,MAGJ,MAAO,KAIHK,IACIR,EAAqBM,SACrBP,EAAkBW,UAG3B,IAEH,MAAMC,EAAeC,EACjB,KAAA,CACIC,YAAcC,GAAyBf,EAAkBc,YAAYC,GACrEC,YAAcD,GAAyBf,EAAkBgB,YAAYD,GACrEE,GAAInB,EAAUS,UAElB,IAGJ,OACIW,EAAC3B,EAAe4B,SAAQ,CAACC,MAAOR,GAC3BlB,EACAO,EAAqBM,SAAWW,EAACG,oUAAAA,CAAAA,CAAQJ,GAAInB,EAAUS,SAAaZ,MAK3E2B,EAAa,KACf,MAAMC,EAAMC,EAAWjC,GACvB,IAAKgC,EACD,MAAM,IAAIE,MAAM,oDAEpB,OAAOF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createElement as e}from"../../../external/preact/dist/preact.js";import{useRef as t,useState as o,useLayoutEffect as r,useEffect as n}from"../../../external/preact/hooks/dist/hooks.js";import{createPortal as i}from"../../../external/preact/compat/dist/compat.js";import s from"../../../_virtual/index.js";function l(l){const c=t(null),[a,d]=o("top"),[u,f]=o(!0),[p,v]=o({});return r(()=>{var e;if(!(null==l?void 0:l.visible)||!(null==l||null===(e=l.anchorRef)||void 0===e?void 0:e.current)||!c.current)return;const t=()=>{const e=l.anchorRef.current,t=c.current,o=e.getBoundingClientRect(),r=o.top+window.scrollY,n=o.left+window.scrollX,i=o.top,s=window.innerHeight-o.bottom;let a;a=i>=t.offsetHeight+8?"top":s>=t.offsetHeight+8||s>i?"bottom":"top";const u={position:"absolute",left:n+o.width/2,transform:"translateX(-50%)",willChange:"transform"};u.top="top"===a?r-t.offsetHeight-8:r+o.height+8,v(u),d(a)};return window.addEventListener("scroll",t,{capture:!0}),window.addEventListener("resize",t),t(),()=>{window.removeEventListener("scroll",t,{capture:!0}),window.removeEventListener("resize",t)}},[null==l?void 0:l.visible,null==l?void 0:l.anchorRef]),n(()=>{var e;const t=null==l||null===(e=l.anchorRef)||void 0===e?void 0:e.current;if(t&&"IntersectionObserver"in window){const e=new IntersectionObserver(([e])=>{f(e.isIntersecting)},{threshold:.1});return e.observe(t),()=>{e.disconnect()}}},[null==l?void 0:l.anchorRef]),i(e("div",{id:l.id,role:"tooltip","aria-live":"polite",className:s({"adyen-checkout-tooltip":!0,"adyen-checkout-tooltip--hidden":!l.visible||!u,[`adyen-checkout-tooltip--${a}`]:!0}),ref:c,style:p},l.text,e("div",{className:`adyen-checkout-tooltip-arrow adyen-checkout-tooltip-arrow--${a}`})),document.body)}export{l as Tooltip};
|
|
2
|
+
//# sourceMappingURL=Tooltip.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Tooltip.js","sources":["../../../../../src/components/internal/Tooltip/Tooltip.tsx"],"sourcesContent":["import { h } from 'preact';\nimport { useRef, useEffect, useState, useLayoutEffect } from 'preact/hooks';\nimport { createPortal } from 'preact/compat';\nimport cx from 'classnames';\nimport './Tooltip.scss';\nimport { TooltipPosition, TooltipProps } from './types';\n\n// 8px space between the target and the tooltip\nconst OFFSET = 8;\n\nexport function Tooltip(props: TooltipProps) {\n const tooltipRef = useRef<HTMLDivElement>(null);\n const [position, setPosition] = useState<TooltipPosition>('top');\n const [isAnchorVisible, setIsAnchorVisible] = useState<boolean>(true);\n const [style, setStyle] = useState({});\n\n useLayoutEffect(() => {\n if (!props?.visible || !props?.anchorRef?.current || !tooltipRef.current) return;\n\n const updatePosition = () => {\n const anchorEl = props.anchorRef.current;\n const tooltipEl = tooltipRef.current;\n const anchorRect = anchorEl.getBoundingClientRect();\n\n const offsetTop = anchorRect.top + window.scrollY;\n const offsetLeft = anchorRect.left + window.scrollX;\n const spaceAbove = anchorRect.top;\n const spaceBelow = window.innerHeight - anchorRect.bottom;\n\n let newPosition: TooltipPosition;\n if (spaceAbove >= tooltipEl.offsetHeight + OFFSET) {\n newPosition = 'top';\n } else if (spaceBelow >= tooltipEl.offsetHeight + OFFSET) {\n newPosition = 'bottom';\n } else {\n newPosition = spaceBelow > spaceAbove ? 'bottom' : 'top';\n }\n\n const newStyle: any = {\n position: 'absolute',\n left: offsetLeft + anchorRect.width / 2,\n transform: 'translateX(-50%)',\n willChange: 'transform'\n };\n newStyle.top = newPosition === 'top' ? offsetTop - tooltipEl.offsetHeight - OFFSET : offsetTop + anchorRect.height + OFFSET;\n\n setStyle(newStyle);\n setPosition(newPosition);\n };\n\n // We need {capture: true}, if the tooltip is placed inside scrollable containers because:\n // Scroll does not bubble. So if an element inside your page scrolls (like a <div> with overflow: scroll),\n // and you attach a scroll listener on the window without capture: true, it won’t catch those inner scrolls.\n window.addEventListener('scroll', updatePosition, { capture: true });\n window.addEventListener('resize', updatePosition);\n\n updatePosition();\n\n return () => {\n window.removeEventListener('scroll', updatePosition, { capture: true });\n window.removeEventListener('resize', updatePosition);\n };\n }, [props?.visible, props?.anchorRef]);\n\n // Hide the tooltip if it's not in the viewport.\n useEffect(() => {\n const anchor = props?.anchorRef?.current;\n if (!anchor) return;\n\n if ('IntersectionObserver' in window) {\n const observer = new IntersectionObserver(\n ([entry]) => {\n setIsAnchorVisible(entry.isIntersecting);\n },\n { threshold: 0.1 }\n );\n observer.observe(anchor);\n\n return () => {\n observer.disconnect();\n };\n }\n }, [props?.anchorRef]);\n\n return createPortal(\n <div\n id={props.id}\n role=\"tooltip\"\n aria-live={'polite'}\n className={cx({\n 'adyen-checkout-tooltip': true,\n 'adyen-checkout-tooltip--hidden': !props.visible || !isAnchorVisible,\n [`adyen-checkout-tooltip--${position}`]: true\n })}\n ref={tooltipRef}\n style={style}\n >\n {props.text}\n <div className={`adyen-checkout-tooltip-arrow adyen-checkout-tooltip-arrow--${position}`} />\n </div>,\n document.body\n );\n}\n"],"names":["Tooltip","props","tooltipRef","useRef","position","setPosition","useState","isAnchorVisible","setIsAnchorVisible","style","setStyle","useLayoutEffect","visible","anchorRef","current","updatePosition","anchorEl","tooltipEl","anchorRect","getBoundingClientRect","offsetTop","top","window","scrollY","offsetLeft","left","scrollX","spaceAbove","spaceBelow","innerHeight","bottom","newPosition","offsetHeight","newStyle","width","transform","willChange","height","addEventListener","capture","removeEventListener","useEffect","anchor","observer","IntersectionObserver","entry","isIntersecting","threshold","observe","disconnect","createPortal","h","div","id","role","aria-live","className","cx","ref","text","document","body"],"mappings":"wTAUO,SAASA,EAAQC,GACpB,MAAMC,EAAaC,EAAuB,OACnCC,EAAUC,GAAeC,EAA0B,QACnDC,EAAiBC,GAAsBF,GAAkB,IACzDG,EAAOC,GAAYJ,EAAS,CAAA,GAsEnC,OApEAK,EAAgB,KACYV,IAAAA,EAAxB,KAAKA,aAAAA,EAAAA,EAAOW,YAAYX,SAAgB,QAAhBA,EAAAA,EAAOY,qBAAPZ,OAAAA,EAAAA,EAAkBa,WAAYZ,EAAWY,QAAS,OAE1E,MAAMC,EAAiB,KACnB,MAAMC,EAAWf,EAAMY,UAAUC,QAC3BG,EAAYf,EAAWY,QACvBI,EAAaF,EAASG,wBAEtBC,EAAYF,EAAWG,IAAMC,OAAOC,QACpCC,EAAaN,EAAWO,KAAOH,OAAOI,QACtCC,EAAaT,EAAWG,IACxBO,EAAaN,OAAOO,YAAcX,EAAWY,OAEnD,IAAIC,EAEAA,EADAJ,GAAcV,EAAUe,aAtBzB,EAuBe,MACPJ,GAAcX,EAAUe,aAxBhC,GA2BeJ,EAAaD,EAFb,SAEqC,MAGvD,MAAMM,EAAgB,CAClB7B,SAAU,WACVqB,KAAMD,EAAaN,EAAWgB,MAAQ,EACtCC,UAAW,mBACXC,WAAY,aAEhBH,EAASZ,IAAsB,QAAhBU,EAAwBX,EAAYH,EAAUe,aApC1D,EAoCkFZ,EAAYF,EAAWmB,OApCzG,EAsCH3B,EAASuB,GACT5B,EAAY0B,IAWhB,OALAT,OAAOgB,iBAAiB,SAAUvB,EAAgB,CAAEwB,SAAS,IAC7DjB,OAAOgB,iBAAiB,SAAUvB,GAElCA,IAEO,KACHO,OAAOkB,oBAAoB,SAAUzB,EAAgB,CAAEwB,SAAS,IAChEjB,OAAOkB,oBAAoB,SAAUzB,KAE1C,CAACd,aAAAA,EAAAA,EAAOW,QAASX,aAAAA,EAAAA,EAAOY,YAG3B4B,EAAU,KACSxC,IAAAA,EAAf,MAAMyC,EAASzC,SAAgB,QAAhBA,EAAAA,EAAOY,iBAAPZ,IAAAA,OAAAA,EAAAA,EAAkBa,QACjC,GAAK4B,GAED,yBAA0BpB,OAAQ,CAClC,MAAMqB,EAAW,IAAIC,qBACjB,EAAEC,MACErC,EAAmBqC,EAAMC,iBAE7B,CAAEC,UAAW,KAIjB,OAFAJ,EAASK,QAAQN,GAEV,KACHC,EAASM,aAEjB,GACD,CAAChD,aAAAA,EAAAA,EAAOY,YAEJqC,EACHC,EAACC,MAAAA,CACGC,GAAIpD,EAAMoD,GACVC,KAAK,UACLC,YAAW,SACXC,UAAWC,EAAG,CACV,0BAA0B,EAC1B,kCAAmCxD,EAAMW,UAAYL,EACrD,CAAC,2BAA2BH,MAAa,IAE7CsD,IAAKxD,EACLO,MAAOA,GAENR,EAAM0D,KACPR,EAACC,MAAAA,CAAII,UAAW,8DAA8DpD,OAElFwD,SAASC,KAEjB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{getUniqueId as t}from"../../../utils/idGenerator.js";function e(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function r(t){for(var r=1;r<arguments.length;r++){var i=null!=arguments[r]?arguments[r]:{},o=Object.keys(i);"function"==typeof Object.getOwnPropertySymbols&&(o=o.concat(Object.getOwnPropertySymbols(i).filter(function(t){return Object.getOwnPropertyDescriptor(i,t).enumerable}))),o.forEach(function(r){e(t,r,i[r])})}return t}function i(t,e){return e=null!=e?e:{},Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(e)):function(t){var e=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e.push.apply(e,r)}return e}(Object(e)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(e,r))}),t}class o{static registerTooltipHandler(t){this.updateGlobalTooltip=t,this.registered=!0}static canRegisterTooltipHandler(){return!this.registered}static showTooltip(t){clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>this.updateGlobalTooltip(i(r({},t),{visible:!0})),this.DEFAULT_TIMEOUT)}static hideTooltip(t){clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>this.updateGlobalTooltip(i(r({},t),{visible:!1})),this.DEFAULT_TIMEOUT)}static reset(){this.registered=!1,this.updateGlobalTooltip=()=>{},this.notifyPrimaryReset()}static notifyPrimaryReset(){this.eventTarget.dispatchEvent(new Event(o.PRIMARY_TOOLTIP_RESET_EVENT))}static onPrimaryReset(t){return this.eventTarget.addEventListener(o.PRIMARY_TOOLTIP_RESET_EVENT,t),()=>this.eventTarget.removeEventListener(o.PRIMARY_TOOLTIP_RESET_EVENT,t)}}e(o,"tooltipId",t("adyen-checkout-tooltip")),e(o,"DEFAULT_TIMEOUT",100),e(o,"PRIMARY_TOOLTIP_RESET_EVENT","primary-tooltip-reset"),e(o,"timeoutId",null),e(o,"registered",!1),e(o,"updateGlobalTooltip",()=>{}),e(o,"eventTarget",new EventTarget);export{o as TooltipController};
|
|
2
|
+
//# sourceMappingURL=TooltipController.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"TooltipController.js","sources":["../../../../../src/components/internal/Tooltip/TooltipController.ts"],"sourcesContent":["import { TooltipProps } from './types';\nimport { getUniqueId } from '../../../utils/idGenerator';\n\ntype setTooltipState = (state: TooltipProps | null) => void;\n\nexport class TooltipController {\n public static readonly tooltipId = getUniqueId('adyen-checkout-tooltip');\n private static readonly DEFAULT_TIMEOUT = 100;\n private static readonly PRIMARY_TOOLTIP_RESET_EVENT = 'primary-tooltip-reset';\n private static timeoutId: ReturnType<typeof setTimeout> | null = null;\n private static registered = false;\n private static updateGlobalTooltip: setTooltipState = () => {};\n private static eventTarget = new EventTarget();\n\n public static registerTooltipHandler(fn: setTooltipState): void {\n this.updateGlobalTooltip = fn;\n this.registered = true;\n }\n\n public static canRegisterTooltipHandler(): boolean {\n return !this.registered;\n }\n\n public static showTooltip(state?: TooltipProps) {\n clearTimeout(this.timeoutId);\n this.timeoutId = setTimeout(() => this.updateGlobalTooltip({ ...state, visible: true }), this.DEFAULT_TIMEOUT);\n }\n\n public static hideTooltip(state?: TooltipProps) {\n clearTimeout(this.timeoutId);\n this.timeoutId = setTimeout(() => this.updateGlobalTooltip({ ...state, visible: false }), this.DEFAULT_TIMEOUT);\n }\n\n public static reset() {\n this.registered = false;\n this.updateGlobalTooltip = () => {};\n this.notifyPrimaryReset();\n }\n\n private static notifyPrimaryReset() {\n this.eventTarget.dispatchEvent(new Event(TooltipController.PRIMARY_TOOLTIP_RESET_EVENT));\n }\n\n public static onPrimaryReset(callback: () => void) {\n this.eventTarget.addEventListener(TooltipController.PRIMARY_TOOLTIP_RESET_EVENT, callback);\n return () => this.eventTarget.removeEventListener(TooltipController.PRIMARY_TOOLTIP_RESET_EVENT, callback);\n }\n}\n"],"names":["TooltipController","registerTooltipHandler","fn","this","updateGlobalTooltip","registered","canRegisterTooltipHandler","showTooltip","state","clearTimeout","timeoutId","setTimeout","_object_spread_props","_object_spread","visible","DEFAULT_TIMEOUT","hideTooltip","reset","notifyPrimaryReset","eventTarget","dispatchEvent","Event","PRIMARY_TOOLTIP_RESET_EVENT","onPrimaryReset","callback","addEventListener","removeEventListener","_define_property","tooltipId","getUniqueId","EventTarget"],"mappings":"q2BAKO,MAAMA,EAST,6BAAcC,CAAuBC,GACjCC,KAAKC,oBAAsBF,EAC3BC,KAAKE,YAAa,CACtB,CAEA,gCAAcC,GACV,OAAQH,KAAKE,UACjB,CAEA,kBAAcE,CAAYC,GACtBC,aAAaN,KAAKO,WAClBP,KAAKO,UAAYC,WAAW,IAAMR,KAAKC,oBAAoBQ,EAAAC,EAAA,GAAKL,GAAAA,CAAOM,SAAS,KAASX,KAAKY,gBAClG,CAEA,kBAAcC,CAAYR,GACtBC,aAAaN,KAAKO,WAClBP,KAAKO,UAAYC,WAAW,IAAMR,KAAKC,oBAAoBQ,EAAAC,EAAA,GAAKL,GAAAA,CAAOM,SAAS,KAAUX,KAAKY,gBACnG,CAEA,YAAcE,GACVd,KAAKE,YAAa,EAClBF,KAAKC,oBAAsB,OAC3BD,KAAKe,oBACT,CAEA,yBAAeA,GACXf,KAAKgB,YAAYC,cAAc,IAAIC,MAAMrB,EAAkBsB,6BAC/D,CAEA,qBAAcC,CAAeC,GAEzB,OADArB,KAAKgB,YAAYM,iBAAiBzB,EAAkBsB,4BAA6BE,GAC1E,IAAMrB,KAAKgB,YAAYO,oBAAoB1B,EAAkBsB,4BAA6BE,EACrG,EAxCAG,EADS3B,EACc4B,YAAYC,EAAY,2BAC/CF,EAFS3B,EAEee,kBAAkB,KAC1CY,EAHS3B,EAGesB,8BAA8B,yBACtDK,EAJS3B,EAIMU,YAAkD,MACjEiB,EALS3B,EAKMK,cAAa,GAC5BsB,EANS3B,EAMMI,sBAAuC,QACtDuB,EAPS3B,EAOMmB,cAAc,IAAIW"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createElement as t}from"../../../external/preact/dist/preact.js";import e from"../BaseElement/BaseElement.js";import s from"../PayButton/PayButton.js";import{assertIsDropin as i,getRegulatoryDefaults as n,sanitizeResponse as o,verifyPaymentDidNotFail as r,cleanupFinalResult as a}from"./utils.js";import l,{NETWORK_ERROR as h}from"../../../core/Errors/AdyenCheckoutError.js";import{hasOwnProperty as d}from"../../../utils/hasOwnProperty.js";import{ANALYTICS_SUBMIT_STR as c,ANALYTICS_ERROR_TYPE as p}from"../../../core/Analytics/constants.js";import m from"../../../core/Errors/CancelError.js";import{AnalyticsLogEvent as u}from"../../../core/Analytics/AnalyticsLogEvent.js";import{AnalyticsErrorEvent as y}from"../../../core/Analytics/AnalyticsErrorEvent.js";function f(t,e,s){return e in t?Object.defineProperty(t,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}function b(t){for(var e=1;e<arguments.length;e++){var s=null!=arguments[e]?arguments[e]:{},i=Object.keys(s);"function"==typeof Object.getOwnPropertySymbols&&(i=i.concat(Object.getOwnPropertySymbols(s).filter(function(t){return Object.getOwnPropertyDescriptor(s,t).enumerable}))),i.forEach(function(e){f(t,e,s[e])})}return t}function v(t,e){return e=null!=e?e:{},Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(e)):function(t){var e=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e.push.apply(e,s)}return e}(Object(e)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(e,s))}),t}class R extends e{buildElementProps(t){const e=b({showPayButton:!0},this.core.getCorePropsForComponent(),!!(null==t?void 0:t.isStoredPaymentMethod)?{}:this.getPaymentMethodFromPaymentMethodsResponse(null==t?void 0:t.type),t),s=i(this);this.props=this.formatProps(b({},this.constructor.defaultProps,n(this.core.options.countryCode,s),e))}getPaymentMethodFromPaymentMethodsResponse(t){return this.core.paymentMethodsResponse.find(t||this.constructor.type)}storeElementRefOnCore(t){(null==t?void 0:t.isDropin)||this.core.storeElementReference(this)}isAvailable(){return Promise.resolve()}setState(t){this.state=b({},this.state,t),this.onChange()}showValidation(){return this.componentRef&&this.componentRef.showValidation&&this.componentRef.showValidation(),this}setElementStatus(t,e){var s;return null===(s=this.elementRef)||void 0===s||s.setStatus(t,e),this}setStatus(t,e){var s;return(null===(s=this.componentRef)||void 0===s?void 0:s.setStatus)&&this.componentRef.setStatus(t,e),this}onChange(){var t,e;null===(t=(e=this.props).onChange)||void 0===t||t.call(e,{data:this.data,isValid:this.isValid,errors:this.state.errors,valid:this.state.valid},this.elementRef)}setUpAnalytics(t){var e;const s=null===(e=this.props.session)||void 0===e?void 0:e.id;return this.props.modules.analytics.setUp(b({},t,s&&{sessionId:s}))}submitAnalytics(t){try{t.component=this.getComponent(t),this.props.modules.analytics.sendAnalytics(t)}catch(t){console.warn("Failed to submit the analytics event. Error:",t)}}getComponent({component:t}){return t||(this.constructor.analyticsType?this.constructor.analyticsType:"scheme"===this.constructor.type||"bcmc"===this.constructor.type?this.constructor.type:this.type)}submit(){this.isValid?this.makePaymentsCall().then(o).then(r).then(this.handleResponse).catch(t=>{t instanceof m?this.setElementStatus("ready"):this.handleFailedResult(t)}):this.showValidation()}makePaymentsCall(){if(this.setElementStatus("loading"),this.props.onSubmit)return this.submitUsingAdvancedFlow();if(this.core.session){return(this.props.beforeSubmit?new Promise((t,e)=>this.props.beforeSubmit(this.data,this.elementRef,{resolve:t,reject:()=>e(new m("beforeSubmitRejected"))})):Promise.resolve(this.data)).then(this.submitUsingSessionsFlow)}this.handleError(new l("IMPLEMENTATION_ERROR",'It can not perform /payments call. Callback "onSubmit" is missing or Checkout session is not available'))}async submitUsingAdvancedFlow(){return new Promise((t,e)=>{const s=new u({type:c,message:"Shopper clicked pay"});this.submitAnalytics(s),this.props.onSubmit({data:this.data,isValid:this.isValid},this.elementRef,{resolve:t,reject:e})})}async submitUsingSessionsFlow(t){const e=new u({type:c,message:"Shopper clicked pay"});this.submitAnalytics(e);try{return await this.core.session.submitPayment(t)}catch(t){return t instanceof l?this.handleError(t):this.handleError(new l("ERROR","Error when making /payments call",{cause:t})),Promise.reject(t)}}onComplete(t){this.props.onComplete&&this.props.onComplete(t,this.elementRef)}handleAdditionalDetails(t){this.makeAdditionalDetailsCall(t).then(o).then(r).then(this.handleResponse).catch(this.handleFailedResult)}makeAdditionalDetailsCall(t){return this.props.onAdditionalDetails?new Promise((e,s)=>{this.props.onAdditionalDetails(t,this.elementRef,{resolve:e,reject:s})}):this.core.session?this.submitAdditionalDetailsUsingSessionsFlow(t.data):void this.handleError(new l("IMPLEMENTATION_ERROR",'It can not perform /payments/details call. Callback "onAdditionalDetails" is missing or Checkout session is not available'))}async submitAdditionalDetailsUsingSessionsFlow(t){try{return await this.core.session.submitDetails(t)}catch(t){return t instanceof l?this.handleError(t):this.handleError(new l("ERROR","Error when making /details call",{cause:t})),Promise.reject(t)}}handleAction(t,e={}){if(!t||!t.type){if(d(t,"action")&&d(t,"resultCode"))throw new Error('handleAction::Invalid Action - the passed action object itself has an "action" property and a "resultCode": have you passed in the whole response object by mistake?');throw new Error('handleAction::Invalid Action - the passed action object does not have a "type" property')}const s=this.core.createFromAction(t,v(b({},this.elementRef.props,e),{onAdditionalDetails:this.handleAdditionalDetails}));return s?(this.unmount(),s.mount(this._node)):null}onActionHandled(t){var e,s;null===(s=this.props)||void 0===s||null===(e=s.onActionHandled)||void 0===e||e.call(s,b({originalAction:this.props.originalAction},t))}handleResponse(t){var e,s;t.action?this.elementRef.handleAction(t.action):(null===(s=t.order)||void 0===s||null===(e=s.remainingAmount)||void 0===e?void 0:e.value)>0?this.handleOrder(t):this.handleSuccessResult(t)}handleKeyPress(t){var e;"Enter"!==t.key&&"Enter"!==t.code||(t.preventDefault(),this.onEnterKeyPressed(null===(e=document)||void 0===e?void 0:e.activeElement,this))}onEnterKeyPressed(t,e){this.props.onEnterKeyPressed?this.props.onEnterKeyPressed(t,e):(t.blur(),this.submit())}updateParent(t={}){return this.elementRef.core.update(t)}get isValid(){return!1}get icon(){const t=this.props.paymentMethodType||this.type;var e;return null!==(e=this.props.icon)&&void 0!==e?e:this.resources.getImage()(t)}get displayName(){var t,e;const s=null===(e=this.core.paymentMethodsResponse)||void 0===e||null===(t=e.paymentMethods)||void 0===t?void 0:t.find(t=>t.type===this.type);return this.props.name||(null==s?void 0:s.name)||this.type}get accessibleName(){return this.displayName}get additionalInfo(){return null}get type(){return this.props.type||this.constructor.type}async handleAdvanceFlowPaymentMethodsUpdate(t,e){return new Promise((e,s)=>{if(!this.props.onPaymentMethodsRequest)return e();this.props.onPaymentMethodsRequest(v(b({},t&&{order:{orderData:t.orderData,pspReference:t.pspReference}}),{locale:this.core.options.locale}),{resolve:e,reject:s})}).catch(t=>{this.handleError(new l("IMPLEMENTATION_ERROR","Something failed during payment methods update or onPaymentMethodsRequest was not implemented",{cause:t}))}).then(s=>this.core.update(v(b({},s&&{paymentMethodsResponse:s}),{order:t,amount:t?t.remainingAmount:e})))}constructor(e,n){super(e,n),f(this,"componentRef",void 0),f(this,"resources",void 0),f(this,"elementRef",void 0),f(this,"handleError",t=>{if(this.setElementStatus("ready"),t.name===h&&t.options.code){const e=new y({errorType:p.apiError,code:t.options.code});this.submitAnalytics(e)}this.props.onError&&this.props.onError(t,this.elementRef)}),f(this,"handleOrder",t=>{const{order:e}=t;(this.core.session?this.core.update({order:e}):this.handleAdvanceFlowPaymentMethodsUpdate(e)).then(()=>{var t,s;null===(t=(s=this.props).onOrderUpdated)||void 0===t||t.call(s,{order:e})})}),f(this,"handleFailedResult",t=>{var e,s;i(this.elementRef)&&this.elementRef.displayFinalAnimation("error"),a(t),null===(e=(s=this.props).onPaymentFailed)||void 0===e||e.call(s,t,this.elementRef)}),f(this,"handleSuccessResult",t=>{var e,s;i(this.elementRef)&&this.elementRef.displayFinalAnimation("success"),a(t),null===(e=(s=this.props).onPaymentCompleted)||void 0===e||e.call(s,t,this.elementRef)}),f(this,"setComponentRef",t=>{this.componentRef=t}),f(this,"payButton",e=>t(s,v(b({},e),{amount:this.props.amount,secondaryAmount:this.props.secondaryAmount,onClick:this.submit}))),this.core.register(this.constructor),this.submit=this.submit.bind(this),this.setState=this.setState.bind(this),this.onComplete=this.onComplete.bind(this),this.handleAction=this.handleAction.bind(this),this.handleOrder=this.handleOrder.bind(this),this.handleAdditionalDetails=this.handleAdditionalDetails.bind(this),this.handleResponse=this.handleResponse.bind(this),this.setElementStatus=this.setElementStatus.bind(this),this.submitAnalytics=this.submitAnalytics.bind(this),this.makePaymentsCall=this.makePaymentsCall.bind(this),this.makeAdditionalDetailsCall=this.makeAdditionalDetailsCall.bind(this),this.submitUsingSessionsFlow=this.submitUsingSessionsFlow.bind(this),this.elementRef=n&&n.elementRef||this,this.resources=this.props.modules?this.props.modules.resources:void 0,this.storeElementRefOnCore(this.props),this.onEnterKeyPressed=this.onEnterKeyPressed.bind(this),this.onActionHandled=this.onActionHandled.bind(this)}}f(R,"type",void 0),f(R,"txVariants",[]);export{R as UIElement,R as default};
|
|
1
|
+
import{createElement as t}from"../../../external/preact/dist/preact.js";import e from"../BaseElement/BaseElement.js";import s from"../PayButton/PayButton.js";import{assertIsDropin as i,getRegulatoryDefaults as n,sanitizeResponse as o,verifyPaymentDidNotFail as r,cleanupFinalResult as a}from"./utils.js";import l,{NETWORK_ERROR as h}from"../../../core/Errors/AdyenCheckoutError.js";import{hasOwnProperty as d}from"../../../utils/hasOwnProperty.js";import{ANALYTICS_SUBMIT_STR as c,ANALYTICS_ERROR_TYPE as p}from"../../../core/Analytics/constants.js";import m from"../../../core/Errors/CancelError.js";import{AnalyticsLogEvent as u}from"../../../core/Analytics/AnalyticsLogEvent.js";import{AnalyticsErrorEvent as y}from"../../../core/Analytics/AnalyticsErrorEvent.js";function f(t,e,s){return e in t?Object.defineProperty(t,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}function b(t){for(var e=1;e<arguments.length;e++){var s=null!=arguments[e]?arguments[e]:{},i=Object.keys(s);"function"==typeof Object.getOwnPropertySymbols&&(i=i.concat(Object.getOwnPropertySymbols(s).filter(function(t){return Object.getOwnPropertyDescriptor(s,t).enumerable}))),i.forEach(function(e){f(t,e,s[e])})}return t}function v(t,e){return e=null!=e?e:{},Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(e)):function(t){var e=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e.push.apply(e,s)}return e}(Object(e)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(e,s))}),t}class R extends e{buildElementProps(t){const e=b({showPayButton:!0},this.core.getCorePropsForComponent(),!!(null==t?void 0:t.isStoredPaymentMethod)?{}:this.getPaymentMethodFromPaymentMethodsResponse(null==t?void 0:t.type),t),s=i(this);this.props=this.formatProps(b({},this.constructor.defaultProps,n(this.core.options.countryCode,s),e))}getPaymentMethodFromPaymentMethodsResponse(t){var e;return null===(e=this.core.paymentMethodsResponse)||void 0===e?void 0:e.find(t||this.constructor.type)}storeElementRefOnCore(t){(null==t?void 0:t.isDropin)||this.core.storeElementReference(this)}isAvailable(){return Promise.resolve()}setState(t){this.state=b({},this.state,t),this.onChange()}showValidation(){return this.componentRef&&this.componentRef.showValidation&&this.componentRef.showValidation(),this}setElementStatus(t,e){var s;return null===(s=this.elementRef)||void 0===s||s.setStatus(t,e),this}setStatus(t,e){var s;return(null===(s=this.componentRef)||void 0===s?void 0:s.setStatus)&&this.componentRef.setStatus(t,e),this}onChange(){var t,e;null===(t=(e=this.props).onChange)||void 0===t||t.call(e,{data:this.data,isValid:this.isValid,errors:this.state.errors,valid:this.state.valid},this.elementRef)}setUpAnalytics(t){var e;const s=null===(e=this.props.session)||void 0===e?void 0:e.id;return this.props.modules.analytics.setUp(b({},t,s&&{sessionId:s}))}submitAnalytics(t){try{t.component=this.getComponent(t),this.props.modules.analytics.sendAnalytics(t)}catch(t){console.warn("Failed to submit the analytics event. Error:",t)}}getComponent({component:t}){return t||(this.constructor.analyticsType?this.constructor.analyticsType:"scheme"===this.constructor.type||"bcmc"===this.constructor.type?this.constructor.type:this.type)}submit(){this.isValid?this.makePaymentsCall().then(o).then(r).then(this.handleResponse).catch(t=>{t instanceof m?this.setElementStatus("ready"):this.handleFailedResult(t)}):this.showValidation()}makePaymentsCall(){if(this.setElementStatus("loading"),this.props.onSubmit)return this.submitUsingAdvancedFlow();if(this.core.session){return(this.props.beforeSubmit?new Promise((t,e)=>this.props.beforeSubmit(this.data,this.elementRef,{resolve:t,reject:()=>e(new m("beforeSubmitRejected"))})):Promise.resolve(this.data)).then(this.submitUsingSessionsFlow)}this.handleError(new l("IMPLEMENTATION_ERROR",'It can not perform /payments call. Callback "onSubmit" is missing or Checkout session is not available'))}async submitUsingAdvancedFlow(){return new Promise((t,e)=>{const s=new u({type:c,message:"Shopper clicked pay"});this.submitAnalytics(s),this.props.onSubmit({data:this.data,isValid:this.isValid},this.elementRef,{resolve:t,reject:e})})}async submitUsingSessionsFlow(t){const e=new u({type:c,message:"Shopper clicked pay"});this.submitAnalytics(e);try{return await this.core.session.submitPayment(t)}catch(t){return t instanceof l?this.handleError(t):this.handleError(new l("ERROR","Error when making /payments call",{cause:t})),Promise.reject(t)}}onComplete(t){this.props.onComplete&&this.props.onComplete(t,this.elementRef)}handleAdditionalDetails(t){this.makeAdditionalDetailsCall(t).then(o).then(r).then(this.handleResponse).catch(this.handleFailedResult)}makeAdditionalDetailsCall(t){return this.props.onAdditionalDetails?new Promise((e,s)=>{this.props.onAdditionalDetails(t,this.elementRef,{resolve:e,reject:s})}):this.core.session?this.submitAdditionalDetailsUsingSessionsFlow(t.data):void this.handleError(new l("IMPLEMENTATION_ERROR",'It can not perform /payments/details call. Callback "onAdditionalDetails" is missing or Checkout session is not available'))}async submitAdditionalDetailsUsingSessionsFlow(t){try{return await this.core.session.submitDetails(t)}catch(t){return t instanceof l?this.handleError(t):this.handleError(new l("ERROR","Error when making /details call",{cause:t})),Promise.reject(t)}}handleAction(t,e={}){if(!t||!t.type){if(d(t,"action")&&d(t,"resultCode"))throw new Error('handleAction::Invalid Action - the passed action object itself has an "action" property and a "resultCode": have you passed in the whole response object by mistake?');throw new Error('handleAction::Invalid Action - the passed action object does not have a "type" property')}const s=this.core.createFromAction(t,v(b({},this.elementRef.props,e),{onAdditionalDetails:this.handleAdditionalDetails}));return s?(this.unmount(),s.mount(this._node)):null}onActionHandled(t){var e,s;null===(s=this.props)||void 0===s||null===(e=s.onActionHandled)||void 0===e||e.call(s,b({originalAction:this.props.originalAction},t))}handleResponse(t){var e,s;t.action?this.elementRef.handleAction(t.action):(null===(s=t.order)||void 0===s||null===(e=s.remainingAmount)||void 0===e?void 0:e.value)>0?this.handleOrder(t):this.handleSuccessResult(t)}handleKeyPress(t){var e;"Enter"!==t.key&&"Enter"!==t.code||(t.preventDefault(),this.onEnterKeyPressed(null===(e=document)||void 0===e?void 0:e.activeElement,this))}onEnterKeyPressed(t,e){this.props.onEnterKeyPressed?this.props.onEnterKeyPressed(t,e):(t.blur(),this.submit())}updateParent(t={}){return this.elementRef.core.update(t)}get isValid(){return!1}get icon(){const t=this.props.paymentMethodType||this.type;var e;return null!==(e=this.props.icon)&&void 0!==e?e:this.resources.getImage()(t)}get displayName(){var t,e;const s=null===(e=this.core.paymentMethodsResponse)||void 0===e||null===(t=e.paymentMethods)||void 0===t?void 0:t.find(t=>t.type===this.type);return this.props.name||(null==s?void 0:s.name)||this.type}get accessibleName(){return this.displayName}get additionalInfo(){return null}get type(){return this.props.type||this.constructor.type}async handleAdvanceFlowPaymentMethodsUpdate(t,e){return new Promise((e,s)=>{if(!this.props.onPaymentMethodsRequest)return e();this.props.onPaymentMethodsRequest(v(b({},t&&{order:{orderData:t.orderData,pspReference:t.pspReference}}),{locale:this.core.options.locale}),{resolve:e,reject:s})}).catch(t=>{this.handleError(new l("IMPLEMENTATION_ERROR","Something failed during payment methods update or onPaymentMethodsRequest was not implemented",{cause:t}))}).then(s=>this.core.update(v(b({},s&&{paymentMethodsResponse:s}),{order:t,amount:t?t.remainingAmount:e})))}constructor(e,n){super(e,n),f(this,"componentRef",void 0),f(this,"resources",void 0),f(this,"elementRef",void 0),f(this,"handleError",t=>{if(this.setElementStatus("ready"),t.name===h&&t.options.code){const e=new y({errorType:p.apiError,code:t.options.code});this.submitAnalytics(e)}this.props.onError&&this.props.onError(t,this.elementRef)}),f(this,"handleOrder",t=>{const{order:e}=t;(this.core.session?this.core.update({order:e}):this.handleAdvanceFlowPaymentMethodsUpdate(e)).then(()=>{var t,s;null===(t=(s=this.props).onOrderUpdated)||void 0===t||t.call(s,{order:e})})}),f(this,"handleFailedResult",t=>{var e,s;i(this.elementRef)&&this.elementRef.displayFinalAnimation("error"),a(t),null===(e=(s=this.props).onPaymentFailed)||void 0===e||e.call(s,t,this.elementRef)}),f(this,"handleSuccessResult",t=>{var e,s;i(this.elementRef)&&this.elementRef.displayFinalAnimation("success"),a(t),null===(e=(s=this.props).onPaymentCompleted)||void 0===e||e.call(s,t,this.elementRef)}),f(this,"setComponentRef",t=>{this.componentRef=t}),f(this,"payButton",e=>t(s,v(b({},e),{amount:this.props.amount,secondaryAmount:this.props.secondaryAmount,onClick:this.submit}))),this.core.register(this.constructor),this.submit=this.submit.bind(this),this.setState=this.setState.bind(this),this.onComplete=this.onComplete.bind(this),this.handleAction=this.handleAction.bind(this),this.handleOrder=this.handleOrder.bind(this),this.handleAdditionalDetails=this.handleAdditionalDetails.bind(this),this.handleResponse=this.handleResponse.bind(this),this.setElementStatus=this.setElementStatus.bind(this),this.submitAnalytics=this.submitAnalytics.bind(this),this.makePaymentsCall=this.makePaymentsCall.bind(this),this.makeAdditionalDetailsCall=this.makeAdditionalDetailsCall.bind(this),this.submitUsingSessionsFlow=this.submitUsingSessionsFlow.bind(this),this.elementRef=n&&n.elementRef||this,this.resources=this.props.modules?this.props.modules.resources:void 0,this.storeElementRefOnCore(this.props),this.onEnterKeyPressed=this.onEnterKeyPressed.bind(this),this.onActionHandled=this.onActionHandled.bind(this)}}f(R,"type",void 0),f(R,"txVariants",[]);export{R as UIElement,R as default};
|
|
2
2
|
//# sourceMappingURL=UIElement.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UIElement.js","sources":["../../../../../src/components/internal/UIElement/UIElement.tsx"],"sourcesContent":["import { h } from 'preact';\nimport BaseElement from '../BaseElement/BaseElement';\nimport PayButton from '../PayButton';\nimport { assertIsDropin, cleanupFinalResult, getRegulatoryDefaults, sanitizeResponse, verifyPaymentDidNotFail } from './utils';\nimport AdyenCheckoutError, { NETWORK_ERROR } from '../../../core/Errors/AdyenCheckoutError';\nimport { hasOwnProperty } from '../../../utils/hasOwnProperty';\nimport { Resources } from '../../../core/Context/Resources';\nimport { ANALYTICS_ERROR_TYPE, ANALYTICS_SUBMIT_STR } from '../../../core/Analytics/constants';\n\nimport { AnalyticsInitialEvent } from '../../../core/Analytics/types';\nimport type { CoreConfiguration, ICore, AdditionalDetailsData } from '../../../core/types';\nimport type { ComponentMethodsRef, PayButtonFunctionProps, UIElementProps, UIElementStatus } from './types';\nimport type { CheckoutSessionDetailsResponse, CheckoutSessionPaymentResponse } from '../../../core/CheckoutSession/types';\nimport type {\n ActionHandledReturnObject,\n CheckoutAdvancedFlowResponse,\n Order,\n PaymentAction,\n PaymentAmount,\n PaymentData,\n PaymentMethod,\n PaymentMethodsResponse,\n PaymentResponseData\n} from '../../../types/global-types';\nimport type { IDropin } from '../../Dropin/types';\nimport type { NewableComponent } from '../../../core/core.registry';\nimport CancelError from '../../../core/Errors/CancelError';\n\nimport './UIElement.scss';\nimport { AnalyticsEvent } from '../../../core/Analytics/AnalyticsEvent';\nimport { AnalyticsLogEvent } from '../../../core/Analytics/AnalyticsLogEvent';\nimport { AnalyticsErrorEvent } from '../../../core/Analytics/AnalyticsErrorEvent';\n\nexport abstract class UIElement<P extends UIElementProps = UIElementProps> extends BaseElement<P> {\n protected componentRef: any;\n\n protected resources: Resources;\n\n public elementRef: UIElement;\n\n public static type = undefined;\n\n /**\n * Defines all txVariants that the Component supports (in case it support multiple ones besides the 'type' one)\n */\n public static txVariants: string[] = [];\n\n constructor(checkout: ICore, props?: P) {\n super(checkout, props);\n\n this.core.register(this.constructor as NewableComponent);\n\n this.submit = this.submit.bind(this);\n this.setState = this.setState.bind(this);\n this.onComplete = this.onComplete.bind(this);\n this.handleAction = this.handleAction.bind(this);\n this.handleOrder = this.handleOrder.bind(this);\n this.handleAdditionalDetails = this.handleAdditionalDetails.bind(this);\n this.handleResponse = this.handleResponse.bind(this);\n this.setElementStatus = this.setElementStatus.bind(this);\n this.submitAnalytics = this.submitAnalytics.bind(this);\n this.makePaymentsCall = this.makePaymentsCall.bind(this);\n this.makeAdditionalDetailsCall = this.makeAdditionalDetailsCall.bind(this);\n this.submitUsingSessionsFlow = this.submitUsingSessionsFlow.bind(this);\n\n this.elementRef = (props && props.elementRef) || this;\n this.resources = this.props.modules ? this.props.modules.resources : undefined;\n\n this.storeElementRefOnCore(this.props);\n\n this.onEnterKeyPressed = this.onEnterKeyPressed.bind(this);\n this.onActionHandled = this.onActionHandled.bind(this);\n }\n\n protected override buildElementProps(componentProps?: P) {\n const globalCoreProps = this.core.getCorePropsForComponent();\n const isStoredPaymentMethod = !!componentProps?.isStoredPaymentMethod;\n\n const paymentMethodFromResponse = isStoredPaymentMethod ? {} : this.getPaymentMethodFromPaymentMethodsResponse(componentProps?.type);\n\n const finalProps = {\n showPayButton: true,\n ...globalCoreProps,\n ...paymentMethodFromResponse,\n ...componentProps\n };\n\n const isDropin = assertIsDropin(this as unknown as IDropin);\n\n this.props = this.formatProps({\n ...this.constructor['defaultProps'], // component defaults\n ...getRegulatoryDefaults(this.core.options.countryCode, isDropin), // regulatory defaults\n ...finalProps // the rest (inc. merchant defined config)\n });\n }\n\n /**\n * Get the payment method from the paymentMethodsResponse\n *\n * @param type - The type of the payment method to get. (This prop is passed by Drop-in OR Standalone components containing the property 'type' as part of their configuration)\n */\n protected getPaymentMethodFromPaymentMethodsResponse(type?: string): PaymentMethod {\n return this.core.paymentMethodsResponse.find(type || this.constructor['type']);\n }\n\n protected storeElementRefOnCore(props?: P) {\n if (!props?.isDropin) {\n this.core.storeElementReference(this);\n }\n }\n\n public isAvailable(): Promise<void> {\n return Promise.resolve();\n }\n\n public setState(newState: object): void {\n this.state = { ...this.state, ...newState };\n this.onChange();\n }\n\n public showValidation(): this {\n if (this.componentRef && this.componentRef.showValidation) this.componentRef.showValidation();\n return this;\n }\n\n /**\n * elementRef is a ref to the subclass that extends UIElement e.g. Card.tsx\n */\n public setElementStatus(status: UIElementStatus, props?: any): this {\n this.elementRef?.setStatus(status, props);\n return this;\n }\n\n /**\n * componentRef is a ref to the primary component inside that subclass e.g. CardInput.tsx\n */\n public setStatus(status: UIElementStatus, props?): this {\n if (this.componentRef?.setStatus) {\n this.componentRef.setStatus(status, props);\n }\n return this;\n }\n\n protected onChange(): void {\n this.props.onChange?.(\n {\n data: this.data,\n isValid: this.isValid,\n errors: this.state.errors,\n valid: this.state.valid\n },\n this.elementRef\n );\n }\n\n // Only called once, for UIElements (including Dropin), as they are being mounted\n protected setUpAnalytics(setUpAnalyticsObj: AnalyticsInitialEvent) {\n const sessionId = this.props.session?.id;\n\n return this.props.modules.analytics.setUp({\n ...setUpAnalyticsObj,\n ...(sessionId && { sessionId })\n });\n }\n\n /**\n * A function for all UIElements, or BaseElement, to use to create an analytics action for when it's been:\n * - mounted,\n * - a PM has been selected\n * - onSubmit has been called (as a result of the pay button being pressed)\n *\n * In some other cases e.g. 3DS2 components, this function is overridden to allow more specific analytics actions to be created\n */\n\n protected submitAnalytics(analyticsObj: AnalyticsEvent) {\n try {\n analyticsObj.component = this.getComponent(analyticsObj);\n\n this.props.modules.analytics.sendAnalytics(analyticsObj);\n } catch (error) {\n console.warn('Failed to submit the analytics event. Error:', error);\n }\n }\n\n /** Work out what the component's \"type\" is:\n * - first check for a dedicated \"analyticsType\" (currently only applies to custom-cards)\n * - otherwise, distinguish cards from non-cards: cards will use their static type property, everything else will use props.type\n */\n private getComponent({ component }: AnalyticsEvent): string {\n if (component) {\n return component;\n }\n if (this.constructor['analyticsType']) {\n return this.constructor['analyticsType'];\n }\n if (this.constructor['type'] === 'scheme' || this.constructor['type'] === 'bcmc') {\n return this.constructor['type'];\n }\n return this.type;\n }\n\n public submit(): void {\n if (!this.isValid) {\n this.showValidation();\n return;\n }\n\n this.makePaymentsCall()\n .then(sanitizeResponse)\n .then(verifyPaymentDidNotFail)\n .then(this.handleResponse)\n .catch((e: PaymentResponseData | Error) => {\n if (e instanceof CancelError) {\n this.setElementStatus('ready');\n return;\n }\n this.handleFailedResult(e as PaymentResponseData);\n });\n }\n\n protected makePaymentsCall(): Promise<CheckoutAdvancedFlowResponse | CheckoutSessionPaymentResponse> {\n this.setElementStatus('loading');\n\n if (this.props.onSubmit) {\n return this.submitUsingAdvancedFlow();\n }\n\n if (this.core.session) {\n const beforeSubmitEvent: Promise<PaymentData> = this.props.beforeSubmit\n ? new Promise((resolve, reject) =>\n this.props.beforeSubmit(this.data, this.elementRef, {\n resolve,\n reject: () => reject(new CancelError('beforeSubmitRejected'))\n })\n )\n : Promise.resolve(this.data);\n\n return beforeSubmitEvent.then(this.submitUsingSessionsFlow);\n }\n\n this.handleError(\n new AdyenCheckoutError(\n 'IMPLEMENTATION_ERROR',\n 'It can not perform /payments call. Callback \"onSubmit\" is missing or Checkout session is not available'\n )\n );\n }\n\n private async submitUsingAdvancedFlow(): Promise<CheckoutAdvancedFlowResponse> {\n return new Promise<CheckoutAdvancedFlowResponse>((resolve, reject) => {\n // Call analytics endpoint\n const event = new AnalyticsLogEvent({\n type: ANALYTICS_SUBMIT_STR,\n message: 'Shopper clicked pay'\n });\n this.submitAnalytics(event);\n\n this.props.onSubmit(\n {\n data: this.data,\n isValid: this.isValid\n },\n this.elementRef,\n { resolve, reject }\n );\n });\n }\n\n private async submitUsingSessionsFlow(data: PaymentData): Promise<CheckoutSessionPaymentResponse> {\n const event = new AnalyticsLogEvent({\n type: ANALYTICS_SUBMIT_STR,\n message: 'Shopper clicked pay'\n });\n this.submitAnalytics(event);\n\n try {\n return await this.core.session.submitPayment(data);\n } catch (error: unknown) {\n if (error instanceof AdyenCheckoutError) {\n this.handleError(error);\n } else {\n this.handleError(new AdyenCheckoutError('ERROR', 'Error when making /payments call', { cause: error }));\n }\n\n return Promise.reject(error);\n }\n\n // // Uncomment to simulate failed\n // return {\n // resultCode: 'Refused',\n // sessionData:\n // 'Ab02b4c0!BQABAgBKGgqfEz8uQlU4yCIOWjA8bkEwmbJ7Qt4r+x5IPXREu1rMjwNk5MDoHFNlv+MWvinS6nXIDniXgRzXCdSC4ksw9CNDBAjOa+B88wRoj/rLTieuWh/0leR88qkV24vtIkjsIsbJTDB78Pd8wX8MEDsXhaAdEIyX9E8eqxuQ3bwPbvLs1Dlgo1ZrfkQRzaNiuVM8ejRG0IWE1bGThJzY+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NL/NrAJNtI6PXrZMNiza0/omPwPfe5ZYuD1Jgq59TX4h9d+3fdkArcJYL7AdoMZON1YEiWY5EzazQwtHd9yzdty9ZHPxAfuOfCh4OhbhFNp+v5YQ+PzKZ+UpM1VxV863+9XgWEURPNvX7qq1cpUSRzrSGq01QBBM3MKzRh5mAgqIdXgtl7L0EXAep0MECc7QY0/o3tW3VR8eEJGsSzrNxpFItqj0SEaIWo25dRfkl5zuw47GQrN9Qzxl2WV3A38MQPUqFtIr/71Rjkphgg49ZGWEYCwgFmm8jJc2/5qTabSGk4bzwiETCTzeydq30bUGqCwglj8CrFViAuQeTJm7dp+PYKMkUNvQRpnSXMj6Kz7rvAMzhzJgK62ltN2idqKxLC7WtivCUgejuQUvNreCYBQCaKwTwP02lZsJpGF9yw8gbyuoB+2aB7IZmgIB8GP4qVQ/ht5B9z/FLohK/8cSPV/4i32SNNdcwhV',\n // sessionResult:\n // 'X3XtfGC7!H4sIAAAAAAAA/6tWykxRslJyDjaxNDMyM3E2MXIyNDUys3RU0lHKTS1KzkjMK3FMTs4vzSsBKgtJLS7xhYo6Z6QmZ+eXlgAVFpcklpQWA+WLUtNKi1NTlGoBMEEbz1cAAAA=iMsCaEJ5LcnsqIUtmNxjm8HtfQ8gZW8JewEU3wHz4qg='\n // };\n }\n\n protected onComplete(state): void {\n if (this.props.onComplete) this.props.onComplete(state, this.elementRef);\n }\n\n protected handleError = (error: AdyenCheckoutError): void => {\n /**\n * Set status using elementRef, which:\n * - If Drop-in, will set status for Dropin component, and then it will propagate the new status for the active payment method component\n * - If Component, it will set its own status\n */\n this.setElementStatus('ready');\n\n if (error.name === NETWORK_ERROR && error.options.code) {\n const event = new AnalyticsErrorEvent({\n errorType: ANALYTICS_ERROR_TYPE.apiError,\n code: error.options.code\n });\n\n this.submitAnalytics(event);\n }\n\n if (this.props.onError) {\n this.props.onError(error, this.elementRef);\n }\n };\n\n protected handleAdditionalDetails(state: AdditionalDetailsData): void {\n this.makeAdditionalDetailsCall(state)\n .then(sanitizeResponse)\n .then(verifyPaymentDidNotFail)\n .then(this.handleResponse)\n .catch(this.handleFailedResult);\n }\n\n private makeAdditionalDetailsCall(state: AdditionalDetailsData): Promise<CheckoutSessionDetailsResponse | CheckoutAdvancedFlowResponse> {\n if (this.props.onAdditionalDetails) {\n return new Promise<CheckoutAdvancedFlowResponse>((resolve, reject) => {\n this.props.onAdditionalDetails(state, this.elementRef, { resolve, reject });\n });\n }\n\n if (this.core.session) {\n return this.submitAdditionalDetailsUsingSessionsFlow(state.data);\n }\n\n this.handleError(\n new AdyenCheckoutError(\n 'IMPLEMENTATION_ERROR',\n 'It can not perform /payments/details call. Callback \"onAdditionalDetails\" is missing or Checkout session is not available'\n )\n );\n }\n\n private async submitAdditionalDetailsUsingSessionsFlow(data: any): Promise<CheckoutSessionDetailsResponse> {\n try {\n return await this.core.session.submitDetails(data);\n } catch (error: unknown) {\n if (error instanceof AdyenCheckoutError) this.handleError(error);\n else this.handleError(new AdyenCheckoutError('ERROR', 'Error when making /details call', { cause: error }));\n\n return Promise.reject(error);\n }\n }\n\n public handleAction(action: PaymentAction, props = {}): UIElement | null {\n if (!action || !action.type) {\n if (hasOwnProperty(action, 'action') && hasOwnProperty(action, 'resultCode')) {\n throw new Error(\n 'handleAction::Invalid Action - the passed action object itself has an \"action\" property and ' +\n 'a \"resultCode\": have you passed in the whole response object by mistake?'\n );\n }\n throw new Error('handleAction::Invalid Action - the passed action object does not have a \"type\" property');\n }\n\n const paymentAction = this.core.createFromAction(action, {\n ...this.elementRef.props,\n ...props,\n onAdditionalDetails: this.handleAdditionalDetails\n });\n\n if (paymentAction) {\n this.unmount();\n return paymentAction.mount(this._node);\n }\n\n return null;\n }\n\n protected onActionHandled(actionHandledObj: ActionHandledReturnObject) {\n this.props?.onActionHandled?.({ originalAction: this.props.originalAction, ...actionHandledObj });\n }\n\n protected handleOrder = (response: PaymentResponseData): void => {\n const { order } = response;\n\n const updateCorePromise = this.core.session ? this.core.update({ order }) : this.handleAdvanceFlowPaymentMethodsUpdate(order);\n\n void updateCorePromise.then(() => {\n this.props.onOrderUpdated?.({ order });\n });\n };\n\n /**\n * Handles when the payment fails. The payment fails when:\n * - adv flow: the merchant rejects the payment due to a critical error\n * - adv flow: the merchant resolves the payment with a failed resultCode\n * - sessions: a network error occurs when making the payment\n * - sessions: the payment fails with a failed resultCode\n *\n * @param result\n */\n protected handleFailedResult = (result?: PaymentResponseData): void => {\n if (assertIsDropin(this.elementRef)) {\n this.elementRef.displayFinalAnimation('error');\n }\n\n cleanupFinalResult(result);\n this.props.onPaymentFailed?.(result, this.elementRef);\n };\n\n protected handleSuccessResult = (result: PaymentResponseData): void => {\n if (assertIsDropin(this.elementRef)) {\n this.elementRef.displayFinalAnimation('success');\n }\n\n cleanupFinalResult(result);\n this.props.onPaymentCompleted?.(result, this.elementRef);\n };\n\n /**\n * Handles a /payments or /payments/details response.\n * The component will handle automatically actions, orders, and final results.\n *\n * Expected to be called after sanitizeResponse has been run on the raw payment response\n *\n * @param response -\n */\n protected handleResponse(response: PaymentResponseData): void {\n if (response.action) {\n this.elementRef.handleAction(response.action);\n return;\n }\n\n if (response.order?.remainingAmount?.value > 0) {\n // we don't want to call elementRef here, use the component handler\n // we do this way so the logic on handlingOrder is associated with payment method\n this.handleOrder(response);\n return;\n }\n\n this.handleSuccessResult(response);\n }\n\n protected handleKeyPress(e: h.JSX.TargetedKeyboardEvent<HTMLInputElement> | KeyboardEvent) {\n if (e.key === 'Enter' || e.code === 'Enter') {\n e.preventDefault(); // Prevent <form> submission if Component is placed inside a form\n\n this.onEnterKeyPressed(document?.activeElement, this);\n }\n }\n\n /**\n * Handle Enter key pressed from a UIElement (called via handleKeyPress)\n * @param obj\n */\n protected onEnterKeyPressed(activeElement: Element, component: UIElement) {\n if (this.props.onEnterKeyPressed) {\n this.props.onEnterKeyPressed(activeElement, component);\n } else {\n (activeElement as HTMLElement).blur();\n this.submit();\n }\n }\n\n /**\n * Call update on parent instance\n * This function exist to make safe access to the protected _parentInstance\n * @param options - CoreOptions\n */\n public updateParent(options: CoreConfiguration = {}): Promise<ICore> {\n return this.elementRef.core.update(options);\n }\n\n public setComponentRef = (ref: ComponentMethodsRef) => {\n this.componentRef = ref;\n };\n\n /**\n * Get the current validation status of the element\n */\n public get isValid(): boolean {\n return false;\n }\n\n /**\n * Get the element icon URL for the current environment\n */\n public get icon(): string {\n const type = this.props.paymentMethodType || this.type;\n return this.props.icon ?? this.resources.getImage()(type);\n }\n\n /**\n * Get the element's displayable name\n */\n public get displayName(): string {\n const paymentMethodFromResponse = this.core.paymentMethodsResponse?.paymentMethods?.find(pm => pm.type === this.type);\n return this.props.name || paymentMethodFromResponse?.name || this.type;\n }\n\n /**\n * Get the element accessible name, used in the aria-label of the button that controls selected payment method\n */\n public get accessibleName(): string {\n return this.displayName;\n }\n\n /**\n * Used to display the second line of a payment method item\n */\n get additionalInfo(): string {\n return null;\n }\n\n /**\n * Return the type of an element\n */\n public get type(): string {\n return this.props.type || this.constructor['type'];\n }\n\n /**\n * Get the payButton component for the current element\n */\n protected payButton = (props: PayButtonFunctionProps) => {\n return <PayButton {...props} amount={this.props.amount} secondaryAmount={this.props.secondaryAmount} onClick={this.submit} />;\n };\n\n /**\n * Used in the Partial Orders flow.\n * When the Order is updated, the merchant can request new payment methods based on the new remaining amount\n *\n * @private\n */\n protected async handleAdvanceFlowPaymentMethodsUpdate(order: Order | null, amount?: PaymentAmount) {\n return new Promise<void | PaymentMethodsResponse>((resolve, reject) => {\n if (!this.props.onPaymentMethodsRequest) {\n return resolve();\n }\n\n this.props.onPaymentMethodsRequest(\n {\n ...(order && {\n order: {\n orderData: order.orderData,\n pspReference: order.pspReference\n }\n }),\n locale: this.core.options.locale\n },\n { resolve, reject }\n );\n })\n .catch(error => {\n this.handleError(\n new AdyenCheckoutError(\n 'IMPLEMENTATION_ERROR',\n 'Something failed during payment methods update or onPaymentMethodsRequest was not implemented',\n {\n cause: error\n }\n )\n );\n })\n .then(paymentMethodsResponse => {\n // in the case of the session flow we get order, amount, countryCode and shopperLocale from initialize()\n // apply the same logic here for order and amount\n // in the future it might be worth moving this logic to be performed by the core on update()\n // it would make this more consistent\n return this.core.update({\n ...(paymentMethodsResponse && { paymentMethodsResponse }),\n order,\n amount: order ? order.remainingAmount : amount\n });\n });\n }\n}\n\nexport default UIElement;\n"],"names":["UIElement","BaseElement","buildElementProps","componentProps","finalProps","_object_spread","showPayButton","this","core","getCorePropsForComponent","isStoredPaymentMethod","getPaymentMethodFromPaymentMethodsResponse","type","isDropin","assertIsDropin","props","formatProps","constructor","getRegulatoryDefaults","options","countryCode","paymentMethodsResponse","find","storeElementRefOnCore","storeElementReference","isAvailable","Promise","resolve","setState","newState","state","onChange","showValidation","componentRef","setElementStatus","status","_this_elementRef","elementRef","setStatus","_this_componentRef","_this_props_onChange","_this_props","call","data","isValid","errors","valid","setUpAnalytics","setUpAnalyticsObj","_this_props_session","sessionId","session","id","modules","analytics","setUp","submitAnalytics","analyticsObj","component","getComponent","sendAnalytics","error","console","warn","submit","makePaymentsCall","then","sanitizeResponse","verifyPaymentDidNotFail","handleResponse","catch","e","CancelError","handleFailedResult","onSubmit","submitUsingAdvancedFlow","beforeSubmit","reject","submitUsingSessionsFlow","handleError","AdyenCheckoutError","event","AnalyticsLogEvent","ANALYTICS_SUBMIT_STR","message","submitPayment","cause","onComplete","handleAdditionalDetails","makeAdditionalDetailsCall","onAdditionalDetails","submitAdditionalDetailsUsingSessionsFlow","submitDetails","handleAction","action","hasOwnProperty","Error","paymentAction","createFromAction","_object_spread_props","unmount","mount","_node","onActionHandled","actionHandledObj","_this_props_onActionHandled","originalAction","response","order","remainingAmount","value","handleOrder","handleSuccessResult","handleKeyPress","document","key","code","preventDefault","onEnterKeyPressed","activeElement","blur","updateParent","update","icon","paymentMethodType","_this_props_icon","resources","getImage","displayName","_this_core_paymentMethodsResponse_paymentMethods","_this_core_paymentMethodsResponse","paymentMethodFromResponse","paymentMethods","pm","name","accessibleName","additionalInfo","handleAdvanceFlowPaymentMethodsUpdate","amount","onPaymentMethodsRequest","orderData","pspReference","locale","checkout","super","_define_property","NETWORK_ERROR","AnalyticsErrorEvent","errorType","ANALYTICS_ERROR_TYPE","apiError","onError","_this_props_onOrderUpdated","onOrderUpdated","result","_this_props_onPaymentFailed","displayFinalAnimation","cleanupFinalResult","onPaymentFailed","_this_props_onPaymentCompleted","onPaymentCompleted","setComponentRef","ref","payButton","h","PayButton","secondaryAmount","onClick","register","bind","undefined","txVariants"],"mappings":"wiDAiCO,MAAeA,UAA6DC,EAyC5DC,iBAAAA,CAAkBC,GACjC,MAKMC,EAAaC,EAAA,CACfC,eAAe,GANKC,KAAKC,KAAKC,8BACFN,aAAAA,EAAAA,EAAgBO,uBAEU,GAAKH,KAAKI,2CAA2CR,aAAAA,EAAAA,EAAgBS,MAMxHT,GAGDU,EAAWC,EAAeP,MAEhCA,KAAKQ,MAAQR,KAAKS,YAAYX,EAAA,CAAA,EACvBE,KAAKU,yBACLC,EAAsBX,KAAKC,KAAKW,QAAQC,YAAaP,GACrDT,GAEX,CAOUO,0CAAAA,CAA2CC,GACjD,OAAOL,KAAKC,KAAKa,uBAAuBC,KAAKV,GAAQL,KAAKU,YAAY,KAC1E,CAEUM,qBAAAA,CAAsBR,IACvBA,aAAAA,EAAAA,EAAOF,WACRN,KAAKC,KAAKgB,sBAAsBjB,KAExC,CAEOkB,WAAAA,GACH,OAAOC,QAAQC,SACnB,CAEOC,QAAAA,CAASC,GACZtB,KAAKuB,MAAQzB,KAAKE,KAAKuB,MAAUD,GACjCtB,KAAKwB,UACT,CAEOC,cAAAA,GAEH,OADIzB,KAAK0B,cAAgB1B,KAAK0B,aAAaD,gBAAgBzB,KAAK0B,aAAaD,iBACtEzB,IACX,CAKA,gBAAA2B,CAAwBC,EAAyBpB,GAC7C,IAAAqB,EACA,OADe,QAAfA,EAAA7B,KAAK8B,sBAALD,GAAAA,EAAiBE,UAAUH,EAAQpB,GAC5BR,IACX,CAKA,SAAA+B,CAAiBH,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,KAAKlK,MACnDA,KAAKiD,gBAAkBjD,KAAKiD,gBAAgBiH,KAAKlK,MACjDA,KAAK0D,iBAAmB1D,KAAK0D,iBAAiBwG,KAAKlK,MACnDA,KAAKkF,0BAA4BlF,KAAKkF,0BAA0BgF,KAAKlK,MACrEA,KAAKuE,wBAA0BvE,KAAKuE,wBAAwB2F,KAAKlK,MAEjEA,KAAK8B,WAActB,GAASA,EAAMsB,YAAe9B,KACjDA,KAAKuH,UAAYvH,KAAKQ,MAAMsC,QAAU9C,KAAKQ,MAAMsC,QAAQyE,eAAY4C,EAErEnK,KAAKgB,sBAAsBhB,KAAKQ,OAEhCR,KAAK+G,kBAAoB/G,KAAK+G,kBAAkBmD,KAAKlK,MACrDA,KAAKgG,gBAAkBhG,KAAKgG,gBAAgBkE,KAAKlK,KACrD,EAhCA0I,EAPkBjJ,EAOJY,YAAO8J,GAKrBzB,EAZkBjJ,EAYJ2K,aAAuB"}
|
|
1
|
+
{"version":3,"file":"UIElement.js","sources":["../../../../../src/components/internal/UIElement/UIElement.tsx"],"sourcesContent":["import { h } from 'preact';\nimport BaseElement from '../BaseElement/BaseElement';\nimport PayButton from '../PayButton';\nimport { assertIsDropin, cleanupFinalResult, getRegulatoryDefaults, sanitizeResponse, verifyPaymentDidNotFail } from './utils';\nimport AdyenCheckoutError, { NETWORK_ERROR } from '../../../core/Errors/AdyenCheckoutError';\nimport { hasOwnProperty } from '../../../utils/hasOwnProperty';\nimport { Resources } from '../../../core/Context/Resources';\nimport { ANALYTICS_ERROR_TYPE, ANALYTICS_SUBMIT_STR } from '../../../core/Analytics/constants';\n\nimport { AnalyticsInitialEvent } from '../../../core/Analytics/types';\nimport type { CoreConfiguration, ICore, AdditionalDetailsData } from '../../../core/types';\nimport type { ComponentMethodsRef, PayButtonFunctionProps, UIElementProps, UIElementStatus } from './types';\nimport type { CheckoutSessionDetailsResponse, CheckoutSessionPaymentResponse } from '../../../core/CheckoutSession/types';\nimport type {\n ActionHandledReturnObject,\n CheckoutAdvancedFlowResponse,\n Order,\n PaymentAction,\n PaymentAmount,\n PaymentData,\n PaymentMethod,\n PaymentMethodsResponse,\n PaymentResponseData\n} from '../../../types/global-types';\nimport type { IDropin } from '../../Dropin/types';\nimport type { NewableComponent } from '../../../core/core.registry';\nimport CancelError from '../../../core/Errors/CancelError';\n\nimport './UIElement.scss';\nimport { AnalyticsEvent } from '../../../core/Analytics/AnalyticsEvent';\nimport { AnalyticsLogEvent } from '../../../core/Analytics/AnalyticsLogEvent';\nimport { AnalyticsErrorEvent } from '../../../core/Analytics/AnalyticsErrorEvent';\n\nexport abstract class UIElement<P extends UIElementProps = UIElementProps> extends BaseElement<P> {\n protected componentRef: any;\n\n protected resources: Resources;\n\n public elementRef: UIElement;\n\n public static type = undefined;\n\n /**\n * Defines all txVariants that the Component supports (in case it support multiple ones besides the 'type' one)\n */\n public static txVariants: string[] = [];\n\n constructor(checkout: ICore, props?: P) {\n super(checkout, props);\n\n this.core.register(this.constructor as NewableComponent);\n\n this.submit = this.submit.bind(this);\n this.setState = this.setState.bind(this);\n this.onComplete = this.onComplete.bind(this);\n this.handleAction = this.handleAction.bind(this);\n this.handleOrder = this.handleOrder.bind(this);\n this.handleAdditionalDetails = this.handleAdditionalDetails.bind(this);\n this.handleResponse = this.handleResponse.bind(this);\n this.setElementStatus = this.setElementStatus.bind(this);\n this.submitAnalytics = this.submitAnalytics.bind(this);\n this.makePaymentsCall = this.makePaymentsCall.bind(this);\n this.makeAdditionalDetailsCall = this.makeAdditionalDetailsCall.bind(this);\n this.submitUsingSessionsFlow = this.submitUsingSessionsFlow.bind(this);\n\n this.elementRef = (props && props.elementRef) || this;\n this.resources = this.props.modules ? this.props.modules.resources : undefined;\n\n this.storeElementRefOnCore(this.props);\n\n this.onEnterKeyPressed = this.onEnterKeyPressed.bind(this);\n this.onActionHandled = this.onActionHandled.bind(this);\n }\n\n protected override buildElementProps(componentProps?: P) {\n const globalCoreProps = this.core.getCorePropsForComponent();\n const isStoredPaymentMethod = !!componentProps?.isStoredPaymentMethod;\n\n const paymentMethodFromResponse = isStoredPaymentMethod ? {} : this.getPaymentMethodFromPaymentMethodsResponse(componentProps?.type);\n\n const finalProps = {\n showPayButton: true,\n ...globalCoreProps,\n ...paymentMethodFromResponse,\n ...componentProps\n };\n\n const isDropin = assertIsDropin(this as unknown as IDropin);\n\n this.props = this.formatProps({\n ...this.constructor['defaultProps'], // component defaults\n ...getRegulatoryDefaults(this.core.options.countryCode, isDropin), // regulatory defaults\n ...finalProps // the rest (inc. merchant defined config)\n });\n }\n\n /**\n * Get the payment method from the paymentMethodsResponse\n *\n * @param type - The type of the payment method to get. (This prop is passed by Drop-in OR Standalone components containing the property 'type' as part of their configuration)\n */\n protected getPaymentMethodFromPaymentMethodsResponse(type?: string): PaymentMethod {\n return this.core.paymentMethodsResponse?.find(type || this.constructor['type']);\n }\n\n protected storeElementRefOnCore(props?: P) {\n if (!props?.isDropin) {\n this.core.storeElementReference(this);\n }\n }\n\n public isAvailable(): Promise<void> {\n return Promise.resolve();\n }\n\n public setState(newState: object): void {\n this.state = { ...this.state, ...newState };\n this.onChange();\n }\n\n public showValidation(): this {\n if (this.componentRef && this.componentRef.showValidation) this.componentRef.showValidation();\n return this;\n }\n\n /**\n * elementRef is a ref to the subclass that extends UIElement e.g. Card.tsx\n */\n public setElementStatus(status: UIElementStatus, props?: any): this {\n this.elementRef?.setStatus(status, props);\n return this;\n }\n\n /**\n * componentRef is a ref to the primary component inside that subclass e.g. CardInput.tsx\n */\n public setStatus(status: UIElementStatus, props?): this {\n if (this.componentRef?.setStatus) {\n this.componentRef.setStatus(status, props);\n }\n return this;\n }\n\n protected onChange(): void {\n this.props.onChange?.(\n {\n data: this.data,\n isValid: this.isValid,\n errors: this.state.errors,\n valid: this.state.valid\n },\n this.elementRef\n );\n }\n\n // Only called once, for UIElements (including Dropin), as they are being mounted\n protected setUpAnalytics(setUpAnalyticsObj: AnalyticsInitialEvent) {\n const sessionId = this.props.session?.id;\n\n return this.props.modules.analytics.setUp({\n ...setUpAnalyticsObj,\n ...(sessionId && { sessionId })\n });\n }\n\n /**\n * A function for all UIElements, or BaseElement, to use to create an analytics action for when it's been:\n * - mounted,\n * - a PM has been selected\n * - onSubmit has been called (as a result of the pay button being pressed)\n *\n * In some other cases e.g. 3DS2 components, this function is overridden to allow more specific analytics actions to be created\n */\n\n protected submitAnalytics(analyticsObj: AnalyticsEvent) {\n try {\n analyticsObj.component = this.getComponent(analyticsObj);\n\n this.props.modules.analytics.sendAnalytics(analyticsObj);\n } catch (error) {\n console.warn('Failed to submit the analytics event. Error:', error);\n }\n }\n\n /** Work out what the component's \"type\" is:\n * - first check for a dedicated \"analyticsType\" (currently only applies to custom-cards)\n * - otherwise, distinguish cards from non-cards: cards will use their static type property, everything else will use props.type\n */\n private getComponent({ component }: AnalyticsEvent): string {\n if (component) {\n return component;\n }\n if (this.constructor['analyticsType']) {\n return this.constructor['analyticsType'];\n }\n if (this.constructor['type'] === 'scheme' || this.constructor['type'] === 'bcmc') {\n return this.constructor['type'];\n }\n return this.type;\n }\n\n public submit(): void {\n if (!this.isValid) {\n this.showValidation();\n return;\n }\n\n this.makePaymentsCall()\n .then(sanitizeResponse)\n .then(verifyPaymentDidNotFail)\n .then(this.handleResponse)\n .catch((e: PaymentResponseData | Error) => {\n if (e instanceof CancelError) {\n this.setElementStatus('ready');\n return;\n }\n this.handleFailedResult(e as PaymentResponseData);\n });\n }\n\n protected makePaymentsCall(): Promise<CheckoutAdvancedFlowResponse | CheckoutSessionPaymentResponse> {\n this.setElementStatus('loading');\n\n if (this.props.onSubmit) {\n return this.submitUsingAdvancedFlow();\n }\n\n if (this.core.session) {\n const beforeSubmitEvent: Promise<PaymentData> = this.props.beforeSubmit\n ? new Promise((resolve, reject) =>\n this.props.beforeSubmit(this.data, this.elementRef, {\n resolve,\n reject: () => reject(new CancelError('beforeSubmitRejected'))\n })\n )\n : Promise.resolve(this.data);\n\n return beforeSubmitEvent.then(this.submitUsingSessionsFlow);\n }\n\n this.handleError(\n new AdyenCheckoutError(\n 'IMPLEMENTATION_ERROR',\n 'It can not perform /payments call. Callback \"onSubmit\" is missing or Checkout session is not available'\n )\n );\n }\n\n private async submitUsingAdvancedFlow(): Promise<CheckoutAdvancedFlowResponse> {\n return new Promise<CheckoutAdvancedFlowResponse>((resolve, reject) => {\n // Call analytics endpoint\n const event = new AnalyticsLogEvent({\n type: ANALYTICS_SUBMIT_STR,\n message: 'Shopper clicked pay'\n });\n this.submitAnalytics(event);\n\n this.props.onSubmit(\n {\n data: this.data,\n isValid: this.isValid\n },\n this.elementRef,\n { resolve, reject }\n );\n });\n }\n\n private async submitUsingSessionsFlow(data: PaymentData): Promise<CheckoutSessionPaymentResponse> {\n const event = new AnalyticsLogEvent({\n type: ANALYTICS_SUBMIT_STR,\n message: 'Shopper clicked pay'\n });\n this.submitAnalytics(event);\n\n try {\n return await this.core.session.submitPayment(data);\n } catch (error: unknown) {\n if (error instanceof AdyenCheckoutError) {\n this.handleError(error);\n } else {\n this.handleError(new AdyenCheckoutError('ERROR', 'Error when making /payments call', { cause: error }));\n }\n\n return Promise.reject(error);\n }\n\n // // Uncomment to simulate failed\n // return {\n // resultCode: 'Refused',\n // sessionData:\n // 'Ab02b4c0!BQABAgBKGgqfEz8uQlU4yCIOWjA8bkEwmbJ7Qt4r+x5IPXREu1rMjwNk5MDoHFNlv+MWvinS6nXIDniXgRzXCdSC4ksw9CNDBAjOa+B88wRoj/rLTieuWh/0leR88qkV24vtIkjsIsbJTDB78Pd8wX8MEDsXhaAdEIyX9E8eqxuQ3bwPbvLs1Dlgo1ZrfkQRzaNiuVM8ejRG0IWE1bGThJzY+sJvZZHvlDMXIlxhZcDoQvsMj/WwE6+nFJxBiC3oRzmvVn3AbkLQGtvwq16UUSfYbPzG9dXypJMtcrZAQYq2g/2+BSibCcmee9AXq/wij11BERrYmjbDt5NkkdUnDVgAB7pdqbnWX0A2sxBKeYtLSP2kxp+5LoU/Wty3fmcVA3VKVkHfgmIihkeL8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Aep0MECc7QY0/o3tW3VR8eEJGsSzrNxpFItqj0SEaIWo25dRfkl5zuw47GQrN9Qzxl2WV3A38MQPUqFtIr/71Rjkphgg49ZGWEYCwgFmm8jJc2/5qTabSGk4bzwiETCTzeydq30bUGqCwglj8CrFViAuQeTJm7dp+PYKMkUNvQRpnSXMj6Kz7rvAMzhzJgK62ltN2idqKxLC7WtivCUgejuQUvNreCYBQCaKwTwP02lZsJpGF9yw8gbyuoB+2aB7IZmgIB8GP4qVQ/ht5B9z/FLohK/8cSPV/4i32SNNdcwhV',\n // sessionResult:\n // 'X3XtfGC7!H4sIAAAAAAAA/6tWykxRslJyDjaxNDMyM3E2MXIyNDUys3RU0lHKTS1KzkjMK3FMTs4vzSsBKgtJLS7xhYo6Z6QmZ+eXlgAVFpcklpQWA+WLUtNKi1NTlGoBMEEbz1cAAAA=iMsCaEJ5LcnsqIUtmNxjm8HtfQ8gZW8JewEU3wHz4qg='\n // };\n }\n\n protected onComplete(state): void {\n if (this.props.onComplete) this.props.onComplete(state, this.elementRef);\n }\n\n protected handleError = (error: AdyenCheckoutError): void => {\n /**\n * Set status using elementRef, which:\n * - If Drop-in, will set status for Dropin component, and then it will propagate the new status for the active payment method component\n * - If Component, it will set its own status\n */\n this.setElementStatus('ready');\n\n if (error.name === NETWORK_ERROR && error.options.code) {\n const event = new AnalyticsErrorEvent({\n errorType: ANALYTICS_ERROR_TYPE.apiError,\n code: error.options.code\n });\n\n this.submitAnalytics(event);\n }\n\n if (this.props.onError) {\n this.props.onError(error, this.elementRef);\n }\n };\n\n protected handleAdditionalDetails(state: AdditionalDetailsData): void {\n this.makeAdditionalDetailsCall(state)\n .then(sanitizeResponse)\n .then(verifyPaymentDidNotFail)\n .then(this.handleResponse)\n .catch(this.handleFailedResult);\n }\n\n private makeAdditionalDetailsCall(state: AdditionalDetailsData): Promise<CheckoutSessionDetailsResponse | CheckoutAdvancedFlowResponse> {\n if (this.props.onAdditionalDetails) {\n return new Promise<CheckoutAdvancedFlowResponse>((resolve, reject) => {\n this.props.onAdditionalDetails(state, this.elementRef, { resolve, reject });\n });\n }\n\n if (this.core.session) {\n return this.submitAdditionalDetailsUsingSessionsFlow(state.data);\n }\n\n this.handleError(\n new AdyenCheckoutError(\n 'IMPLEMENTATION_ERROR',\n 'It can not perform /payments/details call. Callback \"onAdditionalDetails\" is missing or Checkout session is not available'\n )\n );\n }\n\n private async submitAdditionalDetailsUsingSessionsFlow(data: any): Promise<CheckoutSessionDetailsResponse> {\n try {\n return await this.core.session.submitDetails(data);\n } catch (error: unknown) {\n if (error instanceof AdyenCheckoutError) this.handleError(error);\n else this.handleError(new AdyenCheckoutError('ERROR', 'Error when making /details call', { cause: error }));\n\n return Promise.reject(error);\n }\n }\n\n public handleAction(action: PaymentAction, props = {}): UIElement | null {\n if (!action || !action.type) {\n if (hasOwnProperty(action, 'action') && hasOwnProperty(action, 'resultCode')) {\n throw new Error(\n 'handleAction::Invalid Action - the passed action object itself has an \"action\" property and ' +\n 'a \"resultCode\": have you passed in the whole response object by mistake?'\n );\n }\n throw new Error('handleAction::Invalid Action - the passed action object does not have a \"type\" property');\n }\n\n const paymentAction = this.core.createFromAction(action, {\n ...this.elementRef.props,\n ...props,\n onAdditionalDetails: this.handleAdditionalDetails\n });\n\n if (paymentAction) {\n this.unmount();\n return paymentAction.mount(this._node);\n }\n\n return null;\n }\n\n protected onActionHandled(actionHandledObj: ActionHandledReturnObject) {\n this.props?.onActionHandled?.({ originalAction: this.props.originalAction, ...actionHandledObj });\n }\n\n protected handleOrder = (response: PaymentResponseData): void => {\n const { order } = response;\n\n const updateCorePromise = this.core.session ? this.core.update({ order }) : this.handleAdvanceFlowPaymentMethodsUpdate(order);\n\n void updateCorePromise.then(() => {\n this.props.onOrderUpdated?.({ order });\n });\n };\n\n /**\n * Handles when the payment fails. The payment fails when:\n * - adv flow: the merchant rejects the payment due to a critical error\n * - adv flow: the merchant resolves the payment with a failed resultCode\n * - sessions: a network error occurs when making the payment\n * - sessions: the payment fails with a failed resultCode\n *\n * @param result\n */\n protected handleFailedResult = (result?: PaymentResponseData): void => {\n if (assertIsDropin(this.elementRef)) {\n this.elementRef.displayFinalAnimation('error');\n }\n\n cleanupFinalResult(result);\n this.props.onPaymentFailed?.(result, this.elementRef);\n };\n\n protected handleSuccessResult = (result: PaymentResponseData): void => {\n if (assertIsDropin(this.elementRef)) {\n this.elementRef.displayFinalAnimation('success');\n }\n\n cleanupFinalResult(result);\n this.props.onPaymentCompleted?.(result, this.elementRef);\n };\n\n /**\n * Handles a /payments or /payments/details response.\n * The component will handle automatically actions, orders, and final results.\n *\n * Expected to be called after sanitizeResponse has been run on the raw payment response\n *\n * @param response -\n */\n protected handleResponse(response: PaymentResponseData): void {\n if (response.action) {\n this.elementRef.handleAction(response.action);\n return;\n }\n\n if (response.order?.remainingAmount?.value > 0) {\n // we don't want to call elementRef here, use the component handler\n // we do this way so the logic on handlingOrder is associated with payment method\n this.handleOrder(response);\n return;\n }\n\n this.handleSuccessResult(response);\n }\n\n protected handleKeyPress(e: h.JSX.TargetedKeyboardEvent<HTMLInputElement> | KeyboardEvent) {\n if (e.key === 'Enter' || e.code === 'Enter') {\n e.preventDefault(); // Prevent <form> submission if Component is placed inside a form\n\n this.onEnterKeyPressed(document?.activeElement, this);\n }\n }\n\n /**\n * Handle Enter key pressed from a UIElement (called via handleKeyPress)\n * @param obj\n */\n protected onEnterKeyPressed(activeElement: Element, component: UIElement) {\n if (this.props.onEnterKeyPressed) {\n this.props.onEnterKeyPressed(activeElement, component);\n } else {\n (activeElement as HTMLElement).blur();\n this.submit();\n }\n }\n\n /**\n * Call update on parent instance\n * This function exist to make safe access to the protected _parentInstance\n * @param options - CoreOptions\n */\n public updateParent(options: CoreConfiguration = {}): Promise<ICore> {\n return this.elementRef.core.update(options);\n }\n\n public setComponentRef = (ref: ComponentMethodsRef) => {\n this.componentRef = ref;\n };\n\n /**\n * Get the current validation status of the element\n */\n public get isValid(): boolean {\n return false;\n }\n\n /**\n * Get the element icon URL for the current environment\n */\n public get icon(): string {\n const type = this.props.paymentMethodType || this.type;\n return this.props.icon ?? this.resources.getImage()(type);\n }\n\n /**\n * Get the element's displayable name\n */\n public get displayName(): string {\n const paymentMethodFromResponse = this.core.paymentMethodsResponse?.paymentMethods?.find(pm => pm.type === this.type);\n return this.props.name || paymentMethodFromResponse?.name || this.type;\n }\n\n /**\n * Get the element accessible name, used in the aria-label of the button that controls selected payment method\n */\n public get accessibleName(): string {\n return this.displayName;\n }\n\n /**\n * Used to display the second line of a payment method item\n */\n get additionalInfo(): string {\n return null;\n }\n\n /**\n * Return the type of an element\n */\n public get type(): string {\n return this.props.type || this.constructor['type'];\n }\n\n /**\n * Get the payButton component for the current element\n */\n protected payButton = (props: PayButtonFunctionProps) => {\n return <PayButton {...props} amount={this.props.amount} secondaryAmount={this.props.secondaryAmount} onClick={this.submit} />;\n };\n\n /**\n * Used in the Partial Orders flow.\n * When the Order is updated, the merchant can request new payment methods based on the new remaining amount\n *\n * @private\n */\n protected async handleAdvanceFlowPaymentMethodsUpdate(order: Order | null, amount?: PaymentAmount) {\n return new Promise<void | PaymentMethodsResponse>((resolve, reject) => {\n if (!this.props.onPaymentMethodsRequest) {\n return resolve();\n }\n\n this.props.onPaymentMethodsRequest(\n {\n ...(order && {\n order: {\n orderData: order.orderData,\n pspReference: order.pspReference\n }\n }),\n locale: this.core.options.locale\n },\n { resolve, reject }\n );\n })\n .catch(error => {\n this.handleError(\n new AdyenCheckoutError(\n 'IMPLEMENTATION_ERROR',\n 'Something failed during payment methods update or onPaymentMethodsRequest was not implemented',\n {\n cause: error\n }\n )\n );\n })\n .then(paymentMethodsResponse => {\n // in the case of the session flow we get order, amount, countryCode and shopperLocale from initialize()\n // apply the same logic here for order and amount\n // in the future it might be worth moving this logic to be performed by the core on update()\n // it would make this more consistent\n return this.core.update({\n ...(paymentMethodsResponse && { paymentMethodsResponse }),\n order,\n amount: order ? order.remainingAmount : amount\n });\n });\n }\n}\n\nexport default UIElement;\n"],"names":["UIElement","BaseElement","buildElementProps","componentProps","finalProps","_object_spread","showPayButton","this","core","getCorePropsForComponent","isStoredPaymentMethod","getPaymentMethodFromPaymentMethodsResponse","type","isDropin","assertIsDropin","props","formatProps","constructor","getRegulatoryDefaults","options","countryCode","_this_core_paymentMethodsResponse","paymentMethodsResponse","find","storeElementRefOnCore","storeElementReference","isAvailable","Promise","resolve","setState","newState","state","onChange","showValidation","componentRef","setElementStatus","status","_this_elementRef","elementRef","setStatus","_this_componentRef","_this_props_onChange","_this_props","call","data","isValid","errors","valid","setUpAnalytics","setUpAnalyticsObj","_this_props_session","sessionId","session","id","modules","analytics","setUp","submitAnalytics","analyticsObj","component","getComponent","sendAnalytics","error","console","warn","submit","makePaymentsCall","then","sanitizeResponse","verifyPaymentDidNotFail","handleResponse","catch","e","CancelError","handleFailedResult","onSubmit","submitUsingAdvancedFlow","beforeSubmit","reject","submitUsingSessionsFlow","handleError","AdyenCheckoutError","event","AnalyticsLogEvent","ANALYTICS_SUBMIT_STR","message","submitPayment","cause","onComplete","handleAdditionalDetails","makeAdditionalDetailsCall","onAdditionalDetails","submitAdditionalDetailsUsingSessionsFlow","submitDetails","handleAction","action","hasOwnProperty","Error","paymentAction","createFromAction","_object_spread_props","unmount","mount","_node","onActionHandled","actionHandledObj","_this_props_onActionHandled","originalAction","response","order","remainingAmount","value","handleOrder","handleSuccessResult","handleKeyPress","document","key","code","preventDefault","onEnterKeyPressed","activeElement","blur","updateParent","update","icon","paymentMethodType","_this_props_icon","resources","getImage","displayName","_this_core_paymentMethodsResponse_paymentMethods","paymentMethodFromResponse","paymentMethods","pm","name","accessibleName","additionalInfo","handleAdvanceFlowPaymentMethodsUpdate","amount","onPaymentMethodsRequest","orderData","pspReference","locale","checkout","super","_define_property","NETWORK_ERROR","AnalyticsErrorEvent","errorType","ANALYTICS_ERROR_TYPE","apiError","onError","_this_props_onOrderUpdated","onOrderUpdated","result","_this_props_onPaymentFailed","displayFinalAnimation","cleanupFinalResult","onPaymentFailed","_this_props_onPaymentCompleted","onPaymentCompleted","setComponentRef","ref","payButton","h","PayButton","secondaryAmount","onClick","register","bind","undefined","txVariants"],"mappings":"wiDAiCO,MAAeA,UAA6DC,EAyC5DC,iBAAAA,CAAkBC,GACjC,MAKMC,EAAaC,EAAA,CACfC,eAAe,GANKC,KAAKC,KAAKC,8BACFN,aAAAA,EAAAA,EAAgBO,uBAEU,GAAKH,KAAKI,2CAA2CR,aAAAA,EAAAA,EAAgBS,MAMxHT,GAGDU,EAAWC,EAAeP,MAEhCA,KAAKQ,MAAQR,KAAKS,YAAYX,EAAA,CAAA,EACvBE,KAAKU,yBACLC,EAAsBX,KAAKC,KAAKW,QAAQC,YAAaP,GACrDT,GAEX,CAOUO,0CAAAA,CAA2CC,GAC1C,IAAAS,EAAP,OAAuC,QAAhCA,EAAAd,KAAKC,KAAKc,8BAAV,IAAAD,OAAA,EAAAA,EAAkCE,KAAKX,GAAQL,KAAKU,YAAY,KAC3E,CAEUO,qBAAAA,CAAsBT,IACvBA,aAAAA,EAAAA,EAAOF,WACRN,KAAKC,KAAKiB,sBAAsBlB,KAExC,CAEOmB,WAAAA,GACH,OAAOC,QAAQC,SACnB,CAEOC,QAAAA,CAASC,GACZvB,KAAKwB,MAAQ1B,KAAKE,KAAKwB,MAAUD,GACjCvB,KAAKyB,UACT,CAEOC,cAAAA,GAEH,OADI1B,KAAK2B,cAAgB3B,KAAK2B,aAAaD,gBAAgB1B,KAAK2B,aAAaD,iBACtE1B,IACX,CAKA,gBAAA4B,CAAwBC,EAAyBrB,GAC7C,IAAAsB,EACA,OADe,QAAfA,EAAA9B,KAAK+B,sBAALD,GAAAA,EAAiBE,UAAUH,EAAQrB,GAC5BR,IACX,CAKA,SAAAgC,CAAiBH,EAAyBrB,GAClC,IAAAyB,EAGJ,eAHIA,EAAAjC,KAAK2B,oBAAL,IAAAM,OAAA,EAAAA,EAAmBD,YACnBhC,KAAK2B,aAAaK,UAAUH,EAAQrB,GAEjCR,IACX,CAEUyB,Q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+E,KAAKlK,MACrEA,KAAKwE,wBAA0BxE,KAAKwE,wBAAwB0F,KAAKlK,MAEjEA,KAAK+B,WAAcvB,GAASA,EAAMuB,YAAe/B,KACjDA,KAAKwH,UAAYxH,KAAKQ,MAAMuC,QAAU/C,KAAKQ,MAAMuC,QAAQyE,eAAY2C,EAErEnK,KAAKiB,sBAAsBjB,KAAKQ,OAEhCR,KAAKgH,kBAAoBhH,KAAKgH,kBAAkBkD,KAAKlK,MACrDA,KAAKiG,gBAAkBjG,KAAKiG,gBAAgBiE,KAAKlK,KACrD,EAhCA0I,EAPkBjJ,EAOJY,YAAO8J,GAKrBzB,EAZkBjJ,EAYJ2K,aAAuB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sources":["../../../../../src/components/internal/UIElement/utils.ts"],"sourcesContent":["import { UIElementStatus } from './types';\nimport { RawPaymentResponse, PaymentResponseData, Order } from '../../../types/global-types';\nimport { IDropin } from '../../Dropin/types';\n\nconst ALLOWED_PROPERTIES = ['action', 'resultCode', 'sessionData', 'order', 'sessionResult', 'donationToken', 'error'];\n\nexport function sanitizeResponse(response: RawPaymentResponse): PaymentResponseData {\n const removedProperties = [];\n\n const sanitizedObject = Object.keys(response).reduce((acc, cur) => {\n if (!ALLOWED_PROPERTIES.includes(cur)) {\n removedProperties.push(cur);\n } else {\n acc[cur] = response[cur];\n }\n return acc;\n }, {});\n\n if (removedProperties.length) console.warn(`The following properties should not be passed to the client: ${removedProperties.join(', ')}`);\n\n return sanitizedObject as PaymentResponseData;\n}\n\n/**\n * Remove not relevant properties in the final payment result object\n *\n * @param paymentResponse\n */\nexport function cleanupFinalResult(paymentResponse?: PaymentResponseData): void {\n if (!paymentResponse) return;\n\n delete paymentResponse.order;\n delete paymentResponse.action;\n if (!paymentResponse.donationToken || paymentResponse.donationToken.length === 0) {\n delete paymentResponse.donationToken;\n }\n}\n\nexport function resolveFinalResult(result: PaymentResponseData): [status: UIElementStatus, statusProps?: any] {\n switch (result.resultCode) {\n case 'Authorised':\n case 'Received':\n return ['success'];\n case 'Pending':\n return ['success'];\n case 'Cancelled':\n case 'Error':\n case 'Refused':\n return ['error'];\n default:\n }\n}\n\nexport function verifyPaymentDidNotFail(response: PaymentResponseData): Promise<PaymentResponseData> {\n if (['Cancelled', 'Error', 'Refused'].includes(response.resultCode)) {\n return Promise.reject(response);\n }\n\n return Promise.resolve(response);\n}\n\nexport function assertIsDropin(element: any): element is IDropin {\n if (!element) return false;\n\n const isDropin = typeof element.activePaymentMethod === 'object' && typeof element.closeActivePaymentMethod === 'function';\n return isDropin;\n}\n\nexport function getRegulatoryDefaults(countryCode: string, isDropin: boolean): Record<string, any> {\n switch (countryCode) {\n // Finnish regulations state that no payment method can be open by default\n case 'FI':\n return isDropin\n ? {\n openFirstPaymentMethod: false,\n openFirstStoredPaymentMethod: false\n }\n : {};\n default:\n return {};\n }\n}\n\nexport function sanitizeOrder(order: Order) {\n if (!order || !order.orderData || !order.pspReference) return null;\n return {\n orderData: order.orderData,\n pspReference: order.pspReference\n };\n}\n"],"names":["ALLOWED_PROPERTIES","sanitizeResponse","response","removedProperties","sanitizedObject","Object","keys","reduce","acc","cur","includes","push","length","console","warn","join","cleanupFinalResult","paymentResponse","order","action","donationToken","verifyPaymentDidNotFail","resultCode","Promise","reject","resolve","assertIsDropin","element","activePaymentMethod","closeActivePaymentMethod","getRegulatoryDefaults","countryCode","isDropin","openFirstPaymentMethod","openFirstStoredPaymentMethod","sanitizeOrder","orderData","pspReference"],"mappings":"AAIA,MAAMA,EAAqB,CAAC,SAAU,aAAc,cAAe,QAAS,gBAAiB,gBAAiB,SAEvG,SAASC,EAAiBC,GAC7B,MAAMC,EAAoB,GAEpBC,EAAkBC,OAAOC,KAAKJ,GAAUK,OAAO,CAACC,EAAKC,KAClDT,EAAmBU,SAASD,GAG7BD,EAAIC,GAAOP,EAASO,GAFpBN,EAAkBQ,KAAKF,GAIpBD,GACR,
|
|
1
|
+
{"version":3,"file":"utils.js","sources":["../../../../../src/components/internal/UIElement/utils.ts"],"sourcesContent":["import { UIElementStatus } from './types';\nimport { RawPaymentResponse, PaymentResponseData, Order } from '../../../types/global-types';\nimport { IDropin } from '../../Dropin/types';\n\nconst ALLOWED_PROPERTIES = ['action', 'resultCode', 'sessionData', 'order', 'sessionResult', 'donationToken', 'error'];\n\nexport function sanitizeResponse(response: RawPaymentResponse): PaymentResponseData {\n const removedProperties = [];\n\n const sanitizedObject = Object.keys(response).reduce((acc, cur) => {\n if (!ALLOWED_PROPERTIES.includes(cur)) {\n removedProperties.push(cur);\n } else {\n acc[cur] = response[cur];\n }\n return acc;\n }, {});\n\n if (removedProperties.length) console.warn(`The following properties should not be passed to the client: ${removedProperties.join(', ')}`);\n\n return sanitizedObject as PaymentResponseData;\n}\n\n/**\n * Remove not relevant properties in the final payment result object\n *\n * @param paymentResponse\n */\nexport function cleanupFinalResult(paymentResponse?: PaymentResponseData): void {\n if (!paymentResponse) return;\n\n delete paymentResponse.order;\n delete paymentResponse.action;\n if (!paymentResponse.donationToken || paymentResponse.donationToken.length === 0) {\n delete paymentResponse.donationToken;\n }\n}\n\nexport function resolveFinalResult(result: PaymentResponseData): [status: UIElementStatus, statusProps?: any] {\n switch (result.resultCode) {\n case 'Authorised':\n case 'Received':\n return ['success'];\n case 'Pending':\n return ['success'];\n case 'Cancelled':\n case 'Error':\n case 'Refused':\n return ['error'];\n default:\n }\n}\n\nexport function verifyPaymentDidNotFail(response: PaymentResponseData): Promise<PaymentResponseData> {\n if (['Cancelled', 'Error', 'Refused'].includes(response.resultCode)) {\n return Promise.reject(response);\n }\n\n return Promise.resolve(response);\n}\n\nexport function assertIsDropin(element: any): element is IDropin {\n if (!element) return false;\n\n const isDropin = typeof element.activePaymentMethod === 'object' && typeof element.closeActivePaymentMethod === 'function';\n return isDropin;\n}\n\nexport function getRegulatoryDefaults(countryCode: string, isDropin: boolean): Record<string, any> {\n switch (countryCode) {\n // Finnish regulations state that no payment method can be open by default\n case 'FI':\n return isDropin\n ? {\n openFirstPaymentMethod: false,\n openFirstStoredPaymentMethod: false\n }\n : {};\n default:\n return {};\n }\n}\n\nexport function sanitizeOrder(order: Order) {\n if (!order || !order.orderData || !order.pspReference) return null;\n return {\n orderData: order.orderData,\n pspReference: order.pspReference\n };\n}\n"],"names":["ALLOWED_PROPERTIES","sanitizeResponse","response","removedProperties","sanitizedObject","Object","keys","reduce","acc","cur","includes","push","length","console","warn","join","cleanupFinalResult","paymentResponse","order","action","donationToken","verifyPaymentDidNotFail","resultCode","Promise","reject","resolve","assertIsDropin","element","activePaymentMethod","closeActivePaymentMethod","getRegulatoryDefaults","countryCode","isDropin","openFirstPaymentMethod","openFirstStoredPaymentMethod","sanitizeOrder","orderData","pspReference"],"mappings":"AAIA,MAAMA,EAAqB,CAAC,SAAU,aAAc,cAAe,QAAS,gBAAiB,gBAAiB,SAEvG,SAASC,EAAiBC,GAC7B,MAAMC,EAAoB,GAEpBC,EAAkBC,OAAOC,KAAKJ,GAAUK,OAAO,CAACC,EAAKC,KAClDT,EAAmBU,SAASD,GAG7BD,EAAIC,GAAOP,EAASO,GAFpBN,EAAkBQ,KAAKF,GAIpBD,GACR,CAAA,GAIH,OAFIL,EAAkBS,QAAQC,QAAQC,KAAK,gEAAgEX,EAAkBY,KAAK,SAE3HX,CACX,CAOO,SAASY,EAAmBC,GAC1BA,WAEEA,EAAgBC,aAChBD,EAAgBE,OAClBF,EAAgBG,eAA0D,IAAzCH,EAAgBG,cAAcR,eACzDK,EAAgBG,cAE/B,CAiBO,SAASC,EAAwBnB,GACpC,MAAI,CAAC,YAAa,QAAS,WAAWQ,SAASR,EAASoB,YAC7CC,QAAQC,OAAOtB,GAGnBqB,QAAQE,QAAQvB,EAC3B,CAEO,SAASwB,EAAeC,GAC3B,IAAKA,EAAS,OAAO,EAGrB,MADwD,iBAAhCA,EAAQC,qBAAgF,mBAArCD,EAAQE,wBAEvF,CAEO,SAASC,EAAsBC,EAAqBC,GACvD,MAES,OAFDD,GAGOC,EACD,CACIC,wBAAwB,EACxBC,8BAA8B,GAIjC,CAAA,CAEnB,CAEO,SAASC,EAAcjB,GAC1B,OAAKA,GAAUA,EAAMkB,WAAclB,EAAMmB,aAClC,CACHD,UAAWlB,EAAMkB,UACjBC,aAAcnB,EAAMmB,cAHsC,IAKlE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Voucher.js","sources":["../../../../../src/components/internal/Voucher/Voucher.tsx"],"sourcesContent":["import { h } from 'preact';\nimport classNames from 'classnames';\nimport Button from '../Button';\nimport { copyToClipboard } from '../../../utils/clipboard';\n\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport './Voucher.scss';\nimport { VoucherProps } from './types';\nimport useImage from '../../../core/Context/useImage';\nimport { PREFIX } from '../Icon/constants';\nimport DetailsTable from '../DetailsTable';\n\nexport default function Voucher({ voucherDetails = [], className = '', ...props }: VoucherProps) {\n const { i18n } = useCoreContext();\n const getImage = useImage();\n\n props.onActionHandled?.({ componentType: props.paymentMethodType, actionDescription: 'voucher-presented' });\n\n return (\n <div className={classNames('adyen-checkout__voucher-result', `adyen-checkout__voucher-result--${props.paymentMethodType}`, className)}>\n <div className=\"adyen-checkout__voucher-result__top\">\n <div className=\"adyen-checkout__voucher-result__image\">\n {!!props.imageUrl && (\n <span className=\"adyen-checkout__voucher-result__image__wrapper\">\n <img alt={props.paymentMethodType} className=\"adyen-checkout__voucher-result__image__brand\" src={props.imageUrl} />\n </span>\n )}\n\n {!!props.issuerImageUrl && (\n <span className=\"adyen-checkout__voucher-result__image__wrapper\">\n <img alt={props.paymentMethodType} className=\"adyen-checkout__voucher-result__image__issuer\" src={props.issuerImageUrl} />\n </span>\n )}\n </div>\n\n <div className=\"adyen-checkout__voucher-result__introduction\">\n {props.introduction}{' '}\n {props.instructionsUrl && (\n <a\n className=\"adyen-checkout-link adyen-checkout-link--voucher-result-instructions\"\n href={props.instructionsUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n {i18n.get('voucher.readInstructions')} ›\n </a>\n )}\n </div>\n\n {props.amount && (\n <div className=\"adyen-checkout__voucher-result__amount\">\n {props.amount}\n\n {props.surcharge && (\n <span className=\"adyen-checkout__voucher-result__surcharge\">\n ({i18n.get('voucher.surcharge').replace('%@', props.surcharge)})\n </span>\n )}\n </div>\n )}\n </div>\n\n {props.reference && (\n <div className=\"adyen-checkout__voucher-result__separator\">\n <div className=\"adyen-checkout__voucher-result__separator__inner\" />\n <div className=\"adyen-checkout__voucher-result__code__label\">\n <span className=\"adyen-checkout__voucher-result__code__label__text\">{i18n.get('voucher.paymentReferenceLabel')}</span>\n </div>\n </div>\n )}\n\n <div className=\"adyen-checkout__voucher-result__bottom\">\n {props.reference && (\n <div className=\"adyen-checkout__voucher-result__code\">\n {props.barcode && (\n <img\n alt={i18n.get('voucher.paymentReferenceLabel')}\n className=\"adyen-checkout__voucher-result__code__barcode\"\n src={props.barcode}\n />\n )}\n <span>{props.reference}</span>\n </div>\n )}\n\n {(!!props.downloadUrl || !!props.copyBtn) && (\n <ul className=\"adyen-checkout__voucher-result__actions\">\n {!!props.copyBtn && (\n <li className=\"adyen-checkout__voucher-result__actions__item\">\n <Button\n inline\n variant=\"action\"\n onClick={(e, { complete }) => {\n copyToClipboard(props.reference);\n complete();\n }}\n icon={getImage({ imageFolder: 'components/' })(`${PREFIX}copy`)}\n label={i18n.get('button.copy')}\n />\n </li>\n )}\n\n {!!props.downloadUrl && (\n <li className=\"adyen-checkout__voucher-result__actions__item\">\n <Button\n inline\n variant=\"action\"\n href={props.downloadUrl}\n icon={getImage({ imageFolder: 'components/' })(`${PREFIX}download`)}\n label={props.downloadButtonText || i18n.get('button.download')}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n />\n </li>\n )}\n </ul>\n )}\n\n <DetailsTable tableFields={voucherDetails} />\n </div>\n </div>\n );\n}\n"],"names":["Voucher","_param","props","voucherDetails","className","i18n","useCoreContext","getImage","useImage","onActionHandled","componentType","paymentMethodType","actionDescription","h","div","classNames","imageUrl","span","img","alt","src","issuerImageUrl","introduction","instructionsUrl","a","href","target","rel","get","amount","surcharge","replace","reference","barcode","downloadUrl","copyBtn","ul","li","Button","inline","variant","onClick","e","complete","copyToClipboard","icon","imageFolder","PREFIX","label","downloadButtonText","DetailsTable","tableFields"],"mappings":"4xBAYe,SAASA,EAAQC,OAI5BC,GAJ4BC,eAAEA,EAAiB,GAAEC,UAAEA,EAAY,IAAnCH,EAA0CC,EAAAA,EAA1CD,EAAA,CAAEE,iBAAqBC,cACnD,MAAMC,KAAEA,GAASC,IACXC,EAAWC,IAIjB,OAFqB,QAArBN,EAAAA,EAAMO,uBAANP,IAAAA,GAAAA,OAAAA,EAAwB,CAAEQ,cAAeR,EAAMS,kBAAmBC,kBAAmB,sBAGjFC,EAACC,MAAAA,CAAIV,UAAWW,EAAW,iCAAkC,mCAAmCb,EAAMS,oBAAqBP,IACvHS,EAACC,MAAAA,CAAIV,UAAU,uCACXS,EAACC,MAAAA,CAAIV,UAAU,2CACRF,EAAMc,UACLH,EAACI,OAAAA,CAAKb,UAAU,kDACZS,EAACK,MAAAA,CAAIC,IAAKjB,EAAMS,kBAAmBP,UAAU,+CAA+CgB,IAAKlB,EAAMc,cAI5Gd,EAAMmB,gBACLR,EAACI,OAAAA,CAAKb,UAAU,kDACZS,EAACK,MAAAA,CAAIC,IAAKjB,EAAMS,kBAAmBP,UAAU,gDAAgDgB,IAAKlB,EAAMmB,mBAKpHR,EAACC,MAAAA,CAAIV,UAAU,gDACVF,EAAMoB,aAAc,IACpBpB,EAAMqB,iBACHV,EAACW,IAAAA,CACGpB,UAAU,uEACVqB,KAAMvB,EAAMqB,gBACZG,OAAO,SACPC,IAAI,uBAEHtB,EAAKuB,IAAI,4BAA4B,OAKjD1B,EAAM2B,QACHhB,EAACC,MAAAA,CAAIV,UAAU,0CACVF,EAAM2B,OAEN3B,EAAM4B,WACHjB,EAACI,OAAAA,CAAKb,UAAU,6CAA4C,IACtDC,EAAKuB,IAAI,qBAAqBG,QAAQ,KAAM7B,EAAM4B,WAAW,OAOlF5B,EAAM8B,WACHnB,EAACC,MAAAA,CAAIV,UAAU,6CACXS,EAACC,MAAAA,CAAIV,UAAU,qDACfS,EAACC,MAAAA,CAAIV,UAAU,+CACXS,EAACI,OAAAA,CAAKb,UAAU,qDAAqDC,EAAKuB,IAAI,oCAK1Ff,EAACC,MAAAA,CAAIV,UAAU,0CACVF,EAAM8B,WACHnB,EAACC,MAAAA,CAAIV,UAAU,wCACVF,EAAM+B,SACHpB,EAACK,MAAAA,CACGC,IAAKd,EAAKuB,IAAI,iCACdxB,UAAU,gDACVgB,IAAKlB,EAAM+B,UAGnBpB,EAACI,YAAMf,EAAM8B,eAIjB9B,EAAMgC,eAAiBhC,EAAMiC,UAC7BtB,EAACuB,KAAAA,CAAGhC,UAAU,6CACPF,EAAMiC,SACLtB,EAACwB,KAAAA,CAAGjC,UAAU,iDACVS,EAACyB,EAAAA,CACGC,QAAAA,EACAC,QAAQ,SACRC,QAAS,CAACC,GAAKC,
|
|
1
|
+
{"version":3,"file":"Voucher.js","sources":["../../../../../src/components/internal/Voucher/Voucher.tsx"],"sourcesContent":["import { h } from 'preact';\nimport classNames from 'classnames';\nimport Button from '../Button';\nimport { copyToClipboard } from '../../../utils/clipboard';\n\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport './Voucher.scss';\nimport { VoucherProps } from './types';\nimport useImage from '../../../core/Context/useImage';\nimport { PREFIX } from '../Icon/constants';\nimport DetailsTable from '../DetailsTable';\n\nexport default function Voucher({ voucherDetails = [], className = '', ...props }: VoucherProps) {\n const { i18n } = useCoreContext();\n const getImage = useImage();\n\n props.onActionHandled?.({ componentType: props.paymentMethodType, actionDescription: 'voucher-presented' });\n\n return (\n <div className={classNames('adyen-checkout__voucher-result', `adyen-checkout__voucher-result--${props.paymentMethodType}`, className)}>\n <div className=\"adyen-checkout__voucher-result__top\">\n <div className=\"adyen-checkout__voucher-result__image\">\n {!!props.imageUrl && (\n <span className=\"adyen-checkout__voucher-result__image__wrapper\">\n <img alt={props.paymentMethodType} className=\"adyen-checkout__voucher-result__image__brand\" src={props.imageUrl} />\n </span>\n )}\n\n {!!props.issuerImageUrl && (\n <span className=\"adyen-checkout__voucher-result__image__wrapper\">\n <img alt={props.paymentMethodType} className=\"adyen-checkout__voucher-result__image__issuer\" src={props.issuerImageUrl} />\n </span>\n )}\n </div>\n\n <div className=\"adyen-checkout__voucher-result__introduction\">\n {props.introduction}{' '}\n {props.instructionsUrl && (\n <a\n className=\"adyen-checkout-link adyen-checkout-link--voucher-result-instructions\"\n href={props.instructionsUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n {i18n.get('voucher.readInstructions')} ›\n </a>\n )}\n </div>\n\n {props.amount && (\n <div className=\"adyen-checkout__voucher-result__amount\">\n {props.amount}\n\n {props.surcharge && (\n <span className=\"adyen-checkout__voucher-result__surcharge\">\n ({i18n.get('voucher.surcharge').replace('%@', props.surcharge)})\n </span>\n )}\n </div>\n )}\n </div>\n\n {props.reference && (\n <div className=\"adyen-checkout__voucher-result__separator\">\n <div className=\"adyen-checkout__voucher-result__separator__inner\" />\n <div className=\"adyen-checkout__voucher-result__code__label\">\n <span className=\"adyen-checkout__voucher-result__code__label__text\">{i18n.get('voucher.paymentReferenceLabel')}</span>\n </div>\n </div>\n )}\n\n <div className=\"adyen-checkout__voucher-result__bottom\">\n {props.reference && (\n <div className=\"adyen-checkout__voucher-result__code\">\n {props.barcode && (\n <img\n alt={i18n.get('voucher.paymentReferenceLabel')}\n className=\"adyen-checkout__voucher-result__code__barcode\"\n src={props.barcode}\n />\n )}\n <span>{props.reference}</span>\n </div>\n )}\n\n {(!!props.downloadUrl || !!props.copyBtn) && (\n <ul className=\"adyen-checkout__voucher-result__actions\">\n {!!props.copyBtn && (\n <li className=\"adyen-checkout__voucher-result__actions__item\">\n <Button\n inline\n variant=\"action\"\n onClick={(e, { complete }) => {\n void copyToClipboard(props.reference);\n complete();\n }}\n icon={getImage({ imageFolder: 'components/' })(`${PREFIX}copy`)}\n label={i18n.get('button.copy')}\n />\n </li>\n )}\n\n {!!props.downloadUrl && (\n <li className=\"adyen-checkout__voucher-result__actions__item\">\n <Button\n inline\n variant=\"action\"\n href={props.downloadUrl}\n icon={getImage({ imageFolder: 'components/' })(`${PREFIX}download`)}\n label={props.downloadButtonText || i18n.get('button.download')}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n />\n </li>\n )}\n </ul>\n )}\n\n <DetailsTable tableFields={voucherDetails} />\n </div>\n </div>\n );\n}\n"],"names":["Voucher","_param","props","voucherDetails","className","i18n","useCoreContext","getImage","useImage","onActionHandled","componentType","paymentMethodType","actionDescription","h","div","classNames","imageUrl","span","img","alt","src","issuerImageUrl","introduction","instructionsUrl","a","href","target","rel","get","amount","surcharge","replace","reference","barcode","downloadUrl","copyBtn","ul","li","Button","inline","variant","onClick","e","complete","copyToClipboard","icon","imageFolder","PREFIX","label","downloadButtonText","DetailsTable","tableFields"],"mappings":"4xBAYe,SAASA,EAAQC,OAI5BC,GAJ4BC,eAAEA,EAAiB,GAAEC,UAAEA,EAAY,IAAnCH,EAA0CC,EAAAA,EAA1CD,EAAA,CAAEE,iBAAqBC,cACnD,MAAMC,KAAEA,GAASC,IACXC,EAAWC,IAIjB,OAFqB,QAArBN,EAAAA,EAAMO,uBAANP,IAAAA,GAAAA,OAAAA,EAAwB,CAAEQ,cAAeR,EAAMS,kBAAmBC,kBAAmB,sBAGjFC,EAACC,MAAAA,CAAIV,UAAWW,EAAW,iCAAkC,mCAAmCb,EAAMS,oBAAqBP,IACvHS,EAACC,MAAAA,CAAIV,UAAU,uCACXS,EAACC,MAAAA,CAAIV,UAAU,2CACRF,EAAMc,UACLH,EAACI,OAAAA,CAAKb,UAAU,kDACZS,EAACK,MAAAA,CAAIC,IAAKjB,EAAMS,kBAAmBP,UAAU,+CAA+CgB,IAAKlB,EAAMc,cAI5Gd,EAAMmB,gBACLR,EAACI,OAAAA,CAAKb,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A,CAAGjC,UAAU,iDACVS,EAACyB,EAAAA,CACGC,QAAAA,EACAC,QAAQ,SACRf,KAAMvB,EAAMgC,YACZW,KAAMtC,EAAS,CAAEuC,YAAa,eAAxBvC,CAAyC,GAAGwC,aAClDC,MAAO9C,EAAM+C,oBAAsB5C,EAAKuB,IAAI,mBAC5CF,OAAO,SACPC,IAAI,0BAOxBd,EAACqC,EAAAA,CAAaC,YAAahD,KAI3C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sources":["../../../../src/core/Analytics/utils.ts"],"sourcesContent":["import { AnalyticsData } from './types';\nimport { errorCodeMapping, ALLOWED_ANALYTICS_DATA } from './constants';\nimport { digitsOnlyFormatter } from '../../utils/Formatters/formatters';\nimport { ERROR_FIELD_REQUIRED, ERROR_INVALID_FORMAT_EXPECTS } from '../Errors/constants';\n\nexport const getUTCTimestamp = () => Date.now();\n\nexport const mapErrorCodesForAnalytics = (errorCode: string, target: string) => {\n // Some of the more generic error codes required combination with target to retrieve a specific code\n if (errorCode === ERROR_FIELD_REQUIRED || errorCode === ERROR_INVALID_FORMAT_EXPECTS) {\n return errorCodeMapping[`${errorCode}.${target}`] ?? errorCode;\n }\n\n let errCode = errorCodeMapping[errorCode] ?? errorCode;\n\n // If errCode isn't now a number - then we just need to remove any non-digits\n // since the correct error code is already contained within the string e.g. securedField related errors\n if (isNaN(Number(errCode))) {\n errCode = digitsOnlyFormatter(errCode);\n }\n\n return errCode;\n};\n\nexport const processAnalyticsData = (analyticsData: AnalyticsData): AnalyticsData => {\n return Object.keys(analyticsData).reduce((acc, prop) => {\n if (ALLOWED_ANALYTICS_DATA.includes(prop)) acc[prop] = analyticsData[prop];\n return acc;\n }, {});\n};\n"],"names":["getUTCTimestamp","Date","now","mapErrorCodesForAnalytics","errorCode","target","errorCodeMapping","ERROR_FIELD_REQUIRED","ERROR_INVALID_FORMAT_EXPECTS","errCode","isNaN","Number","digitsOnlyFormatter","processAnalyticsData","analyticsData","Object","keys","reduce","acc","prop","ALLOWED_ANALYTICS_DATA","includes"],"mappings":"yPAKO,MAAMA,EAAkB,IAAMC,KAAKC,MAE7BC,EAA4B,CAACC,EAAmBC,KAG9CC,IAAAA,EAGGA,EAJd,GAAIF,IAAcG,GAAwBH,IAAcI,EACpD,OAAiD,QAA1CF,EAAAA,EAAiB,GAAGF,KAAaC,YAAjCC,IAAAA,EAAAA,EAA8CF,EAGzD,IAAIK,EAAqC,QAA3BH,EAAAA,EAAiBF,cAAjBE,EAAAA,EAA+BF,EAQ7C,OAJIM,MAAMC,OAAOF,MACbA,EAAUG,EAAoBH,IAG3BA,GAGEI,EAAwBC,GAC1BC,OAAOC,KAAKF,GAAeG,OAAO,CAACC,EAAKC,KACvCC,EAAuBC,SAASF,KAAOD,EAAIC,GAAQL,EAAcK,IAC9DD,GACR"}
|
|
1
|
+
{"version":3,"file":"utils.js","sources":["../../../../src/core/Analytics/utils.ts"],"sourcesContent":["import { AnalyticsData } from './types';\nimport { errorCodeMapping, ALLOWED_ANALYTICS_DATA } from './constants';\nimport { digitsOnlyFormatter } from '../../utils/Formatters/formatters';\nimport { ERROR_FIELD_REQUIRED, ERROR_INVALID_FORMAT_EXPECTS } from '../Errors/constants';\n\nexport const getUTCTimestamp = () => Date.now();\n\nexport const mapErrorCodesForAnalytics = (errorCode: string, target: string) => {\n // Some of the more generic error codes required combination with target to retrieve a specific code\n if (errorCode === ERROR_FIELD_REQUIRED || errorCode === ERROR_INVALID_FORMAT_EXPECTS) {\n return errorCodeMapping[`${errorCode}.${target}`] ?? errorCode;\n }\n\n let errCode = errorCodeMapping[errorCode] ?? errorCode;\n\n // If errCode isn't now a number - then we just need to remove any non-digits\n // since the correct error code is already contained within the string e.g. securedField related errors\n if (isNaN(Number(errCode))) {\n errCode = digitsOnlyFormatter(errCode);\n }\n\n return errCode;\n};\n\nexport const processAnalyticsData = (analyticsData: AnalyticsData): AnalyticsData => {\n return Object.keys(analyticsData).reduce((acc, prop) => {\n if (ALLOWED_ANALYTICS_DATA.includes(prop)) acc[prop] = analyticsData[prop];\n return acc;\n }, {});\n};\n"],"names":["getUTCTimestamp","Date","now","mapErrorCodesForAnalytics","errorCode","target","errorCodeMapping","ERROR_FIELD_REQUIRED","ERROR_INVALID_FORMAT_EXPECTS","errCode","isNaN","Number","digitsOnlyFormatter","processAnalyticsData","analyticsData","Object","keys","reduce","acc","prop","ALLOWED_ANALYTICS_DATA","includes"],"mappings":"yPAKO,MAAMA,EAAkB,IAAMC,KAAKC,MAE7BC,EAA4B,CAACC,EAAmBC,KAG9CC,IAAAA,EAGGA,EAJd,GAAIF,IAAcG,GAAwBH,IAAcI,EACpD,OAAiD,QAA1CF,EAAAA,EAAiB,GAAGF,KAAaC,YAAjCC,IAAAA,EAAAA,EAA8CF,EAGzD,IAAIK,EAAqC,QAA3BH,EAAAA,EAAiBF,cAAjBE,EAAAA,EAA+BF,EAQ7C,OAJIM,MAAMC,OAAOF,MACbA,EAAUG,EAAoBH,IAG3BA,GAGEI,EAAwBC,GAC1BC,OAAOC,KAAKF,GAAeG,OAAO,CAACC,EAAKC,KACvCC,EAAuBC,SAASF,KAAOD,EAAIC,GAAQL,EAAcK,IAC9DD,GACR,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SRPanel.js","sources":["../../../../src/core/Errors/SRPanel.tsx"],"sourcesContent":["import { h } from 'preact';\nimport './SRPanel.scss';\nimport { AriaAttributes, SRPanelProps } from './types';\nimport BaseElement from '../../components/internal/BaseElement/BaseElement';\nimport { SRMessages, SRMessagesRef } from './SRMessages';\nimport type { ICore } from '../types';\n\n/**\n * A panel meant to hold messages that will be read out by ScreenReaders on an aria-live=\"polite\" basis\n * Expects a string or string array of message to add to the panel to be read out\n * For testing purposes can be made visible\n */\nexport class SRPanel extends BaseElement<SRPanelProps> {\n public static type = 'srPanel';\n\n public static defaultProps: Partial<SRPanelProps> = {\n enabled: true,\n node: 'body',\n showPanel: false,\n id: 'ariaLiveSRPanel',\n ariaAttributes: {\n 'aria-relevant': 'all',\n 'aria-live': 'polite',\n 'aria-atomic': 'true'\n }\n };\n\n private readonly srPanelContainer = null;\n\n private readonly id;\n private readonly showPanel;\n private readonly _enabled: boolean;\n private readonly _moveFocus: boolean;\n\n private componentRef: SRMessagesRef;\n\n constructor(checkout: ICore, props?: SRPanelProps) {\n super(checkout, props);\n\n this.id = this.props.id;\n this.showPanel = process.env.NODE_ENV !== 'production' ? this.props.showPanel : false;\n this._enabled = false;\n this._moveFocus = this.props.moveFocus ?? true;\n\n if (this.props.enabled) {\n this._enabled = true;\n\n const panelParent = document.querySelector(this.props.node);\n\n if (panelParent) {\n const preExistingSRPanel = document.getElementById(this.id);\n if (preExistingSRPanel) {\n panelParent.removeChild(preExistingSRPanel);\n }\n\n this.srPanelContainer = document.createElement('div');\n this.srPanelContainer.className = 'sr-panel-holder';\n this.srPanelContainer.id = this.id;\n\n panelParent.appendChild(this.srPanelContainer);\n\n this.mount(this.srPanelContainer);\n } else {\n throw new Error('Component could not mount. Root node was not found.');\n }\n }\n }\n\n public setComponentRef = ref => {\n this.componentRef = ref;\n };\n\n public get enabled() {\n return this._enabled;\n }\n\n public get moveFocus() {\n return this._moveFocus;\n }\n\n public setAriaProps(ariaAttributes: AriaAttributes): void {\n const firstPanel = document.querySelector('[class^=\"adyen-checkout-sr-panel\"]');\n for (const [key, value] of Object.entries(ariaAttributes)) {\n firstPanel.setAttribute(key, value);\n }\n this.props = { ...this.props, ariaAttributes: { ...this.props.ariaAttributes, ...ariaAttributes } };\n }\n\n // A method we can expose to allow comps to set messages in this panel\n public setMessages = (messages: string[] | string): void => {\n if (!this.props.enabled) return;\n\n let panelMessages = null;\n if (messages) {\n // Ensure panelMessages is an array\n panelMessages = Array.isArray(messages) ? messages : [messages];\n }\n\n this.componentRef.setMessages(panelMessages);\n };\n\n render() {\n if (!this.props.enabled) return null;\n return (\n <div\n className={this.showPanel ? 'adyen-checkout-sr-panel' : 'adyen-checkout-sr-panel--sr-only'}\n role={'log'}\n {...this.props.ariaAttributes}\n {...(process.env.NODE_ENV !== 'production' && { 'data-testid': this.id })}\n >\n <SRMessages setComponentRef={this.setComponentRef} />\n </div>\n );\n }\n}\n"],"names":["SRPanel","BaseElement","enabled","this","_enabled","moveFocus","_moveFocus","setAriaProps","ariaAttributes","firstPanel","document","querySelector","key","value","Object","entries","setAttribute","props","_object_spread_props","_object_spread","render","h","div","className","showPanel","role","SRMessages","setComponentRef","constructor","checkout","_this_props_moveFocus","super","_define_property","srPanelContainer","id","componentRef","ref","setMessages","messages","panelMessages","Array","isArray","panelParent","node","Error","preExistingSRPanel","getElementById","removeChild","createElement","appendChild","mount","type","defaultProps"],"mappings":"+9BAYO,MAAMA,UAAgBC,EA4DzB,WAAWC,GACP,OAAOC,KAAKC,QAChB,CAEA,aAAWC,GACP,OAAOF,KAAKG,UAChB,CAEOC,YAAAA,CAAaC,GAChB,MAAMC,EAAaC,SAASC,cAAc,sCAC1C,IAAK,MAAOC,EAAKC,KAAUC,OAAOC,QAAQP,GACtCC,EAAWO,aAAaJ,EAAKC,GAEjCV,KAAKc,MAAQC,EAAAC,EAAA,CAAA,EAAKhB,KAAKc,OAAK,CAAET,eAAgBW,KAAKhB,KAAKc,MAAMT,eAAmBA,IACrF,CAeAY,MAAAA,GACI,OAAKjB,KAAKc,MAAMf,QAEZmB,EAACC,MAAAA,EAAAA,CACGC,UAAWpB,KAAKqB,UAAY,0BAA4B,mCACxDC,KAAM,OACFtB,KAAKc,MAAMT,gBACV,GAELa,EAACK,EAAAA,CAAWC,gBAAiBxB,KAAKwB,mBARV,IAWpC,CA7EA,WAAAC,CAAYC,EAAiBZ,GAMP,IAAAa,EAElB,GAPAC,MAAMF,EAAUZ,GAVpBe,EAAA7B,KAAiB8B,mBAAmB,MAEpCD,EAAA7B,KAAiB+B,UAAjB,GACAF,EAAA7B,KAAiBqB,iBAAjB,GACAQ,EAAA7B,KAAiBC,gBAAjB,GACA4B,EAAA7B,KAAiBG,kBAAjB,GAEA0B,EAAA7B,KAAQgC,oBAAR,GAkCAH,EAAA7B,KAAOwB,kBAAkBS,IACrBjC,KAAKgC,aAAeC,IAoBxBJ,EAAA7B,KAAOkC,cAAeC,IAClB,IAAKnC,KAAKc,MAAMf,QAAS,OAEzB,IAAIqC,EAAgB,KAChBD,IAEAC,EAAgBC,MAAMC,QAAQH,GAAYA,EAAW,CAACA,IAG1DnC,KAAKgC,aAAaE,YAAYE,KA3D9BpC,KAAK+B,GAAK/B,KAAKc,MAAMiB,GACrB/B,KAAKqB,WAA2E,EAChFrB,KAAKC,UAAW,EAChBD,KAAKG,WAAiC,QAApBwB,EAAA3B,KAAKc,MAAMZ,iBAAX,IAAAyB,GAAAA,EAEd3B,KAAKc,MAAMf,QAAS,CACpBC,KAAKC,UAAW,EAEhB,MAAMsC,EAAchC,SAASC,cAAcR,KAAKc,MAAM0B,MAEtD,IAAID,EAcA,MAAM,IAAIE,MAAM,uDAdH,CACb,MAAMC,EAAqBnC,SAASoC,eAAe3C,KAAK+B,IACpDW,GACAH,EAAYK,YAAYF,GAG5B1C,KAAK8B,iBAAmBvB,SAASsC,cAAc,OAC/C7C,KAAK8B,iBAAiBV,UAAY,kBAClCpB,KAAK8B,iBAAiBC,GAAK/B,KAAK+B,GAEhCQ,EAAYO,YAAY9C,KAAK8B,kBAE7B9B,KAAK+C,MAAM/C,KAAK8B,
|
|
1
|
+
{"version":3,"file":"SRPanel.js","sources":["../../../../src/core/Errors/SRPanel.tsx"],"sourcesContent":["import { h } from 'preact';\nimport './SRPanel.scss';\nimport { AriaAttributes, SRPanelProps } from './types';\nimport BaseElement from '../../components/internal/BaseElement/BaseElement';\nimport { SRMessages, SRMessagesRef } from './SRMessages';\nimport type { ICore } from '../types';\n\n/**\n * A panel meant to hold messages that will be read out by ScreenReaders on an aria-live=\"polite\" basis\n * Expects a string or string array of message to add to the panel to be read out\n * For testing purposes can be made visible\n */\nexport class SRPanel extends BaseElement<SRPanelProps> {\n public static type = 'srPanel';\n\n public static defaultProps: Partial<SRPanelProps> = {\n enabled: true,\n node: 'body',\n showPanel: false,\n id: 'ariaLiveSRPanel',\n ariaAttributes: {\n 'aria-relevant': 'all',\n 'aria-live': 'polite',\n 'aria-atomic': 'true'\n }\n };\n\n private readonly srPanelContainer = null;\n\n private readonly id;\n private readonly showPanel;\n private readonly _enabled: boolean;\n private readonly _moveFocus: boolean;\n\n private componentRef: SRMessagesRef;\n\n constructor(checkout: ICore, props?: SRPanelProps) {\n super(checkout, props);\n\n this.id = this.props.id;\n this.showPanel = process.env.NODE_ENV !== 'production' ? this.props.showPanel : false;\n this._enabled = false;\n this._moveFocus = this.props.moveFocus ?? true;\n\n if (this.props.enabled) {\n this._enabled = true;\n\n const panelParent = document.querySelector(this.props.node);\n\n if (panelParent) {\n const preExistingSRPanel = document.getElementById(this.id);\n if (preExistingSRPanel) {\n panelParent.removeChild(preExistingSRPanel);\n }\n\n this.srPanelContainer = document.createElement('div');\n this.srPanelContainer.className = 'sr-panel-holder';\n this.srPanelContainer.id = this.id;\n\n panelParent.appendChild(this.srPanelContainer);\n\n this.mount(this.srPanelContainer);\n } else {\n throw new Error('Component could not mount. Root node was not found.');\n }\n }\n }\n\n public setComponentRef = ref => {\n this.componentRef = ref;\n };\n\n public get enabled() {\n return this._enabled;\n }\n\n public get moveFocus() {\n return this._moveFocus;\n }\n\n public setAriaProps(ariaAttributes: AriaAttributes): void {\n const firstPanel = document.querySelector('[class^=\"adyen-checkout-sr-panel\"]');\n for (const [key, value] of Object.entries(ariaAttributes)) {\n firstPanel.setAttribute(key, value);\n }\n this.props = { ...this.props, ariaAttributes: { ...this.props.ariaAttributes, ...ariaAttributes } };\n }\n\n // A method we can expose to allow comps to set messages in this panel\n public setMessages = (messages: string[] | string): void => {\n if (!this.props.enabled) return;\n\n let panelMessages = null;\n if (messages) {\n // Ensure panelMessages is an array\n panelMessages = Array.isArray(messages) ? messages : [messages];\n }\n\n this.componentRef.setMessages(panelMessages);\n };\n\n render() {\n if (!this.props.enabled) return null;\n return (\n <div\n className={this.showPanel ? 'adyen-checkout-sr-panel' : 'adyen-checkout-sr-panel--sr-only'}\n role={'log'}\n {...this.props.ariaAttributes}\n {...(process.env.NODE_ENV !== 'production' && { 'data-testid': this.id })}\n >\n <SRMessages setComponentRef={this.setComponentRef} />\n </div>\n );\n }\n}\n"],"names":["SRPanel","BaseElement","enabled","this","_enabled","moveFocus","_moveFocus","setAriaProps","ariaAttributes","firstPanel","document","querySelector","key","value","Object","entries","setAttribute","props","_object_spread_props","_object_spread","render","h","div","className","showPanel","role","SRMessages","setComponentRef","constructor","checkout","_this_props_moveFocus","super","_define_property","srPanelContainer","id","componentRef","ref","setMessages","messages","panelMessages","Array","isArray","panelParent","node","Error","preExistingSRPanel","getElementById","removeChild","createElement","appendChild","mount","type","defaultProps"],"mappings":"+9BAYO,MAAMA,UAAgBC,EA4DzB,WAAWC,GACP,OAAOC,KAAKC,QAChB,CAEA,aAAWC,GACP,OAAOF,KAAKG,UAChB,CAEOC,YAAAA,CAAaC,GAChB,MAAMC,EAAaC,SAASC,cAAc,sCAC1C,IAAK,MAAOC,EAAKC,KAAUC,OAAOC,QAAQP,GACtCC,EAAWO,aAAaJ,EAAKC,GAEjCV,KAAKc,MAAQC,EAAAC,EAAA,CAAA,EAAKhB,KAAKc,OAAK,CAAET,eAAgBW,KAAKhB,KAAKc,MAAMT,eAAmBA,IACrF,CAeAY,MAAAA,GACI,OAAKjB,KAAKc,MAAMf,QAEZmB,EAACC,MAAAA,EAAAA,CACGC,UAAWpB,KAAKqB,UAAY,0BAA4B,mCACxDC,KAAM,OACFtB,KAAKc,MAAMT,gBACV,GAELa,EAACK,EAAAA,CAAWC,gBAAiBxB,KAAKwB,mBARV,IAWpC,CA7EA,WAAAC,CAAYC,EAAiBZ,GAMP,IAAAa,EAElB,GAPAC,MAAMF,EAAUZ,GAVpBe,EAAA7B,KAAiB8B,mBAAmB,MAEpCD,EAAA7B,KAAiB+B,UAAjB,GACAF,EAAA7B,KA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ARIO, ERROR_ACTION_FOCUS_FIELD, ErrorCodePrefixes, SF_ErrorCodes } from './constants';\nimport { SFError } from '../../components/Card/components/CardInput/types';\nimport { SortErrorsObj, SortedErrorObject, GenericError, SetSRMessagesReturnObject } from './types';\nimport { ValidationRuleResult } from '../../utils/Validator/ValidationRuleResult';\nimport { ErrorMessageObject } from '../../utils/Validator/types';\nimport {\n ENCRYPTED_CARD_NUMBER,\n ENCRYPTED_EXPIRY_DATE,\n ENCRYPTED_EXPIRY_MONTH,\n ENCRYPTED_EXPIRY_YEAR,\n ENCRYPTED_PWD_FIELD,\n ENCRYPTED_SECURITY_CODE\n} from '../../components/internal/SecuredFields/lib/constants';\nimport { AriaConfigObject } from '../../components/internal/SecuredFields/lib/types';\nimport type Language from '../../language';\n\n/**\n * Extract and translate all the errorCodes related to a specific securedField\n * @param i18n\n * @param errorCodeIdentifier - the identifier for which type of errorCodes we need to collect e.g. 'cc-num'\n */\nexport const getTranslatedErrors = (i18n: Language, errorCodeIdentifier: string): Record<SF_ErrorCodes, string> => {\n const transObj = Object.values(SF_ErrorCodes).reduce((acc, value) => {\n // Limit to errors related to specific sf\n if (value.includes(errorCodeIdentifier)) {\n acc[value] = i18n.get(value);\n }\n return acc;\n }, {}) as Record<SF_ErrorCodes, string>;\n\n return transObj;\n};\n\n/**\n * Adds a new error property to an object.\n * This error property is an object containing the translated errors, stored by code, that relate to the securedFields\n * @param originalObject - object we want to duplicate and enhance\n * @param i18n - an i18n object to use to get translations\n * @returns a duplicate of the original object with a new property: \"error\" whose value is a object containing the translated errors\n */\nexport const addErrorTranslationsToObject = (originalObj: AriaConfigObject, i18n: Language, fieldType: string): AriaConfigObject => {\n const nuObj: AriaConfigObject = { ...originalObj };\n\n const errorCodeIdentifier = fieldTypeToErrorCodeIdentifier(fieldType);\n nuObj.error = getTranslatedErrors(i18n, errorCodeIdentifier);\n\n return nuObj;\n};\n\nexport const getErrorMessageFromCode = (errorCode: string, codeMap: Record<string, string>): string => {\n let errMsg = errorCode;\n for (const [key, value] of Object.entries(codeMap)) {\n if (value === errorCode) {\n errMsg = key;\n break;\n }\n }\n return errMsg?.toLowerCase().replace(/[_.\\s]/g, '-');\n};\n\n/**\n * errorCodeIdentifiers must match the prefixes to the numbers in ERROR_CODES (Errors/constants.ts)\n * (Which in turn must match the keys in the translations files)\n */\nconst fieldTypeToErrorCodeIdentifier = (fieldType: string): string => {\n let errorCodeIdentifier;\n switch (fieldType) {\n case ENCRYPTED_CARD_NUMBER:\n errorCodeIdentifier = ErrorCodePrefixes.CC_NUM;\n break;\n case ENCRYPTED_EXPIRY_DATE:\n errorCodeIdentifier = ErrorCodePrefixes.CC_DAT;\n break;\n case ENCRYPTED_EXPIRY_MONTH:\n errorCodeIdentifier = ErrorCodePrefixes.CC_MTH;\n break;\n case ENCRYPTED_EXPIRY_YEAR:\n errorCodeIdentifier = ErrorCodePrefixes.CC_YR;\n break;\n case ENCRYPTED_SECURITY_CODE:\n errorCodeIdentifier = ErrorCodePrefixes.CC_CVC;\n break;\n case ENCRYPTED_PWD_FIELD:\n errorCodeIdentifier = ErrorCodePrefixes.KCP_PWD;\n break;\n default:\n }\n return errorCodeIdentifier;\n};\n\n/**\n * sortErrorsByLayout - takes a list of errors and a layout, and returns a sorted array of error objects with translated error messages\n *\n * @param errors - an object containing errors, referenced by field type\n * @param layout - a string[] controlling how the output error objects will be ordered. Required when it is known that the way the error object is populated can vary e.g. Card comp, &/or anything with a country selector\n * @param i18n - our internal Language mechanism\n * @param countrySpecificLabels - some errors are region specific, e.g. in the US \"postal code\" = \"zip code\", so map the fieldType value accordingly (if it is being added to the errorMessage string)\n * @param fieldTypeMappingFn - a component specific lookup function that will tell us both if we need to prepend the field type to the SR panel message, and, if so, will retrieve the correct translation for the field type\n */\nexport const sortErrorsByLayout = ({ errors, i18n, layout, countrySpecificLabels, fieldTypeMappingFn }: SortErrorsObj): SortedErrorObject[] => {\n const SR_INDICATOR_PREFIX = process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'test' ? '' : '-sr'; // Useful for testing whether SR is reading out aria-live errors (sr) or aria-describedby ones\n\n // Create array of error objects, sorted by layout\n const sortedErrors: SortedErrorObject[] = Object.entries(errors).reduce((acc, [key, value]) => {\n if (value) {\n const errObj: ValidationRuleResult | SFError | GenericError = errors[key];\n\n const TREAT_AS_SF_ERROR = 'errorI18n' in errObj && `rootNode` in errObj; // look for expected props, unique to an SFError\n\n // Some ValidationRuleResults can be passed an object in the 'errorMessage' prop (to give country specific errors)\n const ERROR_MSG_IS_OBJECT = typeof errObj.errorMessage === 'object';\n\n /**\n * Get error codes - these are used if we need to distinguish between showValidation & onBlur errors\n * - For a ValidationRuleResult or GenericError the error \"code\" is contained in the errorMessage prop.\n * - For an SFError the error \"code\" is contained in the error prop.\n */\n let errorCode: string;\n if (TREAT_AS_SF_ERROR) {\n errorCode = errObj.error;\n } else {\n /** Special handling for Address~postalCode (where the errorMessage is an object) */\n if (ERROR_MSG_IS_OBJECT) {\n /** is ValidationRuleResult w. country specific error */\n errorCode = (errObj.errorMessage as ErrorMessageObject).translationKey;\n } else {\n /** is ValidationRuleResult || GenericError || an as yet incorrectly formed error */\n errorCode = errObj.errorMessage as string;\n }\n }\n\n /**\n * Get corresponding error msg - a translated string we can place into the SRPanel\n * NOTE: the error object for a secured field already contains the error in a translated form (errorI18n).\n * For other fields we still need to translate it, so we use the errObj.errorMessage prop as a translation key\n */\n let errorMsg: string;\n if (TREAT_AS_SF_ERROR && 'errorI18n' in errObj) {\n errorMsg = errObj.errorI18n + SR_INDICATOR_PREFIX;\n } else {\n /**\n * For some fields, for a11y reasons (when the translated error msg doesn't contain a reference to the field it refers to), we need to\n * add the field type into the translated error message.\n *\n * This happens with generic errors\n * e.g. \"field.error.required\": \"Enter the %{label}\"\n * or \"invalid.format.expects\": \"%{label} Invalid format. Expected format: %{format}\"\n */\n const mappedLabel = fieldTypeMappingFn ? fieldTypeMappingFn(key, i18n, countrySpecificLabels) : ''; // Retrieve the translated field name, if required\n\n /** Special handling for Address~postalCode where the errorMessage object contains the details of the country specific format that should have been used for the postcode */\n if (ERROR_MSG_IS_OBJECT) {\n /** is ValidationRuleResult w. country specific error */\n const translationKey = (errObj.errorMessage as ErrorMessageObject).translationKey;\n const countrySpecificFormat = (errObj.errorMessage as ErrorMessageObject).translationObject.values.format;\n\n errorMsg = `${i18n.get(translationKey, { values: { label: mappedLabel, format: countrySpecificFormat } })}${SR_INDICATOR_PREFIX}`;\n } else {\n /** is ValidationRuleResult || GenericError || an as yet incorrectly formed error */\n errorMsg = i18n.get(errObj.errorMessage as string, { values: { label: mappedLabel } }) + SR_INDICATOR_PREFIX;\n }\n }\n\n acc.push({ field: key, errorMessage: errorMsg, errorCode });\n\n if (layout) acc.sort((a, b) => layout.indexOf(a.field) - layout.indexOf(b.field));\n }\n return acc;\n }, []);\n\n return sortedErrors;\n};\n\n/**\n * Implemented as a partial, with an object containing the first 6 arguments; then the final argument, errors, is passed to the partial\n *\n * NOTE: using this generic error setting fny is only suitable when errors for the SRPanel are *only* generated by showValidation().\n * When errors are also generated onBlur, as the user leaves the input, the SR message generation becomes more complex - see CardInput as an example\n */\nexport const setSRMessagesFromErrors = (\n { i18n, fieldTypeMappingFn, SRPanelRef },\n { errors, isValidating, layout, countrySpecificLabels }\n): SetSRMessagesReturnObject => {\n const currentErrorsSortedByLayout = sortErrorsByLayout({\n errors,\n i18n,\n fieldTypeMappingFn,\n countrySpecificLabels,\n layout\n });\n\n const doLog = false;\n\n if (doLog) console.log('### setSRMessagesFromErrors::currentErrorsSortedByLayout:: ', currentErrorsSortedByLayout);\n\n if (currentErrorsSortedByLayout.length) {\n /** If validating i.e. \"on submit\" type event - then display all errors in the SR panel */\n if (isValidating) {\n const errorMsgArr: string[] = currentErrorsSortedByLayout.map(errObj => errObj.errorMessage);\n if (doLog) console.log('### setSRMessagesFromErrors:: #1 multiple errors:: (validating) errorMsgArr=', errorMsgArr);\n SRPanelRef.setMessages(errorMsgArr);\n\n const fieldListArr: string[] = currentErrorsSortedByLayout.map(errObj => errObj.field);\n return { currentErrorsSortedByLayout, action: ERROR_ACTION_FOCUS_FIELD, fieldToFocus: fieldListArr[0] };\n } else {\n // prettier-ignore\n if (doLog) console.log('### setSRMessagesFromErrors:: #3 on blur scenario:: not validating but there might be an error, either to set or to clear');\n SRPanelRef?.setMessages(null);\n\n return { currentErrorsSortedByLayout, action: ERROR_ACTION_BLUR_SCENARIO }; // on blur scenario: not validating but there might be an error, either to set or to clear\n }\n } else {\n if (doLog) console.log('### setSRMessagesFromErrors::componentDidUpdate:: #4 clearing errors:: NO currentErrorsSortedByLayout');\n SRPanelRef?.setMessages(null); // no errors - so clear SR panel\n return { currentErrorsSortedByLayout, action: 'none' };\n }\n};\n\nexport const enhanceErrorObjectKeys = (errorObj, keyPrefix) => {\n if (!errorObj) return null;\n const enhancedObj = Object.entries(errorObj).reduce((acc, [key, value]) => {\n if (value) {\n const newKey = `${keyPrefix}${key}`;\n acc[newKey] = value;\n }\n return acc;\n }, {});\n\n return enhancedObj;\n};\n"],"names":["getTranslatedErrors","i18n","errorCodeIdentifier","Object","values","SF_ErrorCodes","reduce","acc","value","includes","get","addErrorTranslationsToObject","originalObj","fieldType","nuObj","_object_spread","fieldTypeToErrorCodeIdentifier","error","getErrorMessageFromCode","errorCode","codeMap","errMsg","key","entries","toLowerCase","replace","ENCRYPTED_CARD_NUMBER","ErrorCodePrefixes","CC_NUM","ENCRYPTED_EXPIRY_DATE","CC_DAT","ENCRYPTED_EXPIRY_MONTH","CC_MTH","ENCRYPTED_EXPIRY_YEAR","CC_YR","ENCRYPTED_SECURITY_CODE","CC_CVC","ENCRYPTED_PWD_FIELD","KCP_PWD","sortErrorsByLayout","errors","layout","countrySpecificLabels","fieldTypeMappingFn","errObj","TREAT_AS_SF_ERROR","ERROR_MSG_IS_OBJECT","errorMessage","errorMsg","translationKey","errorI18n","mappedLabel","countrySpecificFormat","translationObject","format","label","push","field","sort","a","b","indexOf","setSRMessagesFromErrors","SRPanelRef","isValidating","currentErrorsSortedByLayout","length","errorMsgArr","map","setMessages","fieldListArr","action","ERROR_ACTION_FOCUS_FIELD","fieldToFocus","ERROR_ACTION_BLUR_SCENARIO","enhanceErrorObjectKeys","errorObj","keyPrefix"],"mappings":"qeAqBO,MAAMA,EAAsB,CAACC,EAAgBC,IAC/BC,OAAOC,OAAOC,GAAeC,OAAO,CAACC,EAAKC,KAEnDA,EAAMC,SAASP,KACfK,EAAIC,GAASP,EAAKS,IAAIF,IAEnBD,GACR,IAYMI,EAA+B,CAACC,EAA+BX,EAAgBY,KACxF,MAAMC,oUAA0BC,CAAA,CAAA,EAAKH,GAE/BV,EAAsBc,EAA+BH,GAG3D,OAFAC,EAAMG,MAAQjB,EAAoBC,EAAMC,GAEjCY,GAGEI,EAA0B,CAACC,EAAmBC,KACvD,IAAIC,EAASF,EACb,IAAK,MAAOG,EAAKd,KAAUL,OAAOoB,QAAQH,GACtC,GAAIZ,IAAUW,EAAW,CACrBE,EAASC,EACT,KACJ,CAEJ,OAAOD,aAAAA,EAAAA,EAAQG,cAAcC,QAAQ,UAAW,MAO9CT,EAAkCH,IACpC,IAAIX,EACJ,OAAQW,GACJ,KAAKa,EACDxB,EAAsByB,EAAkBC,OACxC,MACJ,KAAKC,EACD3B,EAAsByB,EAAkBG,OACxC,MACJ,KAAKC,EACD7B,EAAsByB,EAAkBK,OACxC,MACJ,KAAKC,EACD/B,EAAsByB,EAAkBO,MACxC,MACJ,KAAKC,EACDjC,EAAsByB,EAAkBS,OACxC,MACJ,KAAKC,EACDnC,EAAsByB,EAAkBW,QAIhD,OAAOpC,GAYEqC,EAAqB,EAAGC,SAAQvC,OAAMwC,SAAQC,wBAAuBC,wBAIpCxC,OAAOoB,QAAQiB,GAAQlC,OAAO,CAACC,GAAMe,EAAKd,MAChF,GAAIA,EAAO,CACP,MAAMoC,EAAwDJ,EAAOlB,GAE/DuB,EAAoB,cAAeD,GAAU,aAAcA,EAG3DE,EAAqD,iBAAxBF,EAAOG,aAO1C,I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AAQ,SAIzCI,EAAyB,CAACC,EAAUC,KAC7C,IAAKD,EAAU,OAAO,KAStB,OARoBzE,OAAOoB,QAAQqD,GAAUtE,OAAO,CAACC,GAAMe,EAAKd,MAC5D,GAAIA,EAAO,CAEPD,EADe,GAAGsE,IAAYvD,KAChBd,CAClB,CACA,OAAOD,GACR"}
|
|
1
|
+
{"version":3,"file":"utils.js","sources":["../../../../src/core/Errors/utils.ts"],"sourcesContent":["import { ERROR_ACTION_BLUR_SCENARIO, ERROR_ACTION_FOCUS_FIELD, ErrorCodePrefixes, SF_ErrorCodes } from './constants';\nimport { SFError } from '../../components/Card/components/CardInput/types';\nimport { SortErrorsObj, SortedErrorObject, GenericError, SetSRMessagesReturnObject } from './types';\nimport { ValidationRuleResult } from '../../utils/Validator/ValidationRuleResult';\nimport { ErrorMessageObject } from '../../utils/Validator/types';\nimport {\n ENCRYPTED_CARD_NUMBER,\n ENCRYPTED_EXPIRY_DATE,\n ENCRYPTED_EXPIRY_MONTH,\n ENCRYPTED_EXPIRY_YEAR,\n ENCRYPTED_PWD_FIELD,\n ENCRYPTED_SECURITY_CODE\n} from '../../components/internal/SecuredFields/lib/constants';\nimport { AriaConfigObject } from '../../components/internal/SecuredFields/lib/types';\nimport type Language from '../../language';\n\n/**\n * Extract and translate all the errorCodes related to a specific securedField\n * @param i18n\n * @param errorCodeIdentifier - the identifier for which type of errorCodes we need to collect e.g. 'cc-num'\n */\nexport const getTranslatedErrors = (i18n: Language, errorCodeIdentifier: string): Record<SF_ErrorCodes, string> => {\n const transObj = Object.values(SF_ErrorCodes).reduce((acc, value) => {\n // Limit to errors related to specific sf\n if (value.includes(errorCodeIdentifier)) {\n acc[value] = i18n.get(value);\n }\n return acc;\n }, {}) as Record<SF_ErrorCodes, string>;\n\n return transObj;\n};\n\n/**\n * Adds a new error property to an object.\n * This error property is an object containing the translated errors, stored by code, that relate to the securedFields\n * @param originalObject - object we want to duplicate and enhance\n * @param i18n - an i18n object to use to get translations\n * @returns a duplicate of the original object with a new property: \"error\" whose value is a object containing the translated errors\n */\nexport const addErrorTranslationsToObject = (originalObj: AriaConfigObject, i18n: Language, fieldType: string): AriaConfigObject => {\n const nuObj: AriaConfigObject = { ...originalObj };\n\n const errorCodeIdentifier = fieldTypeToErrorCodeIdentifier(fieldType);\n nuObj.error = getTranslatedErrors(i18n, errorCodeIdentifier);\n\n return nuObj;\n};\n\nexport const getErrorMessageFromCode = (errorCode: string, codeMap: Record<string, string>): string => {\n let errMsg = errorCode;\n for (const [key, value] of Object.entries(codeMap)) {\n if (value === errorCode) {\n errMsg = key;\n break;\n }\n }\n return errMsg?.toLowerCase().replace(/[_.\\s]/g, '-');\n};\n\n/**\n * errorCodeIdentifiers must match the prefixes to the numbers in ERROR_CODES (Errors/constants.ts)\n * (Which in turn must match the keys in the translations files)\n */\nconst fieldTypeToErrorCodeIdentifier = (fieldType: string): string => {\n let errorCodeIdentifier;\n switch (fieldType) {\n case ENCRYPTED_CARD_NUMBER:\n errorCodeIdentifier = ErrorCodePrefixes.CC_NUM;\n break;\n case ENCRYPTED_EXPIRY_DATE:\n errorCodeIdentifier = ErrorCodePrefixes.CC_DAT;\n break;\n case ENCRYPTED_EXPIRY_MONTH:\n errorCodeIdentifier = ErrorCodePrefixes.CC_MTH;\n break;\n case ENCRYPTED_EXPIRY_YEAR:\n errorCodeIdentifier = ErrorCodePrefixes.CC_YR;\n break;\n case ENCRYPTED_SECURITY_CODE:\n errorCodeIdentifier = ErrorCodePrefixes.CC_CVC;\n break;\n case ENCRYPTED_PWD_FIELD:\n errorCodeIdentifier = ErrorCodePrefixes.KCP_PWD;\n break;\n default:\n }\n return errorCodeIdentifier;\n};\n\n/**\n * sortErrorsByLayout - takes a list of errors and a layout, and returns a sorted array of error objects with translated error messages\n *\n * @param errors - an object containing errors, referenced by field type\n * @param layout - a string[] controlling how the output error objects will be ordered. Required when it is known that the way the error object is populated can vary e.g. Card comp, &/or anything with a country selector\n * @param i18n - our internal Language mechanism\n * @param countrySpecificLabels - some errors are region specific, e.g. in the US \"postal code\" = \"zip code\", so map the fieldType value accordingly (if it is being added to the errorMessage string)\n * @param fieldTypeMappingFn - a component specific lookup function that will tell us both if we need to prepend the field type to the SR panel message, and, if so, will retrieve the correct translation for the field type\n */\nexport const sortErrorsByLayout = ({ errors, i18n, layout, countrySpecificLabels, fieldTypeMappingFn }: SortErrorsObj): SortedErrorObject[] => {\n const SR_INDICATOR_PREFIX = process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'test' ? '' : '-sr'; // Useful for testing whether SR is reading out aria-live errors (sr) or aria-describedby ones\n\n // Create array of error objects, sorted by layout\n const sortedErrors: SortedErrorObject[] = Object.entries(errors).reduce((acc, [key, value]) => {\n if (value) {\n const errObj: ValidationRuleResult | SFError | GenericError = errors[key];\n\n const TREAT_AS_SF_ERROR = 'errorI18n' in errObj && `rootNode` in errObj; // look for expected props, unique to an SFError\n\n // Some ValidationRuleResults can be passed an object in the 'errorMessage' prop (to give country specific errors)\n const ERROR_MSG_IS_OBJECT = typeof errObj.errorMessage === 'object';\n\n /**\n * Get error codes - these are used if we need to distinguish between showValidation & onBlur errors\n * - For a ValidationRuleResult or GenericError the error \"code\" is contained in the errorMessage prop.\n * - For an SFError the error \"code\" is contained in the error prop.\n */\n let errorCode: string;\n if (TREAT_AS_SF_ERROR) {\n errorCode = errObj.error;\n } else {\n /** Special handling for Address~postalCode (where the errorMessage is an object) */\n if (ERROR_MSG_IS_OBJECT) {\n /** is ValidationRuleResult w. country specific error */\n errorCode = (errObj.errorMessage as ErrorMessageObject).translationKey;\n } else {\n /** is ValidationRuleResult || GenericError || an as yet incorrectly formed error */\n errorCode = errObj.errorMessage as string;\n }\n }\n\n /**\n * Get corresponding error msg - a translated string we can place into the SRPanel\n * NOTE: the error object for a secured field already contains the error in a translated form (errorI18n).\n * For other fields we still need to translate it, so we use the errObj.errorMessage prop as a translation key\n */\n let errorMsg: string;\n if (TREAT_AS_SF_ERROR && 'errorI18n' in errObj) {\n errorMsg = errObj.errorI18n + SR_INDICATOR_PREFIX;\n } else {\n /**\n * For some fields, for a11y reasons (when the translated error msg doesn't contain a reference to the field it refers to), we need to\n * add the field type into the translated error message.\n *\n * This happens with generic errors\n * e.g. \"field.error.required\": \"Enter the %{label}\"\n * or \"invalid.format.expects\": \"%{label} Invalid format. Expected format: %{format}\"\n */\n const mappedLabel = fieldTypeMappingFn ? fieldTypeMappingFn(key, i18n, countrySpecificLabels) : ''; // Retrieve the translated field name, if required\n\n /** Special handling for Address~postalCode where the errorMessage object contains the details of the country specific format that should have been used for the postcode */\n if (ERROR_MSG_IS_OBJECT) {\n /** is ValidationRuleResult w. country specific error */\n const translationKey = (errObj.errorMessage as ErrorMessageObject).translationKey;\n const countrySpecificFormat = (errObj.errorMessage as ErrorMessageObject).translationObject.values.format;\n\n errorMsg = `${i18n.get(translationKey, { values: { label: mappedLabel, format: countrySpecificFormat } })}${SR_INDICATOR_PREFIX}`;\n } else {\n /** is ValidationRuleResult || GenericError || an as yet incorrectly formed error */\n errorMsg = i18n.get(errObj.errorMessage as string, { values: { label: mappedLabel } }) + SR_INDICATOR_PREFIX;\n }\n }\n\n acc.push({ field: key, errorMessage: errorMsg, errorCode });\n\n if (layout) acc.sort((a, b) => layout.indexOf(a.field) - layout.indexOf(b.field));\n }\n return acc;\n }, []);\n\n return sortedErrors;\n};\n\n/**\n * Implemented as a partial, with an object containing the first 6 arguments; then the final argument, errors, is passed to the partial\n *\n * NOTE: using this generic error setting fny is only suitable when errors for the SRPanel are *only* generated by showValidation().\n * When errors are also generated onBlur, as the user leaves the input, the SR message generation becomes more complex - see CardInput as an example\n */\nexport const setSRMessagesFromErrors = (\n { i18n, fieldTypeMappingFn, SRPanelRef },\n { errors, isValidating, layout, countrySpecificLabels }\n): SetSRMessagesReturnObject => {\n const currentErrorsSortedByLayout = sortErrorsByLayout({\n errors,\n i18n,\n fieldTypeMappingFn,\n countrySpecificLabels,\n layout\n });\n\n const doLog = false;\n\n if (doLog) console.log('### setSRMessagesFromErrors::currentErrorsSortedByLayout:: ', currentErrorsSortedByLayout);\n\n if (currentErrorsSortedByLayout.length) {\n /** If validating i.e. \"on submit\" type event - then display all errors in the SR panel */\n if (isValidating) {\n const errorMsgArr: string[] = currentErrorsSortedByLayout.map(errObj => errObj.errorMessage);\n if (doLog) console.log('### setSRMessagesFromErrors:: #1 multiple errors:: (validating) errorMsgArr=', errorMsgArr);\n SRPanelRef.setMessages(errorMsgArr);\n\n const fieldListArr: string[] = currentErrorsSortedByLayout.map(errObj => errObj.field);\n return { currentErrorsSortedByLayout, action: ERROR_ACTION_FOCUS_FIELD, fieldToFocus: fieldListArr[0] };\n } else {\n // prettier-ignore\n if (doLog) console.log('### setSRMessagesFromErrors:: #3 on blur scenario:: not validating but there might be an error, either to set or to clear');\n SRPanelRef?.setMessages(null);\n\n return { currentErrorsSortedByLayout, action: ERROR_ACTION_BLUR_SCENARIO }; // on blur scenario: not validating but there might be an error, either to set or to clear\n }\n } else {\n if (doLog) console.log('### setSRMessagesFromErrors::componentDidUpdate:: #4 clearing errors:: NO currentErrorsSortedByLayout');\n SRPanelRef?.setMessages(null); // no errors - so clear SR panel\n return { currentErrorsSortedByLayout, action: 'none' };\n }\n};\n\nexport const enhanceErrorObjectKeys = (errorObj, keyPrefix) => {\n if (!errorObj) return null;\n const enhancedObj = Object.entries(errorObj).reduce((acc, [key, value]) => {\n if (value) {\n const newKey = `${keyPrefix}${key}`;\n acc[newKey] = value;\n }\n return acc;\n }, {});\n\n return enhancedObj;\n};\n"],"names":["getTranslatedErrors","i18n","errorCodeIdentifier","Object","values","SF_ErrorCodes","reduce","acc","value","includes","get","addErrorTranslationsToObject","originalObj","fieldType","nuObj","_object_spread","fieldTypeToErrorCodeIdentifier","error","getErrorMessageFromCode","errorCode","codeMap","errMsg","key","entries","toLowerCase","replace","ENCRYPTED_CARD_NUMBER","ErrorCodePrefixes","CC_NUM","ENCRYPTED_EXPIRY_DATE","CC_DAT","ENCRYPTED_EXPIRY_MONTH","CC_MTH","ENCRYPTED_EXPIRY_YEAR","CC_YR","ENCRYPTED_SECURITY_CODE","CC_CVC","ENCRYPTED_PWD_FIELD","KCP_PWD","sortErrorsByLayout","errors","layout","countrySpecificLabels","fieldTypeMappingFn","errObj","TREAT_AS_SF_ERROR","ERROR_MSG_IS_OBJECT","errorMessage","errorMsg","translationKey","errorI18n","mappedLabel","countrySpecificFormat","translationObject","format","label","push","field","sort","a","b","indexOf","setSRMessagesFromErrors","SRPanelRef","isValidating","currentErrorsSortedByLayout","length","errorMsgArr","map","setMessages","fieldListArr","action","ERROR_ACTION_FOCUS_FIELD","fieldToFocus","ERROR_ACTION_BLUR_SCENARIO","enhanceErrorObjectKeys","errorObj","keyPrefix"],"mappings":"qeAqBO,MAAMA,EAAsB,CAACC,EAAgBC,IAC/BC,OAAOC,OAAOC,GAAeC,OAAO,CAACC,EAAKC,KAEnDA,EAAMC,SAASP,KACfK,EAAIC,GAASP,EAAKS,IAAIF,IAEnBD,GACR,CAAA,GAYMI,EAA+B,CAACC,EAA+BX,EAAgBY,KACxF,MAAMC,oUAA0BC,CAAA,CAAA,EAAKH,GAE/BV,EAAsBc,EAA+BH,GAG3D,OAFAC,EAAMG,MAAQjB,EAAoBC,EAAMC,GAEjCY,GAGEI,EAA0B,CAACC,EAAmBC,KACvD,IAAIC,EAASF,EACb,IAAK,MAAOG,EAAKd,KAAUL,OAAOoB,QAAQH,GACtC,GAAIZ,IAAUW,EAAW,CACrBE,EAASC,EACT,KACJ,CAEJ,OAAOD,aAAAA,EAAAA,EAAQG,cAAcC,QAAQ,UAAW,MAO9CT,EAAkCH,IACpC,IAAIX,EACJ,OAAQW,GACJ,KAAKa,EACDxB,EAAsByB,EAAkBC,OACxC,MACJ,KAAKC,EACD3B,EAAsByB,EAAkBG,OACxC,MACJ,KAAKC,EACD7B,EAAsByB,EAAkBK,OACxC,MACJ,KAAKC,EACD/B,EAAsByB,EAAkBO,MACxC,MACJ,KAAKC,EACDjC,EAAsByB,EAAkBS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d,MAAMG,EAAwBF,EAA4BG,IAAIxB,GAAUA,EAAOG,cAE/EgB,EAAWM,YAAYF,GAEvB,MAAMG,EAAyBL,EAA4BG,IAAIxB,GAAUA,EAAOa,OAChF,MAAO,CAAEQ,8BAA6BM,OAAQC,EAA0BC,aAAcH,EAAa,GACvG,CAKI,OAFAP,SAAAA,EAAYM,YAAY,MAEjB,CAAEJ,8BAA6BM,OAAQG,EAEtD,CAGI,OADAX,SAAAA,EAAYM,YAAY,MACjB,CAAEJ,8BAA6BM,OAAQ,SAIzCI,EAAyB,CAACC,EAAUC,KAC7C,IAAKD,EAAU,OAAO,KAStB,OARoBzE,OAAOoB,QAAQqD,GAAUtE,OAAO,CAACC,GAAMe,EAAKd,MAC5D,GAAIA,EAAO,CAEPD,EADe,GAAGsE,IAAYvD,KAChBd,CAClB,CACA,OAAOD,GACR,CAAA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{httpPost as e}from"../http.js";import t from"../../../utils/Storage.js";function n(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const r='WARNING: Failed to retrieve "checkoutAttemptId". Consequently, analytics will not be available for this payment. The payment process, however, will not be affected.';const o=({analyticsContext:o,clientKey:i,locale:c,analyticsPath:l,bundleType:a})=>{let s;const u={errorLevel:"fatal",loadingContext:o,path:`${l}?clientKey=${i}`};return o=>{const l=function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{},o=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(o=o.concat(Object.getOwnPropertySymbols(r).filter(function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable}))),o.forEach(function(t){n(e,t,r[t])})}return e}({version:"6.
|
|
1
|
+
import{httpPost as e}from"../http.js";import t from"../../../utils/Storage.js";function n(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const r='WARNING: Failed to retrieve "checkoutAttemptId". Consequently, analytics will not be available for this payment. The payment process, however, will not be affected.';const o=({analyticsContext:o,clientKey:i,locale:c,analyticsPath:l,bundleType:a})=>{let s;const u={errorLevel:"fatal",loadingContext:o,path:`${l}?clientKey=${i}`};return o=>{const l=function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{},o=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(o=o.concat(Object.getOwnPropertySymbols(r).filter(function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable}))),o.forEach(function(t){n(e,t,r[t])})}return e}({version:"6.20.0",channel:"Web",platform:"Web",buildType:a,locale:c,referrer:window.location.href,screenWidth:window.screen.width},o);if(s)return s;if(!i)return Promise.reject("no-client-key");const f=new t("checkout-attempt-id","sessionStorage"),p=f.get();return function(e){if(!(null==e?void 0:e.id))return!1;const t=Date.now()-9e5;return e.timestamp>t}(p)?Promise.resolve(p.id):(s=e(u,l).then(e=>{if(null==e?void 0:e.checkoutAttemptId)return f.set({id:e.checkoutAttemptId,timestamp:Date.now()}),e.checkoutAttemptId}).catch(()=>Promise.reject(r)),s)}};export{r as FAILURE_MSG,o as default};
|
|
2
2
|
//# sourceMappingURL=collect-id.js.map
|