@adyen/adyen-web 6.0.0-alpha.6 → 6.0.0-alpha.8
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/dist/cjs/adyen.css +6 -6
- 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 +2360 -2035
- package/dist/es/adyen.css +6 -6
- package/dist/es/adyen.css.map +1 -1
- package/dist/es/components/ANCV/ANCV.js +1 -1
- package/dist/es/components/ANCV/ANCV.js.map +1 -1
- package/dist/es/components/ANCV/components/ANCVInput.js.map +1 -1
- package/dist/es/components/Ach/components/AchInput/AchInput.js +1 -1
- package/dist/es/components/Ach/components/AchInput/AchInput.js.map +1 -1
- package/dist/es/components/Ach/components/AchInput/defaultProps.js +1 -1
- package/dist/es/components/Ach/components/AchInput/defaultProps.js.map +1 -1
- package/dist/es/components/AfterPay/AfterPayB2B.js +1 -1
- package/dist/es/components/AfterPay/AfterPayB2B.js.map +1 -1
- package/dist/es/components/BacsDD/BacsDD.js +1 -1
- package/dist/es/components/BacsDD/BacsDD.js.map +1 -1
- package/dist/es/components/BacsDD/components/BacsInput.js +1 -1
- package/dist/es/components/BacsDD/components/BacsInput.js.map +1 -1
- package/dist/es/components/Blik/components/BlikInput.js.map +1 -1
- package/dist/es/components/Boleto/components/BoletoInput/BoletoInput.js +1 -1
- package/dist/es/components/Boleto/components/BoletoInput/BoletoInput.js.map +1 -1
- package/dist/es/components/Card/Card.js +1 -1
- package/dist/es/components/Card/Card.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/CardInput.js +1 -1
- package/dist/es/components/Card/components/CardInput/CardInput.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/defaultProps.js +1 -1
- package/dist/es/components/Card/components/CardInput/defaultProps.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/types.js.map +1 -1
- package/dist/es/components/Card/components/CardInput/utils.js +1 -1
- package/dist/es/components/Card/components/CardInput/utils.js.map +1 -1
- package/dist/es/components/Doku/Doku.js +1 -1
- package/dist/es/components/Doku/Doku.js.map +1 -1
- package/dist/es/components/Doku/components/DokuInput/DokuInput.js +1 -1
- package/dist/es/components/Doku/components/DokuInput/DokuInput.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/Econtext/Econtext.js +1 -1
- package/dist/es/components/Econtext/Econtext.js.map +1 -1
- package/dist/es/components/Econtext/components/EcontextInput/EcontextInput.js +1 -1
- package/dist/es/components/Econtext/components/EcontextInput/EcontextInput.js.map +1 -1
- package/dist/es/components/GooglePay/GooglePay.js.map +1 -1
- package/dist/es/components/PersonalDetails/PersonalDetails.js +1 -1
- package/dist/es/components/PersonalDetails/PersonalDetails.js.map +1 -1
- package/dist/es/components/Sepa/Sepa.js +1 -1
- package/dist/es/components/Sepa/Sepa.js.map +1 -1
- package/dist/es/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.js +1 -1
- package/dist/es/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.js.map +1 -1
- package/dist/es/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.js +1 -1
- package/dist/es/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.js.map +1 -1
- package/dist/es/components/helpers/OpenInvoiceContainer/OpenInvoiceContainer.js +1 -1
- package/dist/es/components/helpers/OpenInvoiceContainer/OpenInvoiceContainer.js.map +1 -1
- package/dist/es/components/internal/BaseElement/BaseElement.js +1 -1
- package/dist/es/components/internal/BaseElement/BaseElement.js.map +1 -1
- package/dist/es/components/internal/OpenInvoice/OpenInvoice.js +1 -1
- package/dist/es/components/internal/OpenInvoice/OpenInvoice.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/SFP/SecuredFieldsProvider.js +1 -1
- package/dist/es/components/internal/SecuredFields/SFP/SecuredFieldsProvider.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/lib/CSF/extensions/createSecuredFields.js +1 -1
- package/dist/es/components/internal/SecuredFields/lib/CSF/extensions/createSecuredFields.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/lib/CSF/extensions/handleEncryption.js +1 -1
- package/dist/es/components/internal/SecuredFields/lib/CSF/extensions/handleEncryption.js.map +1 -1
- package/dist/es/components/internal/SecuredFields/lib/constants.js +1 -1
- package/dist/es/components/internal/SecuredFields/lib/constants.js.map +1 -1
- 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/tx-variants.js +1 -1
- package/dist/es/components/tx-variants.js.map +1 -1
- package/dist/es/core/Analytics/analyticsPreProcessor.js +1 -1
- package/dist/es/core/Analytics/analyticsPreProcessor.js.map +1 -1
- package/dist/es/core/Analytics/constants.js +1 -1
- package/dist/es/core/Analytics/constants.js.map +1 -1
- package/dist/es/core/Analytics/utils.js +1 -1
- package/dist/es/core/Analytics/utils.js.map +1 -1
- package/dist/es/core/ProcessResponse/PaymentAction/PaymentAction.js.map +1 -1
- package/dist/es/core/ProcessResponse/PaymentAction/actionTypes.js +1 -1
- package/dist/es/core/ProcessResponse/PaymentAction/actionTypes.js.map +1 -1
- package/dist/es/core/Services/analytics/collect-id.js +1 -1
- package/dist/es/core/Services/analytics/log-event.js +1 -1
- package/dist/es/core/config.js +1 -1
- package/dist/es/core/config.js.map +1 -1
- package/dist/es/core/core.js +1 -1
- package/dist/es/core/core.js.map +1 -1
- package/dist/es/core/core.registry.js +1 -1
- package/dist/es/core/core.registry.js.map +1 -1
- package/dist/es/external/preact/dist/preact.js +1 -1
- package/dist/es/external/preact/dist/preact.js.map +1 -1
- package/dist/es/index.d.ts +2360 -2035
- package/dist/es-legacy/adyen.css +6 -6
- package/dist/es-legacy/adyen.css.map +1 -1
- package/dist/es-legacy/components/ANCV/ANCV.js +1 -1
- package/dist/es-legacy/components/ANCV/ANCV.js.map +1 -1
- package/dist/es-legacy/components/ANCV/components/ANCVInput.js.map +1 -1
- package/dist/es-legacy/components/Ach/components/AchInput/AchInput.js +1 -1
- package/dist/es-legacy/components/Ach/components/AchInput/AchInput.js.map +1 -1
- package/dist/es-legacy/components/Ach/components/AchInput/defaultProps.js +1 -1
- package/dist/es-legacy/components/Ach/components/AchInput/defaultProps.js.map +1 -1
- package/dist/es-legacy/components/AfterPay/AfterPayB2B.js +1 -1
- package/dist/es-legacy/components/AfterPay/AfterPayB2B.js.map +1 -1
- package/dist/es-legacy/components/BacsDD/BacsDD.js +1 -1
- package/dist/es-legacy/components/BacsDD/BacsDD.js.map +1 -1
- package/dist/es-legacy/components/BacsDD/components/BacsInput.js +1 -1
- package/dist/es-legacy/components/BacsDD/components/BacsInput.js.map +1 -1
- package/dist/es-legacy/components/Blik/components/BlikInput.js.map +1 -1
- package/dist/es-legacy/components/Boleto/components/BoletoInput/BoletoInput.js +1 -1
- package/dist/es-legacy/components/Boleto/components/BoletoInput/BoletoInput.js.map +1 -1
- package/dist/es-legacy/components/Card/Card.js +1 -1
- package/dist/es-legacy/components/Card/Card.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/CardInput.js +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/CardInput.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/defaultProps.js +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/defaultProps.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/types.js.map +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/utils.js +1 -1
- package/dist/es-legacy/components/Card/components/CardInput/utils.js.map +1 -1
- package/dist/es-legacy/components/Doku/Doku.js +1 -1
- package/dist/es-legacy/components/Doku/Doku.js.map +1 -1
- package/dist/es-legacy/components/Doku/components/DokuInput/DokuInput.js +1 -1
- package/dist/es-legacy/components/Doku/components/DokuInput/DokuInput.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/Econtext/Econtext.js +1 -1
- package/dist/es-legacy/components/Econtext/Econtext.js.map +1 -1
- package/dist/es-legacy/components/Econtext/components/EcontextInput/EcontextInput.js +1 -1
- package/dist/es-legacy/components/Econtext/components/EcontextInput/EcontextInput.js.map +1 -1
- package/dist/es-legacy/components/GooglePay/GooglePay.js.map +1 -1
- package/dist/es-legacy/components/PersonalDetails/PersonalDetails.js +1 -1
- package/dist/es-legacy/components/PersonalDetails/PersonalDetails.js.map +1 -1
- package/dist/es-legacy/components/Sepa/Sepa.js +1 -1
- package/dist/es-legacy/components/Sepa/Sepa.js.map +1 -1
- package/dist/es-legacy/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.js +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 +1 -1
- package/dist/es-legacy/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.js.map +1 -1
- package/dist/es-legacy/components/helpers/OpenInvoiceContainer/OpenInvoiceContainer.js +1 -1
- package/dist/es-legacy/components/helpers/OpenInvoiceContainer/OpenInvoiceContainer.js.map +1 -1
- package/dist/es-legacy/components/internal/BaseElement/BaseElement.js +1 -1
- package/dist/es-legacy/components/internal/BaseElement/BaseElement.js.map +1 -1
- package/dist/es-legacy/components/internal/OpenInvoice/OpenInvoice.js +1 -1
- package/dist/es-legacy/components/internal/OpenInvoice/OpenInvoice.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/SFP/SecuredFieldsProvider.js +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/SFP/SecuredFieldsProvider.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/extensions/createSecuredFields.js +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/extensions/createSecuredFields.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/extensions/handleEncryption.js +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/extensions/handleEncryption.js.map +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/constants.js +1 -1
- package/dist/es-legacy/components/internal/SecuredFields/lib/constants.js.map +1 -1
- 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/tx-variants.js +1 -1
- package/dist/es-legacy/components/tx-variants.js.map +1 -1
- package/dist/es-legacy/core/Analytics/analyticsPreProcessor.js +1 -1
- package/dist/es-legacy/core/Analytics/analyticsPreProcessor.js.map +1 -1
- package/dist/es-legacy/core/Analytics/constants.js +1 -1
- package/dist/es-legacy/core/Analytics/constants.js.map +1 -1
- package/dist/es-legacy/core/Analytics/utils.js +1 -1
- package/dist/es-legacy/core/Analytics/utils.js.map +1 -1
- package/dist/es-legacy/core/ProcessResponse/PaymentAction/PaymentAction.js.map +1 -1
- package/dist/es-legacy/core/ProcessResponse/PaymentAction/actionTypes.js +1 -1
- package/dist/es-legacy/core/ProcessResponse/PaymentAction/actionTypes.js.map +1 -1
- package/dist/es-legacy/core/Services/analytics/collect-id.js +1 -1
- package/dist/es-legacy/core/Services/analytics/log-event.js +1 -1
- package/dist/es-legacy/core/config.js +1 -1
- package/dist/es-legacy/core/config.js.map +1 -1
- package/dist/es-legacy/core/core.js +1 -1
- package/dist/es-legacy/core/core.js.map +1 -1
- package/dist/es-legacy/core/core.registry.js +1 -1
- package/dist/es-legacy/core/core.registry.js.map +1 -1
- package/dist/es-legacy/external/preact/dist/preact.js +1 -1
- package/dist/es-legacy/external/preact/dist/preact.js.map +1 -1
- package/package.json +4 -6
package/dist/es/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PrepareFingerprint3DS2.js","sources":["../../../../../../src/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.tsx"],"sourcesContent":["import { Component, h } from 'preact';\nimport DoFingerprint3DS2 from './DoFingerprint3DS2';\nimport { createFingerprintResolveData, createOldFingerprintResolveData, isErrorObject, prepareFingerPrintData } from '../utils';\nimport { PrepareFingerprint3DS2Props, PrepareFingerprint3DS2State } from './types';\nimport { FingerPrintData, ResultObject, ErrorCodeObject } from '../../types';\nimport { ErrorObject } from '../../../../core/Errors/types';\nimport { ActionHandledReturnObject } from '../../../../types/global-types';\nimport { SendAnalyticsObject } from '../../../../core/Analytics/types';\nimport { isValidHttpUrl } from '../../../../utils/isValidURL';\nimport {\n THREEDS2_FULL,\n THREEDS2_FINGERPRINT,\n THREEDS2_FINGERPRINT_ERROR,\n THREEDS2_NUM,\n MISSING_TOKEN_IN_ACTION_MSG,\n THREEDS2_ERROR,\n TIMEOUT\n} from '../../constants';\nimport { ANALYTICS_API_ERROR, Analytics3DS2Errors, ANALYTICS_NETWORK_ERROR } from '../../../../core/Analytics/constants';\n\nclass PrepareFingerprint3DS2 extends Component<PrepareFingerprint3DS2Props, PrepareFingerprint3DS2State> {\n public static type = 'scheme';\n\n public static defaultProps = {\n onComplete: () => {},\n onError: () => {},\n paymentData: '',\n showSpinner: true,\n onActionHandled: () => {},\n isMDFlow: false\n };\n\n constructor(props) {\n super(props);\n\n const { token, notificationURL } = this.props; // See comments on prepareFingerPrintData regarding notificationURL\n\n if (token) {\n const fingerPrintData: FingerPrintData | ErrorObject = prepareFingerPrintData({ token, notificationURL });\n\n this.state = {\n status: 'init',\n fingerPrintData: fingerPrintData as FingerPrintData\n };\n } else {\n // Will be picked up in componentDidMount\n this.state = { fingerPrintData: { success: false, error: MISSING_TOKEN_IN_ACTION_MSG } };\n\n console.debug(`${THREEDS2_FINGERPRINT_ERROR}: ${MISSING_TOKEN_IN_ACTION_MSG}`);\n }\n }\n\n public onActionHandled = (rtnObj: ActionHandledReturnObject) => {\n // Leads to an \"iframe loaded\" log action\n this.props.onSubmitAnalytics({ type: THREEDS2_FULL, message: rtnObj.actionDescription });\n this.props.onActionHandled(rtnObj);\n };\n\n public onFormSubmit = (msg: string) => {\n this.props.onSubmitAnalytics({\n type: THREEDS2_FULL,\n message: msg\n });\n };\n\n componentDidMount() {\n const hasFingerPrintData = !isErrorObject(this.state.fingerPrintData);\n\n if (hasFingerPrintData) {\n const shouldAllowHttpDomains = process.env.NODE_ENV === 'development' && process.env.__CLIENT_ENV__?.indexOf('localhost:8080') > -1; // allow http urls if in development and testing against localhost:8080\n\n /**\n * Check the structure of the created fingerPrintData\n */\n const { threeDSMethodURL, threeDSMethodNotificationURL, postMessageDomain, threeDSServerTransID } = this.state\n .fingerPrintData as FingerPrintData;\n\n const hasValid3DSMethodURL = isValidHttpUrl(threeDSMethodURL, shouldAllowHttpDomains);\n\n // Only render component if we have a threeDSMethodURL. Otherwise, exit with threeDSCompInd: 'U'\n if (!hasValid3DSMethodURL) {\n this.setStatusComplete(\n { threeDSCompInd: 'U' },\n {\n errorCode: Analytics3DS2Errors.TOKEN_IS_MISSING_THREEDSMETHODURL,\n message: `${THREEDS2_FINGERPRINT_ERROR}: Decoded token is missing a valid threeDSMethodURL property`\n }\n );\n\n /**\n * NOTE: we can now use this.props.isMDFlow to decide if we want to send any of these errors to the onError handler\n * - this is problematic in the regular flow since merchants tend to treat any calls to their onError handler as 'fatal',\n * but in the MDFlow we control what the onError handler does.\n */\n // if (this.props.isMDFlow) {}\n\n console.debug('### PrepareFingerprint3DS2::exiting:: no valid threeDSMethodURL');\n return;\n }\n\n const hasValid3DSMethodNotificationURL = isValidHttpUrl(threeDSMethodNotificationURL, shouldAllowHttpDomains);\n const hasValidPostMessageDomain = isValidHttpUrl(postMessageDomain, shouldAllowHttpDomains);\n const hasTransServerID = threeDSServerTransID?.length;\n\n if (!hasValid3DSMethodNotificationURL || !hasValidPostMessageDomain || !hasTransServerID) {\n /**\n * NOTE: EMVCo_3DS_CoreSpec_v2.3.1_20220831.pdf states that we should return: threeDSCompInd: 'N'\n * when the fingerprinting process \"Did not run or did not successfully complete\"\n */\n this.setStatusComplete(\n { threeDSCompInd: 'N' },\n {\n errorCode: Analytics3DS2Errors.TOKEN_IS_MISSING_OTHER_PROPS,\n message: `${THREEDS2_FINGERPRINT_ERROR}: Decoded token is missing one or more of the following properties (threeDSMethodNotificationURL | postMessageDomain | threeDSServerTransID)`\n }\n );\n\n console.debug(\n '### PrepareFingerprint3DS2::exiting:: Decoded token is missing one or more of the following properties (threeDSMethodNotificationURL | postMessageDomain | threeDSServerTransID)'\n );\n\n return;\n }\n\n // Proceed to allow component to render\n this.setState({ status: 'retrievingFingerPrint' });\n //\n } else {\n // Only render component if we have fingerPrintData. Otherwise, complete with threeDSCompInd: 'N'\n\n const errorMsg: string = (this.state.fingerPrintData as ErrorObject).error;\n\n const errorCode =\n errorMsg.indexOf(MISSING_TOKEN_IN_ACTION_MSG) > -1\n ? Analytics3DS2Errors.ACTION_IS_MISSING_TOKEN\n : Analytics3DS2Errors.TOKEN_DECODE_OR_PARSING_FAILED;\n\n this.setStatusComplete(\n { threeDSCompInd: 'N' },\n {\n errorCode,\n message: `${THREEDS2_FINGERPRINT_ERROR}: ${errorMsg}` // can be: 'Missing \"token\" property from threeDS2 action', 'not base64', 'malformed URI sequence' or 'Could not JSON parse token'\n }\n );\n\n console.debug('### PrepareFingerprint3DS2:: token does not exist or could not be base64 decoded &/or JSON.parsed');\n }\n }\n\n setStatusComplete(resultObj: ResultObject, errorCodeObject: ErrorCodeObject = null) {\n this.setState({ status: 'complete' }, () => {\n /**\n * Create the data in the way that the /details endpoint expects.\n * This is different for the flow triggered by the threeds2InMDFlow process than for the new, v67, 'threeDS2' action\n */\n const resolveDataFunction = this.props.isMDFlow ? createOldFingerprintResolveData : createFingerprintResolveData;\n const data = resolveDataFunction(this.props.dataKey, resultObj, this.props.paymentData);\n\n let analyticsObject: SendAnalyticsObject;\n\n /** Are we in an error scenario? If so, submit analytics about it */\n const finalResObject = errorCodeObject ? errorCodeObject : resultObj;\n if (finalResObject.errorCode) {\n const errorTypeAndCode = {\n code: finalResObject.errorCode === TIMEOUT ? Analytics3DS2Errors.THREEDS2_TIMEOUT : finalResObject.errorCode,\n errorType: finalResObject.errorCode === TIMEOUT ? ANALYTICS_NETWORK_ERROR : ANALYTICS_API_ERROR // TODO - for a timeout is this really a Network error? Or is it a \"ThirdParty\" error i.e. the ACS has had a problem serving the fingerprinting page in a timely manner?\n };\n\n /**\n * Timeout or data parsing problems:\n *\n * (threeDSCompInd:\"U\"):\n * - Decoded token is missing a valid threeDSMethodURL property,\n * or, (threeDSCompInd:\"N\"):\n * - Fingerprint process has timed out, // TODO - do we want to know about this timeout event (which is a \"valid\" 3DS2 scenario) from an analytics perspective, and, if so, how do we classify it? ...error? info?\n * also, (threeDSCompInd:\"N\"):\n * - Missing \"token\" property from threeDS2 action\n * - or, decoded token is missing one or more of the following properties (threeDSMethodNotificationURL | postMessageDomain | threeDSServerTransID)\n * - or, token could not be base64 decoded &/or JSON.parsed\n */\n analyticsObject = {\n type: THREEDS2_ERROR,\n message: (finalResObject as ErrorCodeObject).message,\n ...errorTypeAndCode\n };\n\n // Send error to analytics endpoint\n this.props.onSubmitAnalytics(analyticsObject);\n }\n\n /**\n * The fingerprint process is completed, one way or another.\n * The resultObj will be {threeDSCompInd:\"Y\"} in the case of success,\n * else {threeDSCompInd:\"U\"} or {threeDSCompInd:\"N\"} - if we've had some kind of timeout or data parsing problem (as described above)\n */\n analyticsObject = {\n type: THREEDS2_FULL,\n message: `${THREEDS2_NUM} fingerprinting has completed`,\n metadata: { ...resultObj }\n };\n\n // Send log to analytics endpoint\n this.props.onSubmitAnalytics(analyticsObject);\n\n /**\n * Equals call to callSubmit3DS2Fingerprint (except for in 3DS2InMDFlow)\n */\n this.props.onComplete(data);\n });\n }\n\n render({ showSpinner }, { status, fingerPrintData }) {\n if (status === 'retrievingFingerPrint') {\n return (\n <DoFingerprint3DS2\n onCompleteFingerprint={fingerprint => {\n this.setStatusComplete(fingerprint.result);\n }}\n onErrorFingerprint={fingerprint => {\n /**\n * Called when fingerprint times-out (which is still a valid scenario)...\n */\n const timeoutObject: ErrorCodeObject = {\n errorCode: fingerprint.errorCode, // 'timeout'\n message: `${THREEDS2_FINGERPRINT}: ${fingerprint.errorCode}`\n };\n\n this.setStatusComplete(fingerprint.result, timeoutObject); // fingerprint.result = threeDSCompInd: 'N'\n }}\n showSpinner={showSpinner}\n {...fingerPrintData}\n onActionHandled={this.onActionHandled}\n onFormSubmit={this.onFormSubmit}\n />\n );\n }\n\n return null;\n }\n}\n\nexport default PrepareFingerprint3DS2;\n"],"names":["PrepareFingerprint3DS2","Component","static","onComplete","onError","paymentData","showSpinner","onActionHandled","isMDFlow","constructor","props","super","token","notificationURL","this","fingerPrintData","prepareFingerPrintData","state","status","success","error","MISSING_TOKEN_IN_ACTION_MSG","console","debug","THREEDS2_FINGERPRINT_ERROR","rtnObj","onSubmitAnalytics","type","THREEDS2_FULL","message","actionDescription","onFormSubmit","msg","componentDidMount","isErrorObject","shouldAllowHttpDomains","threeDSMethodURL","threeDSMethodNotificationURL","postMessageDomain","threeDSServerTransID","isValidHttpUrl","setStatusComplete","threeDSCompInd","errorCode","Analytics3DS2Errors","TOKEN_IS_MISSING_THREEDSMETHODURL","hasValid3DSMethodNotificationURL","hasValidPostMessageDomain","hasTransServerID","length","TOKEN_IS_MISSING_OTHER_PROPS","setState","errorMsg","indexOf","ACTION_IS_MISSING_TOKEN","TOKEN_DECODE_OR_PARSING_FAILED","resultObj","errorCodeObject","data","createOldFingerprintResolveData","createFingerprintResolveData","dataKey","analyticsObject","finalResObject","errorTypeAndCode","code","TIMEOUT","THREEDS2_TIMEOUT","errorType","ANALYTICS_NETWORK_ERROR","ANALYTICS_API_ERROR","THREEDS2_ERROR","THREEDS2_NUM","metadata","render","h","DoFingerprint3DS2","onCompleteFingerprint","fingerprint","result","onErrorFingerprint","timeoutObject","THREEDS2_FINGERPRINT"],"mappings":"qpBAoBA,MAAMA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AYC,OAAQE,IAE/C3E,YAAaA,KACTS,EACJR,gBAAiBO,KAAKP,gBACtBwB,aAAcjB,KAAKiB,eAKxB,IACX"}
|
|
1
|
+
{"version":3,"file":"PrepareFingerprint3DS2.js","sources":["../../../../../../src/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.tsx"],"sourcesContent":["import { Component, h } from 'preact';\nimport DoFingerprint3DS2 from './DoFingerprint3DS2';\nimport { createFingerprintResolveData, createOldFingerprintResolveData, isErrorObject, prepareFingerPrintData } from '../utils';\nimport { PrepareFingerprint3DS2Props, PrepareFingerprint3DS2State } from './types';\nimport { FingerPrintData, ResultObject, ErrorCodeObject } from '../../types';\nimport { ErrorObject } from '../../../../core/Errors/types';\nimport { ActionHandledReturnObject } from '../../../../types/global-types';\nimport { SendAnalyticsObject } from '../../../../core/Analytics/types';\nimport { isValidHttpUrl } from '../../../../utils/isValidURL';\nimport {\n THREEDS2_FULL,\n THREEDS2_FINGERPRINT,\n THREEDS2_FINGERPRINT_ERROR,\n THREEDS2_NUM,\n MISSING_TOKEN_IN_ACTION_MSG,\n THREEDS2_ERROR,\n TIMEOUT\n} from '../../constants';\nimport { ANALYTICS_API_ERROR, ANALYTICS_NETWORK_ERROR, Analytics3DS2Errors, Analytics3DS2Events } from '../../../../core/Analytics/constants';\n\nclass PrepareFingerprint3DS2 extends Component<PrepareFingerprint3DS2Props, PrepareFingerprint3DS2State> {\n public static type = 'scheme';\n\n public static defaultProps = {\n onComplete: () => {},\n onError: () => {},\n paymentData: '',\n showSpinner: true,\n onActionHandled: () => {},\n isMDFlow: false\n };\n\n constructor(props) {\n super(props);\n\n const { token, notificationURL } = this.props; // See comments on prepareFingerPrintData regarding notificationURL\n\n if (token) {\n const fingerPrintData: FingerPrintData | ErrorObject = prepareFingerPrintData({ token, notificationURL });\n\n this.state = {\n status: 'init',\n fingerPrintData: fingerPrintData as FingerPrintData\n };\n } else {\n // Will be picked up in componentDidMount\n this.state = { fingerPrintData: { success: false, error: MISSING_TOKEN_IN_ACTION_MSG } };\n\n console.debug(`${THREEDS2_FINGERPRINT_ERROR}: ${MISSING_TOKEN_IN_ACTION_MSG}`);\n }\n }\n\n public onActionHandled = (rtnObj: ActionHandledReturnObject) => {\n this.props.onSubmitAnalytics({\n type: THREEDS2_FULL,\n message: rtnObj.actionDescription,\n subtype: Analytics3DS2Events.FINGERPRINT_IFRAME_LOADED\n });\n this.props.onActionHandled(rtnObj);\n };\n\n public onFormSubmit = (msg: string) => {\n this.props.onSubmitAnalytics({\n type: THREEDS2_FULL,\n message: msg,\n subtype: Analytics3DS2Events.FINGERPRINT_DATA_SENT\n });\n };\n\n componentDidMount() {\n const hasFingerPrintData = !isErrorObject(this.state.fingerPrintData);\n\n if (hasFingerPrintData) {\n const shouldAllowHttpDomains =\n /** Allow http urls if in development and testing against localhost:8080 */\n (process.env.NODE_ENV === 'development' && process.env.__CLIENT_ENV__?.indexOf('localhost:8080') > -1) ||\n /**\n * Allows the checkoutshopper demo on localhost:8080 to work -\n * requires a configuration in localhost of environment: 'test', _environmentUrls: {api: 'http://localhost:8080/'}\n */\n (this.props.environment === 'test' && this.props._environmentUrls?.api?.includes('http://localhost:8080'));\n\n /**\n * Check the structure of the created fingerPrintData\n */\n const { threeDSMethodURL, threeDSMethodNotificationURL, postMessageDomain, threeDSServerTransID } = this.state\n .fingerPrintData as FingerPrintData;\n\n const hasValid3DSMethodURL = isValidHttpUrl(threeDSMethodURL, shouldAllowHttpDomains);\n\n // Only render component if we have a threeDSMethodURL. Otherwise, exit with threeDSCompInd: 'U'\n if (!hasValid3DSMethodURL) {\n this.setStatusComplete(\n { threeDSCompInd: 'U' },\n {\n errorCode: Analytics3DS2Errors.TOKEN_IS_MISSING_THREEDSMETHODURL,\n message: `${THREEDS2_FINGERPRINT_ERROR}: Decoded token is missing a valid threeDSMethodURL property`\n }\n );\n\n /**\n * NOTE: we can now use this.props.isMDFlow to decide if we want to send any of these errors to the onError handler\n * - this is problematic in the regular flow since merchants tend to treat any calls to their onError handler as 'fatal',\n * but in the MDFlow we control what the onError handler does.\n */\n // if (this.props.isMDFlow) {}\n\n console.debug('### PrepareFingerprint3DS2::exiting:: no valid threeDSMethodURL');\n return;\n }\n\n const hasValid3DSMethodNotificationURL = isValidHttpUrl(threeDSMethodNotificationURL, shouldAllowHttpDomains);\n const hasValidPostMessageDomain = isValidHttpUrl(postMessageDomain, shouldAllowHttpDomains);\n const hasTransServerID = threeDSServerTransID?.length;\n\n if (!hasValid3DSMethodNotificationURL || !hasValidPostMessageDomain || !hasTransServerID) {\n /**\n * NOTE: EMVCo_3DS_CoreSpec_v2.3.1_20220831.pdf states that we should return: threeDSCompInd: 'N'\n * when the fingerprinting process \"Did not run or did not successfully complete\"\n */\n this.setStatusComplete(\n { threeDSCompInd: 'N' },\n {\n errorCode: Analytics3DS2Errors.TOKEN_IS_MISSING_OTHER_PROPS,\n message: `${THREEDS2_FINGERPRINT_ERROR}: Decoded token is missing one or more of the following properties (threeDSMethodNotificationURL | postMessageDomain | threeDSServerTransID)`\n }\n );\n\n console.debug(\n '### PrepareFingerprint3DS2::exiting:: Decoded token is missing one or more of the following properties (threeDSMethodNotificationURL | postMessageDomain | threeDSServerTransID)'\n );\n\n return;\n }\n\n // Proceed to allow component to render\n this.setState({ status: 'retrievingFingerPrint' });\n //\n } else {\n // Only render component if we have fingerPrintData. Otherwise, complete with threeDSCompInd: 'N'\n\n const errorMsg: string = (this.state.fingerPrintData as ErrorObject).error;\n\n const errorCode =\n errorMsg.indexOf(MISSING_TOKEN_IN_ACTION_MSG) > -1\n ? Analytics3DS2Errors.ACTION_IS_MISSING_TOKEN\n : Analytics3DS2Errors.TOKEN_DECODE_OR_PARSING_FAILED;\n\n this.setStatusComplete(\n { threeDSCompInd: 'N' },\n {\n errorCode,\n message: `${THREEDS2_FINGERPRINT_ERROR}: ${errorMsg}` // can be: 'Missing \"token\" property from threeDS2 action', 'not base64', 'malformed URI sequence' or 'Could not JSON parse token'\n }\n );\n\n console.debug('### PrepareFingerprint3DS2:: token does not exist or could not be base64 decoded &/or JSON.parsed');\n }\n }\n\n setStatusComplete(resultObj: ResultObject, errorCodeObject: ErrorCodeObject = null) {\n this.setState({ status: 'complete' }, () => {\n /**\n * Create the data in the way that the /details endpoint expects.\n * This is different for the flow triggered by the threeds2InMDFlow process than for the new, v67, 'threeDS2' action\n */\n const resolveDataFunction = this.props.isMDFlow ? createOldFingerprintResolveData : createFingerprintResolveData;\n const data = resolveDataFunction(this.props.dataKey, resultObj, this.props.paymentData);\n\n let analyticsObject: SendAnalyticsObject;\n\n /** Are we in an error scenario? If so, submit analytics about it */\n const finalResObject = errorCodeObject ? errorCodeObject : resultObj;\n if (finalResObject.errorCode) {\n const errorTypeAndCode = {\n code: finalResObject.errorCode === TIMEOUT ? Analytics3DS2Errors.THREEDS2_TIMEOUT : finalResObject.errorCode,\n errorType: finalResObject.errorCode === TIMEOUT ? ANALYTICS_NETWORK_ERROR : ANALYTICS_API_ERROR\n };\n\n /**\n * Timeout or data parsing problems:\n *\n * (threeDSCompInd:\"U\"):\n * - Decoded token is missing a valid threeDSMethodURL property,\n * or, (threeDSCompInd:\"N\"):\n * - Fingerprint process has timed out,\n * also, (threeDSCompInd:\"N\"):\n * - Missing \"token\" property from threeDS2 action\n * - or, decoded token is missing one or more of the following properties (threeDSMethodNotificationURL | postMessageDomain | threeDSServerTransID)\n * - or, token could not be base64 decoded &/or JSON.parsed\n */\n analyticsObject = {\n type: THREEDS2_ERROR,\n message: (finalResObject as ErrorCodeObject).message,\n ...errorTypeAndCode\n };\n\n // Send error to analytics endpoint\n this.props.onSubmitAnalytics(analyticsObject);\n }\n\n /** Calculate \"result\" for analytics */\n let result: string;\n\n switch (resultObj?.threeDSCompInd) {\n case 'Y':\n result = 'success';\n break;\n case 'N': {\n if (!errorCodeObject) {\n result = 'failed'; // 'failed' is the result returned from the threeDSMethodURL\n } else {\n result = errorCodeObject.errorCode === TIMEOUT ? TIMEOUT : 'failedInternal'; // timed-out; or, 'failed' as a result of internal checks\n }\n break;\n }\n case 'U':\n result = 'noThreeDSMethodURL';\n break;\n default:\n }\n\n /**\n * The fingerprint process is completed, one way or another.\n * The resultObj will be {threeDSCompInd:\"Y\"} in the case of success,\n * else {threeDSCompInd:\"U\"} or {threeDSCompInd:\"N\"} - if we've had some kind of timeout or data parsing problem (as described above)\n */\n analyticsObject = {\n type: THREEDS2_FULL,\n message: `${THREEDS2_NUM} fingerprinting has completed`,\n subtype: Analytics3DS2Events.FINGERPRINT_COMPLETED,\n result\n };\n\n // Send log to analytics endpoint\n this.props.onSubmitAnalytics(analyticsObject);\n\n /**\n * Equals call to callSubmit3DS2Fingerprint (except for in 3DS2InMDFlow)\n */\n this.props.onComplete(data);\n });\n }\n\n render({ showSpinner }, { status, fingerPrintData }) {\n if (status === 'retrievingFingerPrint') {\n return (\n <DoFingerprint3DS2\n onCompleteFingerprint={fingerprint => {\n this.setStatusComplete(fingerprint.result);\n }}\n onErrorFingerprint={fingerprint => {\n /**\n * Called when fingerprint times-out (which is still a valid scenario)...\n */\n const timeoutObject: ErrorCodeObject = {\n errorCode: fingerprint.errorCode, // 'timeout'\n message: `${THREEDS2_FINGERPRINT}: ${fingerprint.errorCode}`\n };\n\n this.setStatusComplete(fingerprint.result, timeoutObject); // fingerprint.result = threeDSCompInd: 'N'\n }}\n showSpinner={showSpinner}\n {...fingerPrintData}\n onActionHandled={this.onActionHandled}\n onFormSubmit={this.onFormSubmit}\n />\n );\n }\n\n return null;\n }\n}\n\nexport default PrepareFingerprint3DS2;\n"],"names":["PrepareFingerprint3DS2","Component","static","onComplete","onError","paymentData","showSpinner","onActionHandled","isMDFlow","constructor","props","super","token","notificationURL","this","fingerPrintData","prepareFingerPrintData","state","status","success","error","MISSING_TOKEN_IN_ACTION_MSG","console","debug","THREEDS2_FINGERPRINT_ERROR","rtnObj","onSubmitAnalytics","type","THREEDS2_FULL","message","actionDescription","subtype","Analytics3DS2Events","FINGERPRINT_IFRAME_LOADED","onFormSubmit","msg","FINGERPRINT_DATA_SENT","componentDidMount","isErrorObject","shouldAllowHttpDomains","environment","_environmentUrls","api","includes","threeDSMethodURL","threeDSMethodNotificationURL","postMessageDomain","threeDSServerTransID","isValidHttpUrl","setStatusComplete","threeDSCompInd","errorCode","Analytics3DS2Errors","TOKEN_IS_MISSING_THREEDSMETHODURL","hasValid3DSMethodNotificationURL","hasValidPostMessageDomain","hasTransServerID","length","TOKEN_IS_MISSING_OTHER_PROPS","setState","errorMsg","indexOf","ACTION_IS_MISSING_TOKEN","TOKEN_DECODE_OR_PARSING_FAILED","resultObj","errorCodeObject","data","createOldFingerprintResolveData","createFingerprintResolveData","dataKey","analyticsObject","finalResObject","errorTypeAndCode","code","TIMEOUT","THREEDS2_TIMEOUT","errorType","ANALYTICS_NETWORK_ERROR","ANALYTICS_API_ERROR","THREEDS2_ERROR","result","THREEDS2_NUM","FINGERPRINT_COMPLETED","render","h","DoFingerprint3DS2","onCompleteFingerprint","fingerprint","onErrorFingerprint","timeoutObject","THREEDS2_FINGERPRINT"],"mappings":"8qBAoBA,MAAMA,UAA+BC,EACjCC,YAAqB,SAErBA,oBAA6B,CACzBC,WAAY,OACZC,QAAS,OACTC,YAAa,GACbC,aAAa,EACbC,gBAAiB,OACjBC,UAAU,GAGdC,WAAAA,CAAYC,GACRC,MAAMD,GAEN,MAAME,MAAEA,EAAKC,gBAAEA,GAAoBC,KAAKJ,MAExC,GAAIE,EAAO,CACP,MAAMG,EAAiDC,EAAuB,CAAEJ,QAAOC,oBAEvFC,KAAKG,MAAQ,CACTC,OAAQ,OACRH,gBAAiBA,QAIrBD,KAAKG,MAAQ,CAAEF,gBAAiB,CAAEI,SAAS,EAAOC,MAAOC,IAEzDC,QAAQC,MAAM,GAAGC,MAA+BH,IAExD,CAEOd,gBAAmBkB,IACtBX,KAAKJ,MAAMgB,kBAAkB,CACzBC,KAAMC,EACNC,QAASJ,EAAOK,kBAChBC,QAASC,EAAoBC,4BAEjCnB,KAAKJ,MAAMH,gBAAg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AAWlD,KAAKJ,MAAML,aAE3E,IAAIiE,EAGJ,MAAMC,EAAiBN,GAAoCD,EAC3D,GAAIO,EAAepB,UAAW,CAC1B,MAAMqB,EAAmB,CACrBC,KAAMF,EAAepB,YAAcuB,EAAUtB,EAAoBuB,iBAAmBJ,EAAepB,UACnGyB,UAAWL,EAAepB,YAAcuB,EAAUG,EAA0BC,GAehFR,EAAkB,CACd3C,KAAMoD,EACNlD,QAAU0C,EAAmC1C,WAC1C2C,GAIP1D,KAAKJ,MAAMgB,kBAAkB4C,EACjC,CAGA,IAAIU,EAEJ,OAAQhB,GAAWd,gBACf,IAAK,IACD8B,EAAS,UACT,MACJ,IAAK,IAIGA,EAHCf,EAGQA,EAAgBd,YAAcuB,EAAUA,EAAU,iBAFlD,SAIb,MAEJ,IAAK,IACDM,EAAS,qBAUjBV,EAAkB,CACd3C,KAAMC,EACNC,QAAS,GAAGoD,iCACZlD,QAASC,EAAoBkD,sBAC7BF,UAIJlE,KAAKJ,MAAMgB,kBAAkB4C,GAK7BxD,KAAKJ,MAAMP,WAAW+D,EAAAA,GAE9B,CAEAiB,MAAAA,EAAO7E,YAAEA,IAAeY,OAAEA,EAAMH,gBAAEA,IAC9B,MAAe,0BAAXG,EAEIkE,EAACC,EAAAA,CACGC,sBAAuBC,IACnBzE,KAAKmC,kBAAkBsC,EAAYP,OAAM,EAE7CQ,mBAAoBD,IAIhB,MAAME,EAAiC,CACnCtC,UAAWoC,EAAYpC,UACvBtB,QAAS,GAAG6D,MAAyBH,EAAYpC,aAGrDrC,KAAKmC,kBAAkBsC,EAAYP,OAAQS,IAE/CnF,YAAaA,KACTS,EACJR,gBAAiBO,KAAKP,gBACtB2B,aAAcpB,KAAKoB,eAKxB,IACX"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createElement as e}from"../../../external/preact/dist/preact.js";import{UIElement as t}from"../../internal/UIElement/UIElement.js";import s from"../../internal/OpenInvoice/OpenInvoice.js";import{CoreProvider as
|
|
1
|
+
import{createElement as e}from"../../../external/preact/dist/preact.js";import{UIElement as t}from"../../internal/UIElement/UIElement.js";import s from"../../internal/OpenInvoice/OpenInvoice.js";import{CoreProvider as i}from"../../../core/Context/CoreProvider.js";import r from"../../../core/Errors/SRPanelProvider.js";class n extends t{static defaultProps={onChange:()=>{},data:{companyDetails:{},personalDetails:{},billingAddress:{},deliveryAddress:{},bankAccount:{}},visibility:{companyDetails:"hidden",personalDetails:"editable",billingAddress:"editable",deliveryAddress:"editable",bankAccount:"hidden"}};get isValid(){return!!this.state.isValid}formatProps(e){const t=e.countryCode||e.data?.billingAddress?.countryCode;return{...e,allowedCountries:[t],visibility:{...n.defaultProps.visibility,...e.visibility},data:{...e.data,billingAddress:{...e.data.billingAddress,country:t},deliveryAddress:{...e.data.deliveryAddress,country:t}}}}formatData(){const{data:e={}}=this.state,{companyDetails:t={},personalDetails:s={},billingAddress:i,deliveryAddress:r,bankAccount:n}=e;return{paymentMethod:{type:this.constructor.type},...s,...t,...n&&{bankAccount:{iban:n.ibanNumber,ownerName:n.ownerName,countryCode:n.countryCode}},...i&&{billingAddress:i},...(r||i)&&{deliveryAddress:r||i}}}render(){return e(i,{i18n:this.props.i18n,loadingContext:this.props.loadingContext,resources:this.resources},e(r,{srPanel:this.props.modules.srPanel},e(s,{setComponentRef:this.setComponentRef,...this.props,...this.state,onChange:this.setState,onSubmit:this.submit,payButton:this.payButton})))}}export{n as default};
|
|
2
2
|
//# sourceMappingURL=OpenInvoiceContainer.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"OpenInvoiceContainer.js","sources":["../../../../../src/components/helpers/OpenInvoiceContainer/OpenInvoiceContainer.tsx"],"sourcesContent":["import { h } from 'preact';\nimport UIElement from '../../internal/UIElement/UIElement';\nimport OpenInvoice from '../../internal/OpenInvoice';\nimport { CoreProvider } from '../../../core/Context/CoreProvider';\nimport SRPanelProvider from '../../../core/Errors/SRPanelProvider';\nimport { OpenInvoiceConfiguration } from './types';\n\nexport default class OpenInvoiceContainer extends UIElement<OpenInvoiceConfiguration> {\n protected static defaultProps: Partial<OpenInvoiceConfiguration> = {\n onChange: () => {},\n data: { companyDetails: {}, personalDetails: {}, billingAddress: {}, deliveryAddress: {}, bankAccount: {} },\n visibility: {\n companyDetails: 'hidden',\n personalDetails: 'editable',\n billingAddress: 'editable',\n deliveryAddress: 'editable',\n bankAccount: 'hidden'\n }
|
|
1
|
+
{"version":3,"file":"OpenInvoiceContainer.js","sources":["../../../../../src/components/helpers/OpenInvoiceContainer/OpenInvoiceContainer.tsx"],"sourcesContent":["import { h } from 'preact';\nimport UIElement from '../../internal/UIElement/UIElement';\nimport OpenInvoice from '../../internal/OpenInvoice';\nimport { CoreProvider } from '../../../core/Context/CoreProvider';\nimport SRPanelProvider from '../../../core/Errors/SRPanelProvider';\nimport { OpenInvoiceConfiguration } from './types';\n\nexport default class OpenInvoiceContainer extends UIElement<OpenInvoiceConfiguration> {\n protected static defaultProps: Partial<OpenInvoiceConfiguration> = {\n onChange: () => {},\n data: { companyDetails: {}, personalDetails: {}, billingAddress: {}, deliveryAddress: {}, bankAccount: {} },\n visibility: {\n companyDetails: 'hidden',\n personalDetails: 'editable',\n billingAddress: 'editable',\n deliveryAddress: 'editable',\n bankAccount: 'hidden'\n }\n };\n\n /**\n * Returns whether the component state is valid or not\n */\n get isValid() {\n return !!this.state.isValid;\n }\n\n /**\n * Formats props on construction time\n */\n formatProps(props) {\n const country = props.countryCode || props.data?.billingAddress?.countryCode;\n\n return {\n ...props,\n allowedCountries: [country],\n visibility: {\n ...OpenInvoiceContainer.defaultProps.visibility,\n ...props.visibility\n },\n data: {\n ...props.data,\n billingAddress: {\n ...props.data.billingAddress,\n country\n },\n deliveryAddress: {\n ...props.data.deliveryAddress,\n country\n }\n }\n };\n }\n\n /**\n * Formats the component data output\n */\n formatData() {\n const { data = {} } = this.state;\n const { companyDetails = {}, personalDetails = {}, billingAddress, deliveryAddress, bankAccount } = data;\n\n return {\n paymentMethod: {\n type: this.constructor['type']\n },\n ...personalDetails,\n ...companyDetails,\n ...(bankAccount && {\n bankAccount: {\n iban: bankAccount.ibanNumber,\n ownerName: bankAccount.ownerName,\n countryCode: bankAccount.countryCode\n }\n }),\n ...(billingAddress && { billingAddress }),\n ...((deliveryAddress || billingAddress) && { deliveryAddress: deliveryAddress || billingAddress })\n };\n }\n\n render() {\n return (\n <CoreProvider i18n={this.props.i18n} loadingContext={this.props.loadingContext} resources={this.resources}>\n <SRPanelProvider srPanel={this.props.modules.srPanel}>\n <OpenInvoice\n setComponentRef={this.setComponentRef}\n {...this.props}\n {...this.state}\n onChange={this.setState}\n onSubmit={this.submit}\n payButton={this.payButton}\n />\n </SRPanelProvider>\n </CoreProvider>\n );\n }\n}\n"],"names":["OpenInvoiceContainer","UIElement","static","onChange","data","companyDetails","personalDetails","billingAddress","deliveryAddress","bankAccount","visibility","isValid","this","state","formatProps","props","country","countryCode","allowedCountries","defaultProps","formatData","paymentMethod","type","constructor","iban","ibanNumber","ownerName","render","h","CoreProvider","i18n","loadingContext","resources","SRPanelProvider","srPanel","modules","OpenInvoice","setComponentRef","setState","onSubmit","submit","payButton"],"mappings":"+TAOe,MAAMA,UAA6BC,EAC9CC,oBAAmE,CAC/DC,SAAU,OACVC,KAAM,CAAEC,eAAgB,CAAC,EAAGC,gBAAiB,CAAC,EAAGC,eAAgB,CAAC,EAAGC,gBAAiB,CAAC,EAAGC,YAAa,CAAC,GACxGC,WAAY,CACRL,eAAgB,SAChBC,gBAAiB,WACjBC,eAAgB,WAChBC,gBAAiB,WACjBC,YAAa,WAOrB,WAAIE,GACA,QAASC,KAAKC,MAAMF,OACxB,CAKAG,WAAAA,CAAYC,GACR,MAAMC,EAAUD,EAAME,aAAeF,EAAMX,MAAMG,gBAAgBU,YAEjE,MAAO,IACAF,EACHG,iBAAkB,CAACF,GACnBN,WAAY,IACLV,EAAqBmB,aAAaT,cAClCK,EAAML,YAEbN,KAAM,IACCW,EAAMX,KACTG,eAAgB,IACTQ,EAAMX,KAAKG,eACdS,WAEJR,gBAAiB,IACVO,EAAMX,KAAKI,gBACdQ,YAIhB,CAKAI,UAAAA,GACI,MAAMhB,KAAEA,EAAO,CAAA,GAAOQ,KAAKC,OACrBR,eAAEA,EAAiB,CAAE,EAAAC,gBAAEA,EAAkB,CAAA,EAAEC,eAAEA,EAAcC,gBAAEA,EAAeC,YAAEA,GAAgBL,EAEpG,MAAO,CACHiB,cAAe,CACXC,KAAMV,KAAKW,YAAmB,SAE/BjB,KACAD,KACCI,GAAe,CACfA,YAAa,CACTe,KAAMf,EAAYgB,WAClBC,UAAWjB,EAAYiB,UACvBT,YAAaR,EAAYQ,iBAG7BV,GAAkB,CAAEA,sBACnBC,GAAmBD,IAAmB,CAAEC,gBAAiBA,GAAmBD,GAEzF,CAEAoB,MAAAA,GACI,OACIC,EAACC,EAAAA,CAAaC,KAAMlB,KAAKG,MAAMe,KAAMC,eAAgBnB,KAAKG,MAAMgB,eAAgBC,UAAWpB,KAAKoB,WAC5FJ,EAACK,EAAAA,CAAgBC,QAAStB,KAAKG,MAAMoB,QAAQD,SACzCN,EAACQ,EAAAA,CACGC,gBAAiBzB,KAAKyB,mBAClBzB,KAAKG,SACLH,KAAKC,MACTV,SAAUS,KAAK0B,SACfC,SAAU3B,KAAK4B,OACfC,UAAW7B,KAAK6B,aAKpC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{render as t}from"../../../external/preact/dist/preact.js";import o from"../../../utils/getProp.js";import e from"../../../utils/uuid.js";import r from"../../../core/Errors/AdyenCheckoutError.js";import{ANALYTICS_RENDERED_STR as s}from"../../../core/Analytics/constants.js";class n{_id=`${this.constructor.type}-${e()}`;props;state={};_component;_node=null;
|
|
1
|
+
import{render as t}from"../../../external/preact/dist/preact.js";import o from"../../../utils/getProp.js";import e from"../../../utils/uuid.js";import r from"../../../core/Errors/AdyenCheckoutError.js";import{ANALYTICS_RENDERED_STR as s}from"../../../core/Analytics/constants.js";class n{_id=`${this.constructor.type}-${e()}`;core;props;state={};_component;_node=null;static defaultProps={};constructor(t,o){const e=function(t){return!!t&&("function"==typeof t.initialize&&"function"==typeof t.createFromAction)}(t);if(!e)throw new r("IMPLEMENTATION_ERROR",`Trying to initialise the component '${this.constructor.type}' without a reference to an instance of AdyenCheckout`);this.core=t,this.buildElementProps(o)}buildElementProps(t){this.props=this.formatProps({...this.constructor.defaultProps,...t})}formatProps(t){return t}formatData(){return{}}setUpAnalytics(t){return null}submitAnalytics(t){return null}setState(t){this.state={...this.state,...t}}get data(){const t=o(this.props,"modules.risk.data"),e=!!o(this.props,"modules.analytics.getEnabled")?.()?o(this.props,"modules.analytics.getCheckoutAttemptId")?.():"do-not-track",r=this.state.order||this.props.order,s=this.formatData();if(s.paymentMethod&&e&&(s.paymentMethod.checkoutAttemptId=e),"riverty"!==this.props.type&&s.billingAddress){const{firstName:t,lastName:o,...e}=s.billingAddress;s.billingAddress={...e}}return{...t&&{riskData:{clientData:t}},...r&&{order:{orderData:r.orderData,pspReference:r.pspReference}},...s,clientStateDataIndicator:!0}}render(){throw new Error("Payment method cannot be rendered.")}mount(o){const e="string"==typeof o?document.querySelector(o):o;if(!e)throw new Error("Component could not mount. Root node was not found.");const r=!this._node;return this._node&&this.unmount(),this._node=e,this._component=this.render(),t(this._component,e),r&&this.props.modules&&this.props.modules.analytics&&this.setUpAnalytics({containerWidth:e&&e.offsetWidth,component:this.props.isDropin?"dropin":this.constructor.analyticsType??this.constructor.type,flavor:this.props.isDropin?"dropin":"components"}).then((()=>{this.props.isDropin||this.submitAnalytics({type:s})})),this}update(t){return this.props=this.formatProps({...this.props,...t}),this.state={},this.unmount().mount(this._node)}unmount(){return this._node&&t(null,this._node),this}remove(){this.unmount(),this.core&&this.core.remove(this)}}export{n as default};
|
|
2
2
|
//# sourceMappingURL=BaseElement.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseElement.js","sources":["../../../../../src/components/internal/BaseElement/BaseElement.ts"],"sourcesContent":["import { ComponentChild, render } from 'preact';\nimport getProp from '../../../utils/getProp';\nimport uuid from '../../../utils/uuid';\nimport AdyenCheckoutError from '../../../core/Errors/AdyenCheckoutError';\n\nimport type { ICore } from '../../../core/types';\nimport type { BaseElementProps, IBaseElement } from './types';\nimport type { PaymentData } from '../../../types/global-types';\nimport { AnalyticsInitialEvent, SendAnalyticsObject } from '../../../core/Analytics/types';\nimport { ANALYTICS_RENDERED_STR } from '../../../core/Analytics/constants';\n\n/**\n * Verify if the first parameter is instance of Core.\n * We do not use 'instanceof' to avoid importing the Core class directly into this class.\n * @param checkout\n */\nfunction assertIsCoreInstance(checkout: ICore): checkout is ICore {\n if (!checkout) return false;\n const isCoreObject = typeof checkout.initialize === 'function' && typeof checkout.createFromAction === 'function';\n return isCoreObject;\n}\n\nclass BaseElement<P extends BaseElementProps> implements IBaseElement {\n public readonly _id = `${this.constructor['type']}-${uuid()}`;\n\n public props: P;\n public state: any = {};\n public _component;\n\n protected _node: HTMLElement = null;\n protected readonly core: ICore;\n\n protected static defaultProps = {};\n\n constructor(checkout: ICore, props?: P) {\n const isCoreInstance = assertIsCoreInstance(checkout);\n\n if (!isCoreInstance) {\n throw new AdyenCheckoutError(\n 'IMPLEMENTATION_ERROR',\n `Trying to initialise the component '${this.constructor['type']}' without a reference to an instance of AdyenCheckout`\n );\n }\n\n this.core = checkout;\n this.buildElementProps(props);\n }\n\n protected buildElementProps(componentProps?: P) {\n this.props = this.formatProps({ ...this.constructor['defaultProps'], ...componentProps });\n }\n\n /**\n * Executed during creation of any payment element.\n * Gives a chance to any paymentMethod to format the props we're receiving.\n */\n protected formatProps(props: P) {\n return props;\n }\n\n /**\n * Executed on the `data` getter.\n * Returns the component data necessary for the /payments request\n *\n * TODO: Replace 'any' by type PaymentMethodData<T> - this change requires updating all payment methods,\n * properly adding the type of the formatData function\n */\n protected formatData(): any {\n return {};\n }\n\n /* eslint-disable-next-line */\n protected setUpAnalytics(setUpAnalyticsObj: AnalyticsInitialEvent) {\n return null;\n }\n\n /* eslint-disable-next-line */\n protected submitAnalytics(analyticsObj?: SendAnalyticsObject) {\n return null;\n }\n\n protected setState(newState: object): void {\n this.state = { ...this.state, ...newState };\n }\n\n /**\n * Returns the component payment data ready to submit to the Checkout API\n * Note: this does not ensure validity, check isValid first\n */\n public get data(): PaymentData {\n const clientData = getProp(this.props, 'modules.risk.data');\n const useAnalytics = !!getProp(this.props, 'modules.analytics.getEnabled')?.();\n const checkoutAttemptId = useAnalytics ? getProp(this.props, 'modules.analytics.getCheckoutAttemptId')?.() : 'do-not-track';\n const order = this.state.order || this.props.order;\n\n const componentData = this.formatData();\n if (componentData.paymentMethod && checkoutAttemptId) {\n componentData.paymentMethod.checkoutAttemptId = checkoutAttemptId;\n }\n\n // Workaround, to be fixed properly\n // Remove the firstName & lastName in the billingAddress for non Riverty components\n // @ts-ignore type exists\n if (this.props.type !== 'riverty' && componentData.billingAddress) {\n const { firstName, lastName, ...rest } = componentData.billingAddress;\n componentData.billingAddress = { ...rest };\n }\n\n return {\n ...(clientData && { riskData: { clientData } }),\n ...(order && { order: { orderData: order.orderData, pspReference: order.pspReference } }),\n ...componentData,\n clientStateDataIndicator: true\n };\n }\n\n public render(): ComponentChild | Error {\n // render() not implemented in the element\n throw new Error('Payment method cannot be rendered.');\n }\n\n /**\n * Mounts an element into the dom\n * @param domNode - Node (or selector) where we will mount the payment element\n * @returns this - the payment element instance we mounted\n */\n public mount(domNode: HTMLElement | string): this {\n const node = typeof domNode === 'string' ? document.querySelector<HTMLElement>(domNode) : domNode;\n\n if (!node) {\n throw new Error('Component could not mount. Root node was not found.');\n }\n\n const setupAnalytics = !this._node;\n\n if (this._node) {\n this.unmount(); // new, if this._node exists then we are \"remounting\" so we first need to unmount if it's not already been done\n }\n\n this._node = node;\n\n this._component = this.render();\n\n render(this._component, node);\n\n // Set up analytics (once, since this._node is currently undefined) now that we have mounted and rendered\n if (setupAnalytics) {\n if (this.props.modules && this.props.modules.analytics) {\n this.setUpAnalytics({\n containerWidth: node && (node as HTMLElement).offsetWidth,\n component: !this.props.isDropin ? this.constructor['analyticsType'] ?? this.constructor['type'] : 'dropin',\n flavor: !this.props.isDropin ? 'components' : 'dropin'\n }).then(() => {\n // Once the initial analytics set up call has been made...\n // ...create an analytics event declaring that the component has been rendered\n // (The dropin will do this itself from DropinComponent once the PM list has rendered)\n if (!this.props.isDropin) {\n this.submitAnalytics({ type: ANALYTICS_RENDERED_STR });\n }\n });\n }\n }\n\n return this;\n }\n\n /**\n * Updates props, resets the internal state and remounts the element.\n *\n * @param props - props to update\n * @returns this - the element instance\n */\n public update(props: Partial<P>): this {\n this.props = this.formatProps({ ...this.props, ...props });\n this.state = {};\n\n return this.unmount().mount(this._node); // for new mount fny\n }\n\n /**\n * Unmounts a payment element from the DOM\n */\n public unmount(): this {\n if (this._node) {\n render(null, this._node);\n }\n\n return this;\n }\n\n /**\n * Unmounts an element and removes it from the parent instance\n * For \"destroy\" type cleanup - when you don't intend to use the component again\n */\n public remove() {\n this.unmount();\n\n if (this.core) {\n this.core.remove(this);\n }\n }\n}\n\nexport default BaseElement;\n"],"names":["BaseElement","_id","this","constructor","uuid","props","state","_component","_node","core","static","checkout","isCoreInstance","initialize","createFromAction","assertIsCoreInstance","AdyenCheckoutError","buildElementProps","componentProps","formatProps","formatData","setUpAnalytics","setUpAnalyticsObj","submitAnalytics","analyticsObj","setState","newState","data","clientData","getProp","checkoutAttemptId","order","componentData","paymentMethod","type","billingAddress","firstName","lastName","rest","riskData","orderData","pspReference","clientStateDataIndicator","render","Error","mount","domNode","node","document","querySelector","setupAnalytics","unmount","modules","analytics","containerWidth","offsetWidth","component","isDropin","flavor","then","ANALYTICS_RENDERED_STR","update","remove"],"mappings":"wRAsBA,MAAMA,EACcC,IAAM,GAAGC,KAAKC,YAAmB,QAAIC,MAE9CC,MACAC,MAAa,CAAA,EACbC,WAEGC,MAAqB,KACZC,KAEnBC,oBAAgC,CAAA,EAEhCP,WAAAA,CAAYQ,EAAiBN,GACzB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EAAuBE,SAASC,cAA2BH,GAAWA,EAE1F,IAAKC,EACD,MAAM,IAAIH,MAAM,uDAGpB,MAAMM,GAAkBhD,KAAKM,MA8B7B,OA5BIN,KAAKM,OACLN,KAAKiD,UAGTjD,KAAKM,MAAQuC,EAEb7C,KAAKK,WAAaL,KAAKyC,SAEvBA,EAAOzC,KAAKK,WAAYwC,GAGpBG,GACIhD,KAAKG,MAAM+C,SAAWlD,KAAKG,MAAM+C,QAAQC,WACzCnD,KAAKmB,eAAe,CAChBiC,eAAgBP,GAAQA,EAAsBQ,YAC9CC,UAAYtD,KAAKG,MAAMoD,SAA2E,SAAhEvD,KAAKC,2BAAgCD,KAAKC,iBAC5EuD,OAASxD,KAAKG,MAAMoD,SAA0B,SAAf,eAChCE,MAAK,KAICzD,KAAKG,MAAMoD,UACZvD,KAAKqB,gBAAgB,CAAEW,KAAM0B,GACjC,IAKL1D,IACX,CAQO2D,MAAAA,CAAOxD,GAIV,OAHAH,KAAKG,MAAQH,KAAKiB,YAAY,IAAKjB,KAAKG,SAAUA,IAClDH,KAAKI,MAAQ,GAENJ,KAAKiD,UAAUN,MAAM3C,KAAKM,MACrC,CAKA,OAAA2C,GAKI,OAJIjD,KAAKM,OACLmC,EAAO,KAAMzC,KAAKM,OAGfN,IACX,CAMA,MAAA4D,GACI5D,KAAKiD,UAEDjD,KAAKO,MACLP,KAAKO,KAAKqD,OAAO5D,KAEzB"}
|
|
1
|
+
{"version":3,"file":"BaseElement.js","sources":["../../../../../src/components/internal/BaseElement/BaseElement.ts"],"sourcesContent":["import { ComponentChild, render } from 'preact';\nimport getProp from '../../../utils/getProp';\nimport uuid from '../../../utils/uuid';\nimport AdyenCheckoutError from '../../../core/Errors/AdyenCheckoutError';\nimport { ANALYTICS_RENDERED_STR } from '../../../core/Analytics/constants';\n\nimport type { ICore } from '../../../core/types';\nimport type { BaseElementProps, IBaseElement } from './types';\nimport type { PaymentData } from '../../../types/global-types';\nimport type { AnalyticsInitialEvent, SendAnalyticsObject } from '../../../core/Analytics/types';\n\n/**\n * Verify if the first parameter is instance of Core.\n * We do not use 'instanceof' to avoid importing the Core class directly into this class.\n * @param checkout\n */\nfunction assertIsCoreInstance(checkout: ICore): checkout is ICore {\n if (!checkout) return false;\n const isCoreObject = typeof checkout.initialize === 'function' && typeof checkout.createFromAction === 'function';\n return isCoreObject;\n}\n\nabstract class BaseElement<P extends BaseElementProps> implements IBaseElement {\n public readonly _id = `${this.constructor['type']}-${uuid()}`;\n public readonly core: ICore;\n\n public props: P;\n public state: any = {};\n public _component;\n\n protected _node: HTMLElement = null;\n\n protected static defaultProps = {};\n\n constructor(checkout: ICore, props?: P) {\n const isCoreInstance = assertIsCoreInstance(checkout);\n\n if (!isCoreInstance) {\n throw new AdyenCheckoutError(\n 'IMPLEMENTATION_ERROR',\n `Trying to initialise the component '${this.constructor['type']}' without a reference to an instance of AdyenCheckout`\n );\n }\n\n this.core = checkout;\n this.buildElementProps(props);\n }\n\n protected buildElementProps(componentProps?: P) {\n this.props = this.formatProps({ ...this.constructor['defaultProps'], ...componentProps });\n }\n\n /**\n * Executed during creation of any payment element.\n * Gives a chance to any paymentMethod to format the props we're receiving.\n */\n protected formatProps(props: P) {\n return props;\n }\n\n /**\n * Executed on the `data` getter.\n * Returns the component data necessary for the /payments request\n */\n protected formatData(): any {\n return {};\n }\n\n /* eslint-disable-next-line */\n protected setUpAnalytics(setUpAnalyticsObj: AnalyticsInitialEvent) {\n return null;\n }\n\n /* eslint-disable-next-line */\n protected submitAnalytics(analyticsObj?: SendAnalyticsObject) {\n return null;\n }\n\n protected setState(newState: object): void {\n this.state = { ...this.state, ...newState };\n }\n\n /**\n * Returns the component payment data ready to submit to the Checkout API\n * Note: this does not ensure validity, check isValid first\n */\n public get data(): PaymentData {\n const clientData = getProp(this.props, 'modules.risk.data');\n const useAnalytics = !!getProp(this.props, 'modules.analytics.getEnabled')?.();\n const checkoutAttemptId = useAnalytics ? getProp(this.props, 'modules.analytics.getCheckoutAttemptId')?.() : 'do-not-track';\n const order = this.state.order || this.props.order;\n const componentData = this.formatData();\n\n if (componentData.paymentMethod && checkoutAttemptId) {\n componentData.paymentMethod.checkoutAttemptId = checkoutAttemptId;\n }\n\n // Workaround, to be fixed properly\n // Remove the firstName & lastName in the billingAddress for non Riverty components\n // @ts-ignore type exists\n if (this.props.type !== 'riverty' && componentData.billingAddress) {\n const { firstName, lastName, ...rest } = componentData.billingAddress;\n componentData.billingAddress = { ...rest };\n }\n\n return {\n ...(clientData && { riskData: { clientData } }),\n ...(order && { order: { orderData: order.orderData, pspReference: order.pspReference } }),\n ...componentData,\n clientStateDataIndicator: true\n };\n }\n\n public render(): ComponentChild | Error {\n // render() not implemented in the element\n throw new Error('Payment method cannot be rendered.');\n }\n\n /**\n * Mounts an element into the dom\n * @param domNode - Node (or selector) where we will mount the payment element\n * @returns this - the payment element instance we mounted\n */\n public mount(domNode: HTMLElement | string): this {\n const node = typeof domNode === 'string' ? document.querySelector<HTMLElement>(domNode) : domNode;\n\n if (!node) {\n throw new Error('Component could not mount. Root node was not found.');\n }\n\n const setupAnalytics = !this._node;\n\n if (this._node) {\n this.unmount(); // new, if this._node exists then we are \"remounting\" so we first need to unmount if it's not already been done\n }\n\n this._node = node;\n\n this._component = this.render();\n\n render(this._component, node);\n\n // Set up analytics (once, since this._node is currently undefined) now that we have mounted and rendered\n if (setupAnalytics) {\n if (this.props.modules && this.props.modules.analytics) {\n this.setUpAnalytics({\n containerWidth: node && (node as HTMLElement).offsetWidth,\n component: !this.props.isDropin ? this.constructor['analyticsType'] ?? this.constructor['type'] : 'dropin',\n flavor: !this.props.isDropin ? 'components' : 'dropin'\n }).then(() => {\n // Once the initial analytics set up call has been made...\n // ...create an analytics event declaring that the component has been rendered\n // (The dropin will do this itself from DropinComponent once the PM list has rendered)\n if (!this.props.isDropin) {\n this.submitAnalytics({ type: ANALYTICS_RENDERED_STR });\n }\n });\n }\n }\n\n return this;\n }\n\n /**\n * Updates props, resets the internal state and remounts the element.\n *\n * @param props - props to update\n * @returns this - the element instance\n */\n public update(props: Partial<P>): this {\n this.props = this.formatProps({ ...this.props, ...props });\n this.state = {};\n\n return this.unmount().mount(this._node); // for new mount fny\n }\n\n /**\n * Unmounts a payment element from the DOM\n */\n public unmount(): this {\n if (this._node) {\n render(null, this._node);\n }\n\n return this;\n }\n\n /**\n * Unmounts an element and removes it from the parent instance\n * For \"destroy\" type cleanup - when you don't intend to use the component again\n */\n public remove() {\n this.unmount();\n\n if (this.core) {\n this.core.remove(this);\n }\n }\n}\n\nexport default BaseElement;\n"],"names":["BaseElement","_id","this","constructor","uuid","core","props","state","_component","_node","static","checkout","isCoreInstance","initialize","createFromAction","assertIsCoreInstance","AdyenCheckoutError","buildElementProps","componentProps","formatProps","formatData","setUpAnalytics","setUpAnalyticsObj","submitAnalytics","analyticsObj","setState","newState","data","clientData","getProp","checkoutAttemptId","order","componentData","paymentMethod","type","billingAddress","firstName","lastName","rest","riskData","orderData","pspReference","clientStateDataIndicator","render","Error","mount","domNode","node","document","querySelector","setupAnalytics","unmount","modules","analytics","containerWidth","offsetWidth","component","isDropin","flavor","then","ANALYTICS_RENDERED_STR","update","remove"],"mappings":"wRAsBA,MAAeA,EACKC,IAAM,GAAGC,KAAKC,YAAmB,QAAIC,MACrCC,KAETC,MACAC,MAAa,CAAA,EACbC,WAEGC,MAAqB,KAE/BC,oBAAgC,CAAA,EAEhCP,WAAAA,CAAYQ,EAAiBL,GACzB,MAAMM,EAnBd,SAA8BD,GAC1B,QAAKA,IAC+C,mBAAxBA,EAASE,YAAkE,mBAA9BF,EAASG,iBAEtF,CAe+BC,CAAqBJ,GAE5C,IAAKC,EACD,MAAM,IAAII,EACN,uBACA,uCAAuCd,KAAKC,YAAmB,6DAIvED,KAAKG,KAAOM,EACZT,KAAKe,kBAAkBX,EAC3B,CAEUW,iBAAAA,CAAkBC,GACxBhB,KAAKI,MAAQJ,KAAKiB,YAAY,IAAKjB,KAAKC,YAA2B,gBAAKe,GAC5E,CAMUC,WA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Q,YAC9CC,UAAYtD,KAAKI,MAAMmD,SAA2E,SAAhEvD,KAAKC,2BAAgCD,KAAKC,iBAC5EuD,OAASxD,KAAKI,MAAMmD,SAA0B,SAAf,eAChCE,MAAK,KAICzD,KAAKI,MAAMmD,UACZvD,KAAKqB,gBAAgB,CAAEW,KAAM0B,GACjC,IAKL1D,IACX,CAQO2D,MAAAA,CAAOvD,GAIV,OAHAJ,KAAKI,MAAQJ,KAAKiB,YAAY,IAAKjB,KAAKI,SAAUA,IAClDJ,KAAKK,MAAQ,GAENL,KAAKiD,UAAUN,MAAM3C,KAAKO,MACrC,CAKA,OAAA0C,GAKI,OAJIjD,KAAKO,OACLkC,EAAO,KAAMzC,KAAKO,OAGfP,IACX,CAMA,MAAA4D,GACI5D,KAAKiD,UAEDjD,KAAKG,MACLH,KAAKG,KAAKyD,OAAO5D,KAEzB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createElement as e}from"../../../external/preact/dist/preact.js";import{useRef as s,useState as r,useEffect as o}from"../../../external/preact/hooks/dist/hooks.js";import{useCoreContext as i}from"../../../core/Context/CoreProvider.js";import n from"../CompanyDetails/CompanyDetails.js";import t from"../PersonalDetails/PersonalDetails.js";import a from"../Address/Address.js";import l from"../FormFields/Checkbox/Checkbox.js";import d from"../FormFields/ConsentCheckbox/ConsentCheckbox.js";import{getInitialActiveFieldsets as c,fieldsetsSchema as m,getActiveFieldsData as p}from"./utils.js";import b from"../IbanInput/IbanInput.js";import u from"../FormFields/Field/Field.js";import y from"../FormInstruction/FormInstruction.js";import C from"./useSRPanelForOpenInvoiceErrors.js";const h={isValid:!1,errorMessage:"consent.checkbox.invalid",error:"consent.checkbox.invalid"};function f(f){const{countryCode:A,visibility:v}=f,{i18n:k}=i(),g=s({});Object.keys(g.current).length||f.setComponentRef?.(g.current);const D=s(!1),x=c(v,f.data),[F,j]=r(x),{current:w}=s(m.reduce(((e,s)=>(e[s]=e=>{w[s].current=e},e)),{})),R=!!f.consentCheckboxLabel,
|
|
1
|
+
import{createElement as e}from"../../../external/preact/dist/preact.js";import{useRef as s,useState as r,useEffect as o}from"../../../external/preact/hooks/dist/hooks.js";import{useCoreContext as i}from"../../../core/Context/CoreProvider.js";import n from"../CompanyDetails/CompanyDetails.js";import t from"../PersonalDetails/PersonalDetails.js";import a from"../Address/Address.js";import l from"../FormFields/Checkbox/Checkbox.js";import d from"../FormFields/ConsentCheckbox/ConsentCheckbox.js";import{getInitialActiveFieldsets as c,fieldsetsSchema as m,getActiveFieldsData as p}from"./utils.js";import b from"../IbanInput/IbanInput.js";import u from"../FormFields/Field/Field.js";import y from"../FormInstruction/FormInstruction.js";import C from"./useSRPanelForOpenInvoiceErrors.js";const h={isValid:!1,errorMessage:"consent.checkbox.invalid",error:"consent.checkbox.invalid"};function f(f){const{countryCode:A,visibility:v}=f,{i18n:k}=i(),g=s({});Object.keys(g.current).length||f.setComponentRef?.(g.current);const D=s(!1),x=c(v,f.data),[F,j]=r(x),{current:w}=s(m.reduce(((e,s)=>(e[s]=e=>{w[s].current=e},e)),{})),R=!!f.consentCheckboxLabel,E=!R&&Object.keys(F).every((e=>!F[e])),I="editable"===v.deliveryAddress&&"hidden"!==v.billingAddress,[S,q]=r({...f.data,...R&&{consentCheckbox:!1}}),[P,V]=r({}),[M,N]=r({}),[O,L]=r("ready");g.current.showValidation=()=>{D.current=!0,m.forEach((e=>{w[e].current&&w[e].current.showValidation()})),V({...R&&{consentCheckbox:S.consentCheckbox?null:h}})},g.current.setStatus=L,C({errors:P,data:S,props:f,isValidating:D}),o((()=>{const e=Object.keys(F).every((e=>!F[e]||!!M[e])),s=!R||!!M.consentCheckbox,r=e&&s,o=p(F,S);f.onChange({data:o,errors:P,valid:M,isValid:r})}),[S,F]);const B=e=>s=>{q((r=>({...r,[e]:s.data}))),N((r=>({...r,[e]:s.isValid}))),V((r=>({...r,[e]:s.errors})))};return e("div",{className:"adyen-checkout__open-invoice"},e(y,null),F.companyDetails&&e(n,{data:f.data.companyDetails,label:"companyDetails",onChange:B("companyDetails"),setComponentRef:w.companyDetails,visibility:v.companyDetails}),F.personalDetails&&e(t,{data:f.data.personalDetails,requiredFields:f.personalDetailsRequiredFields,label:"personalDetails",onChange:B("personalDetails"),setComponentRef:w.personalDetails,visibility:v.personalDetails}),F.bankAccount&&e(b,{holderName:!0,label:"bankAccount",data:S.bankAccount,onChange:B("bankAccount"),ref:w.bankAccount}),F.billingAddress&&e(a,{allowedCountries:f?.billingAddressSpecification?.allowedCountries??f.allowedCountries,countryCode:A,requiredFields:f.billingAddressRequiredFields,specifications:f.billingAddressSpecification,data:S.billingAddress,label:"billingAddress",onChange:B("billingAddress"),setComponentRef:w.billingAddress,visibility:v.billingAddress}),I&&e(u,{classNameModifiers:["separateDeliveryAddress","consentCheckbox"],name:"separateDeliveryAddress",useLabelElement:!1,showErrorElement:!1},e(l,{label:k.get("separateDeliveryAddress"),checked:F.deliveryAddress,classNameModifiers:["separateDeliveryAddress"],name:"separateDeliveryAddress",onChange:()=>{j((e=>({...e,deliveryAddress:!F.deliveryAddress})))}})),F.deliveryAddress&&e(a,{allowedCountries:f?.deliveryAddressSpecification?.allowedCountries??f.allowedCountries,countryCode:A,requiredFields:f.deliveryAddressRequiredFields,specifications:f.deliveryAddressSpecification,data:S.deliveryAddress,label:"deliveryAddress",onChange:B("deliveryAddress"),setComponentRef:w.deliveryAddress,visibility:v.deliveryAddress}),R&&e(d,{data:S,errorMessage:!!P.consentCheckbox,label:f.consentCheckboxLabel,onChange:e=>{const{checked:s}=e.target;q((e=>({...e,consentCheckbox:s}))),N((e=>({...e,consentCheckbox:s}))),V((e=>({...e,consentCheckbox:s?null:h})))},i18n:k}),f.showPayButton&&f.payButton({status:O,classNameModifiers:[...E?["standalone"]:[]],label:k.get("confirmPurchase")}))}export{f as default};
|
|
2
2
|
//# sourceMappingURL=OpenInvoice.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"OpenInvoice.js","sources":["../../../../../src/components/internal/OpenInvoice/OpenInvoice.tsx"],"sourcesContent":["import { h } from 'preact';\nimport { useEffect, useRef, useState } from 'preact/hooks';\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport CompanyDetails from '../CompanyDetails';\nimport PersonalDetails from '../PersonalDetails';\nimport Address from '../Address';\nimport Checkbox from '../FormFields/Checkbox';\nimport ConsentCheckbox from '../FormFields/ConsentCheckbox';\nimport { getActiveFieldsData, getInitialActiveFieldsets, fieldsetsSchema } from './utils';\nimport {\n OpenInvoiceActiveFieldsets,\n OpenInvoiceFieldsetsRefs,\n OpenInvoiceProps,\n OpenInvoiceStateData,\n OpenInvoiceStateError,\n OpenInvoiceStateValid\n} from './types';\nimport './OpenInvoice.scss';\nimport IbanInput from '../IbanInput';\nimport { GenericError } from '../../../core/Errors/types';\nimport Field from '../FormFields/Field';\nimport FormInstruction from '../FormInstruction';\nimport { ComponentMethodsRef } from '../UIElement/types';\nimport useSRPanelForOpenInvoiceErrors from './useSRPanelForOpenInvoiceErrors';\n\nconst consentCBErrorObj: GenericError = {\n isValid: false,\n errorMessage: 'consent.checkbox.invalid',\n error: 'consent.checkbox.invalid'\n};\n\nexport default function OpenInvoice(props: OpenInvoiceProps) {\n const { countryCode, visibility } = props;\n const { i18n } = useCoreContext();\n\n /** An object by which to expose 'public' members to the parent UIElement */\n const openInvoiceRef = useRef<ComponentMethodsRef>({});\n // Just call once\n if (!Object.keys(openInvoiceRef.current).length) {\n props.setComponentRef?.(openInvoiceRef.current);\n }\n\n const isValidating = useRef(false);\n\n const initialActiveFieldsets: OpenInvoiceActiveFieldsets = getInitialActiveFieldsets(visibility, props.data);\n const [activeFieldsets, setActiveFieldsets] = useState<OpenInvoiceActiveFieldsets>(initialActiveFieldsets);\n\n const { current: fieldsetsRefs } = useRef<OpenInvoiceFieldsetsRefs>(\n fieldsetsSchema.reduce((acc, fieldset) => {\n acc[fieldset] = ref => {\n fieldsetsRefs[fieldset].current = ref;\n };\n return acc;\n }, {})\n );\n\n const checkFieldsets = () => Object.keys(activeFieldsets).every(fieldset => !activeFieldsets[fieldset] || !!valid[fieldset]);\n const hasConsentCheckbox = !!props.consentCheckboxLabel;\n const isStandAloneButton = !hasConsentCheckbox && Object.keys(activeFieldsets).every(key => !activeFieldsets[key]);\n const showSeparateDeliveryAddressCheckbox = visibility.deliveryAddress === 'editable' && visibility.billingAddress !== 'hidden';\n\n const [data, setData] = useState<OpenInvoiceStateData>({\n ...props.data,\n ...(hasConsentCheckbox && { consentCheckbox: false })\n });\n const [errors, setErrors] = useState<OpenInvoiceStateError>({});\n const [valid, setValid] = useState<OpenInvoiceStateValid>({});\n const [status, setStatus] = useState('ready');\n\n // Expose methods expected by parent\n openInvoiceRef.current.showValidation = () => {\n isValidating.current = true;\n fieldsetsSchema.forEach(fieldset => {\n if (fieldsetsRefs[fieldset].current) fieldsetsRefs[fieldset].current.showValidation();\n });\n\n setErrors({\n ...(hasConsentCheckbox && { consentCheckbox: data.consentCheckbox ? null : consentCBErrorObj })\n });\n };\n\n openInvoiceRef.current.setStatus = setStatus;\n\n useSRPanelForOpenInvoiceErrors({ errors, data, props, isValidating });\n\n useEffect(() => {\n const fieldsetsAreValid: boolean = checkFieldsets();\n const consentCheckboxValid: boolean = !hasConsentCheckbox || !!valid.consentCheckbox;\n const isValid: boolean = fieldsetsAreValid && consentCheckboxValid;\n const newData: OpenInvoiceStateData = getActiveFieldsData(activeFieldsets, data);\n props.onChange({ data: newData, errors, valid, isValid });\n }, [data, activeFieldsets]);\n\n const handleFieldset = key => state => {\n setData(prevData => ({ ...prevData, [key]: state.data }));\n setValid(prevValid => ({ ...prevValid, [key]: state.isValid }));\n setErrors(prevErrors => ({ ...prevErrors, [key]: state.errors }));\n };\n\n const handleSeparateDeliveryAddress = () => {\n setActiveFieldsets(prevActiveFields => ({\n ...prevActiveFields,\n deliveryAddress: !activeFieldsets.deliveryAddress\n }));\n };\n\n const handleConsentCheckbox = e => {\n const { checked } = e.target;\n setData(prevData => ({ ...prevData, consentCheckbox: checked }));\n setValid(prevValid => ({ ...prevValid, consentCheckbox: checked }));\n setErrors(prevErrors => ({ ...prevErrors, ...{ consentCheckbox: !checked ? consentCBErrorObj : null } }));\n };\n return (\n <div className=\"adyen-checkout__open-invoice\">\n {props.showFormInstruction && <FormInstruction />}\n {activeFieldsets.companyDetails && (\n <CompanyDetails\n data={props.data.companyDetails}\n label=\"companyDetails\"\n onChange={handleFieldset('companyDetails')}\n setComponentRef={fieldsetsRefs.companyDetails}\n visibility={visibility.companyDetails}\n />\n )}\n\n {activeFieldsets.personalDetails && (\n <PersonalDetails\n data={props.data.personalDetails}\n requiredFields={props.personalDetailsRequiredFields}\n label=\"personalDetails\"\n onChange={handleFieldset('personalDetails')}\n setComponentRef={fieldsetsRefs.personalDetails}\n visibility={visibility.personalDetails}\n />\n )}\n\n {activeFieldsets.bankAccount && (\n <IbanInput\n holderName={true}\n label=\"bankAccount\"\n data={data.bankAccount}\n onChange={handleFieldset('bankAccount')}\n ref={fieldsetsRefs.bankAccount}\n />\n )}\n\n {activeFieldsets.billingAddress && (\n <Address\n allowedCountries={props?.billingAddressSpecification?.allowedCountries ?? props.allowedCountries}\n countryCode={countryCode}\n requiredFields={props.billingAddressRequiredFields}\n specifications={props.billingAddressSpecification}\n data={data.billingAddress}\n label=\"billingAddress\"\n onChange={handleFieldset('billingAddress')}\n setComponentRef={fieldsetsRefs.billingAddress}\n visibility={visibility.billingAddress}\n />\n )}\n\n {showSeparateDeliveryAddressCheckbox && (\n <Field\n classNameModifiers={['separateDeliveryAddress', 'consentCheckbox']}\n name={'separateDeliveryAddress'}\n useLabelElement={false}\n showErrorElement={false}\n >\n <Checkbox\n label={i18n.get('separateDeliveryAddress')}\n checked={activeFieldsets.deliveryAddress}\n classNameModifiers={['separateDeliveryAddress']}\n name={'separateDeliveryAddress'}\n onChange={handleSeparateDeliveryAddress}\n />\n </Field>\n )}\n\n {activeFieldsets.deliveryAddress && (\n <Address\n allowedCountries={props?.deliveryAddressSpecification?.allowedCountries ?? props.allowedCountries}\n countryCode={countryCode}\n requiredFields={props.deliveryAddressRequiredFields}\n specifications={props.deliveryAddressSpecification}\n data={data.deliveryAddress}\n label=\"deliveryAddress\"\n onChange={handleFieldset('deliveryAddress')}\n setComponentRef={fieldsetsRefs.deliveryAddress}\n visibility={visibility.deliveryAddress}\n />\n )}\n\n {hasConsentCheckbox && (\n <ConsentCheckbox\n data={data}\n errorMessage={!!errors.consentCheckbox}\n label={props.consentCheckboxLabel}\n onChange={handleConsentCheckbox}\n i18n={i18n}\n />\n )}\n\n {props.showPayButton &&\n props.payButton({\n status,\n classNameModifiers: [...(isStandAloneButton ? ['standalone'] : [])],\n label: i18n.get('confirmPurchase')\n })}\n </div>\n );\n}\n"],"names":["consentCBErrorObj","isValid","errorMessage","error","OpenInvoice","props","countryCode","visibility","i18n","useCoreContext","openInvoiceRef","useRef","Object","keys","current","length","setComponentRef","isValidating","initialActiveFieldsets","getInitialActiveFieldsets","data","activeFieldsets","setActiveFieldsets","useState","fieldsetsRefs","fieldsetsSchema","reduce","acc","fieldset","ref","hasConsentCheckbox","consentCheckboxLabel","isStandAloneButton","every","key","showSeparateDeliveryAddressCheckbox","deliveryAddress","billingAddress","setData","consentCheckbox","errors","setErrors","valid","setValid","status","setStatus","showValidation","forEach","useSRPanelForOpenInvoiceErrors","useEffect","fieldsetsAreValid","consentCheckboxValid","newData","getActiveFieldsData","onChange","handleFieldset","state","prevData","prevValid","prevErrors","h","div","className","showFormInstruction","FormInstruction","companyDetails","CompanyDetails","label","personalDetails","PersonalDetails","requiredFields","personalDetailsRequiredFields","bankAccount","IbanInput","holderName","Address","allowedCountries","billingAddressSpecification","billingAddressRequiredFields","specifications","Field","classNameModifiers","name","useLabelElement","showErrorElement","Checkbox","get","checked","prevActiveFields","deliveryAddressSpecification","deliveryAddressRequiredFields","ConsentCheckbox","e","target","showPayButton","payButton"],"mappings":"mxBAyBA,MAAMA,EAAkC,CACpCC,SAAS,EACTC,aAAc,2BACdC,MAAO,4BAG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AiB,EACjBC,kBAAkB,GAElBxB,EAACyB,EAAAA,CACGlB,MAAO3D,EAAK8E,IAAI,2BAChBC,QAASlE,EAAgBe,gBACzB6C,mBAAoB,CAAC,2BACrBC,KAAM,0BACN5B,SAzEkB,KAClChC,GAAmBkE,IAAqB,IACjCA,EACHpD,iBAAkBf,EAAgBe,mBACtC,KA0EKf,EAAgBe,iBACbwB,EAACe,EAAAA,CACGC,iBAAkBvE,GAAOoF,8BAA8Bb,kBAAoBvE,EAAMuE,iBACjFtE,YAAaA,EACbgE,eAAgBjE,EAAMqF,8BACtBX,eAAgB1E,EAAMoF,6BACtBrE,KAAMA,EAAKgB,gBACX+B,MAAM,kBACNb,SAAUC,EAAe,mBACzBvC,gBAAiBQ,EAAcY,gBAC/B7B,WAAYA,EAAW6B,kBAI9BN,GACG8B,EAAC+B,EAAAA,CACGvE,KAAMA,EACNlB,eAAgBsC,EAAOD,gBACvB4B,MAAO9D,EAAM0B,qBACbuB,SA1FcsC,IAC1B,MAAML,QAAEA,GAAYK,EAAEC,OACtBvD,GAAQmB,IAAa,IAAKA,EAAUlB,gBAAiBgD,MACrD5C,GAASe,IAAc,IAAKA,EAAWnB,gBAAiBgD,MACxD9C,GAAUkB,IAAe,IAAKA,EAAiBpB,gBAAkBgD,EAA8B,KAApBvF,KAA2B,EAuF1FQ,KAAMA,IAIbH,EAAMyF,eACHzF,EAAM0F,UAAU,CACZnD,SACAqC,mBAAoB,IAAKjD,EAAqB,CAAC,cAAgB,IAC/DmC,MAAO3D,EAAK8E,IAAI,qBAIpC"}
|
|
1
|
+
{"version":3,"file":"OpenInvoice.js","sources":["../../../../../src/components/internal/OpenInvoice/OpenInvoice.tsx"],"sourcesContent":["import { h } from 'preact';\nimport { useEffect, useRef, useState } from 'preact/hooks';\nimport { useCoreContext } from '../../../core/Context/CoreProvider';\nimport CompanyDetails from '../CompanyDetails';\nimport PersonalDetails from '../PersonalDetails';\nimport Address from '../Address';\nimport Checkbox from '../FormFields/Checkbox';\nimport ConsentCheckbox from '../FormFields/ConsentCheckbox';\nimport { getActiveFieldsData, getInitialActiveFieldsets, fieldsetsSchema } from './utils';\nimport {\n OpenInvoiceActiveFieldsets,\n OpenInvoiceFieldsetsRefs,\n OpenInvoiceProps,\n OpenInvoiceStateData,\n OpenInvoiceStateError,\n OpenInvoiceStateValid\n} from './types';\nimport './OpenInvoice.scss';\nimport IbanInput from '../IbanInput';\nimport { GenericError } from '../../../core/Errors/types';\nimport Field from '../FormFields/Field';\nimport FormInstruction from '../FormInstruction';\nimport { ComponentMethodsRef } from '../UIElement/types';\nimport useSRPanelForOpenInvoiceErrors from './useSRPanelForOpenInvoiceErrors';\n\nconst consentCBErrorObj: GenericError = {\n isValid: false,\n errorMessage: 'consent.checkbox.invalid',\n error: 'consent.checkbox.invalid'\n};\n\nexport default function OpenInvoice(props: OpenInvoiceProps) {\n const { countryCode, visibility } = props;\n const { i18n } = useCoreContext();\n\n /** An object by which to expose 'public' members to the parent UIElement */\n const openInvoiceRef = useRef<ComponentMethodsRef>({});\n // Just call once\n if (!Object.keys(openInvoiceRef.current).length) {\n props.setComponentRef?.(openInvoiceRef.current);\n }\n\n const isValidating = useRef(false);\n\n const initialActiveFieldsets: OpenInvoiceActiveFieldsets = getInitialActiveFieldsets(visibility, props.data);\n const [activeFieldsets, setActiveFieldsets] = useState<OpenInvoiceActiveFieldsets>(initialActiveFieldsets);\n\n const { current: fieldsetsRefs } = useRef<OpenInvoiceFieldsetsRefs>(\n fieldsetsSchema.reduce((acc, fieldset) => {\n acc[fieldset] = ref => {\n fieldsetsRefs[fieldset].current = ref;\n };\n return acc;\n }, {})\n );\n\n const checkFieldsets = () => Object.keys(activeFieldsets).every(fieldset => !activeFieldsets[fieldset] || !!valid[fieldset]);\n const hasConsentCheckbox = !!props.consentCheckboxLabel;\n const isStandAloneButton = !hasConsentCheckbox && Object.keys(activeFieldsets).every(key => !activeFieldsets[key]);\n const showSeparateDeliveryAddressCheckbox = visibility.deliveryAddress === 'editable' && visibility.billingAddress !== 'hidden';\n\n const [data, setData] = useState<OpenInvoiceStateData>({\n ...props.data,\n ...(hasConsentCheckbox && { consentCheckbox: false })\n });\n const [errors, setErrors] = useState<OpenInvoiceStateError>({});\n const [valid, setValid] = useState<OpenInvoiceStateValid>({});\n const [status, setStatus] = useState('ready');\n\n // Expose methods expected by parent\n openInvoiceRef.current.showValidation = () => {\n isValidating.current = true;\n fieldsetsSchema.forEach(fieldset => {\n if (fieldsetsRefs[fieldset].current) fieldsetsRefs[fieldset].current.showValidation();\n });\n\n setErrors({\n ...(hasConsentCheckbox && { consentCheckbox: data.consentCheckbox ? null : consentCBErrorObj })\n });\n };\n\n openInvoiceRef.current.setStatus = setStatus;\n\n useSRPanelForOpenInvoiceErrors({ errors, data, props, isValidating });\n\n useEffect(() => {\n const fieldsetsAreValid: boolean = checkFieldsets();\n const consentCheckboxValid: boolean = !hasConsentCheckbox || !!valid.consentCheckbox;\n const isValid: boolean = fieldsetsAreValid && consentCheckboxValid;\n const newData: OpenInvoiceStateData = getActiveFieldsData(activeFieldsets, data);\n props.onChange({ data: newData, errors, valid, isValid });\n }, [data, activeFieldsets]);\n\n const handleFieldset = key => state => {\n setData(prevData => ({ ...prevData, [key]: state.data }));\n setValid(prevValid => ({ ...prevValid, [key]: state.isValid }));\n setErrors(prevErrors => ({ ...prevErrors, [key]: state.errors }));\n };\n\n const handleSeparateDeliveryAddress = () => {\n setActiveFieldsets(prevActiveFields => ({\n ...prevActiveFields,\n deliveryAddress: !activeFieldsets.deliveryAddress\n }));\n };\n\n const handleConsentCheckbox = e => {\n const { checked } = e.target;\n setData(prevData => ({ ...prevData, consentCheckbox: checked }));\n setValid(prevValid => ({ ...prevValid, consentCheckbox: checked }));\n setErrors(prevErrors => ({ ...prevErrors, ...{ consentCheckbox: !checked ? consentCBErrorObj : null } }));\n };\n return (\n <div className=\"adyen-checkout__open-invoice\">\n <FormInstruction />\n\n {activeFieldsets.companyDetails && (\n <CompanyDetails\n data={props.data.companyDetails}\n label=\"companyDetails\"\n onChange={handleFieldset('companyDetails')}\n setComponentRef={fieldsetsRefs.companyDetails}\n visibility={visibility.companyDetails}\n />\n )}\n\n {activeFieldsets.personalDetails && (\n <PersonalDetails\n data={props.data.personalDetails}\n requiredFields={props.personalDetailsRequiredFields}\n label=\"personalDetails\"\n onChange={handleFieldset('personalDetails')}\n setComponentRef={fieldsetsRefs.personalDetails}\n visibility={visibility.personalDetails}\n />\n )}\n\n {activeFieldsets.bankAccount && (\n <IbanInput\n holderName={true}\n label=\"bankAccount\"\n data={data.bankAccount}\n onChange={handleFieldset('bankAccount')}\n ref={fieldsetsRefs.bankAccount}\n />\n )}\n\n {activeFieldsets.billingAddress && (\n <Address\n allowedCountries={props?.billingAddressSpecification?.allowedCountries ?? props.allowedCountries}\n countryCode={countryCode}\n requiredFields={props.billingAddressRequiredFields}\n specifications={props.billingAddressSpecification}\n data={data.billingAddress}\n label=\"billingAddress\"\n onChange={handleFieldset('billingAddress')}\n setComponentRef={fieldsetsRefs.billingAddress}\n visibility={visibility.billingAddress}\n />\n )}\n\n {showSeparateDeliveryAddressCheckbox && (\n <Field\n classNameModifiers={['separateDeliveryAddress', 'consentCheckbox']}\n name={'separateDeliveryAddress'}\n useLabelElement={false}\n showErrorElement={false}\n >\n <Checkbox\n label={i18n.get('separateDeliveryAddress')}\n checked={activeFieldsets.deliveryAddress}\n classNameModifiers={['separateDeliveryAddress']}\n name={'separateDeliveryAddress'}\n onChange={handleSeparateDeliveryAddress}\n />\n </Field>\n )}\n\n {activeFieldsets.deliveryAddress && (\n <Address\n allowedCountries={props?.deliveryAddressSpecification?.allowedCountries ?? props.allowedCountries}\n countryCode={countryCode}\n requiredFields={props.deliveryAddressRequiredFields}\n specifications={props.deliveryAddressSpecification}\n data={data.deliveryAddress}\n label=\"deliveryAddress\"\n onChange={handleFieldset('deliveryAddress')}\n setComponentRef={fieldsetsRefs.deliveryAddress}\n visibility={visibility.deliveryAddress}\n />\n )}\n\n {hasConsentCheckbox && (\n <ConsentCheckbox\n data={data}\n errorMessage={!!errors.consentCheckbox}\n label={props.consentCheckboxLabel}\n onChange={handleConsentCheckbox}\n i18n={i18n}\n />\n )}\n\n {props.showPayButton &&\n props.payButton({\n status,\n classNameModifiers: [...(isStandAloneButton ? ['standalone'] : [])],\n label: i18n.get('confirmPurchase')\n })}\n </div>\n );\n}\n"],"names":["consentCBErrorObj","isValid","errorMessage","error","OpenInvoice","props","countryCode","visibility","i18n","useCoreContext","openInvoiceRef","useRef","Object","keys","current","length","setComponentRef","isValidating","initialActiveFieldsets","getInitialActiveFieldsets","data","activeFieldsets","setActiveFieldsets","useState","fieldsetsRefs","fieldsetsSchema","reduce","acc","fieldset","ref","hasConsentCheckbox","consentCheckboxLabel","isStandAloneButton","every","key","showSeparateDeliveryAddressCheckbox","deliveryAddress","billingAddress","setData","consentCheckbox","errors","setErrors","valid","setValid","status","setStatus","showValidation","forEach","useSRPanelForOpenInvoiceErrors","useEffect","fieldsetsAreValid","consentCheckboxValid","newData","getActiveFieldsData","onChange","handleFieldset","state","prevData","prevValid","prevErrors","h","div","className","FormInstruction","companyDetails","CompanyDetails","label","personalDetails","PersonalDetails","requiredFields","personalDetailsRequiredFields","bankAccount","IbanInput","holderName","Address","allowedCountries","billingAddressSpecification","billingAddressRequiredFields","specifications","Field","classNameModifiers","name","useLabelElement","showErrorElement","Checkbox","get","checked","prevActiveFields","deliveryAddressSpecification","deliveryAddressRequiredFields","ConsentCheckbox","e","target","showPayButton","payButton"],"mappings":"mxBAyBA,MAAMA,EAAkC,CACpCC,SAAS,EACTC,aAAc,2BACdC,MAAO,4BAGI,SAASC,EAAYC,GAChC,MAAMC,YAAEA,EAAWC,WAAEA,GAAeF,GAC9BG,KAAEA,GAASC,IAGXC,EAAiBC,EAA4B,CAAA,GAE9CC,OAAOC,KAAKH,EAAeI,SAASC,QACrCV,EAAMW,kBAAkBN,EAAeI,SAG3C,MAAMG,EAAeN,GAAO,GAEtBO,EAAqDC,EAA0BZ,E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B,EAACc,EAAAA,CACGC,iBAAkBtE,GAAOmF,8BAA8Bb,kBAAoBtE,EAAMsE,iBACjFrE,YAAaA,EACb+D,eAAgBhE,EAAMoF,8BACtBX,eAAgBzE,EAAMmF,6BACtBpE,KAAMA,EAAKgB,gBACX8B,MAAM,kBACNZ,SAAUC,EAAe,mBACzBvC,gBAAiBQ,EAAcY,gBAC/B7B,WAAYA,EAAW6B,kBAI9BN,GACG8B,EAAC8B,EAAAA,CACGtE,KAAMA,EACNlB,eAAgBsC,EAAOD,gBACvB2B,MAAO7D,EAAM0B,qBACbuB,SA3FcqC,IAC1B,MAAML,QAAEA,GAAYK,EAAEC,OACtBtD,GAAQmB,IAAa,IAAKA,EAAUlB,gBAAiB+C,MACrD3C,GAASe,IAAc,IAAKA,EAAWnB,gBAAiB+C,MACxD7C,GAAUkB,IAAe,IAAKA,EAAiBpB,gBAAkB+C,EAA8B,KAApBtF,KAA2B,EAwF1FQ,KAAMA,IAIbH,EAAMwF,eACHxF,EAAMyF,UAAU,CACZlD,SACAoC,mBAAoB,IAAKhD,EAAqB,CAAC,cAAgB,IAC/DkC,MAAO1D,EAAK6E,IAAI,qBAIpC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Component as s}from"../../../../external/preact/dist/preact.js";import{getFields as t,validFieldsReducer as e,getErrorReducer as i,getErrorObject as o}from"./SFPUtils.js";import n from"../lib/CSF/initCSF.js";import r from"./SecuredFieldsProviderHandlers.js";import a from"./defaultProps.js";import{CVC_POLICY_REQUIRED as d,DATE_POLICY_REQUIRED as h,ENCRYPTED_PWD_FIELD as l,ENCRYPTED_CARD_NUMBER as p,DEDICATED_CARD_COMPONENTS as c}from"../lib/constants.js";import u from"../../../../core/Errors/AdyenCheckoutError.js";import{getErrorMessageFromCode as f}from"../../../../core/Errors/utils.js";import{SF_ErrorCodes as m}from"../../../../core/Errors/constants.js";class F extends s{csfLoadFailTimeout;csfLoadFailTimeoutMS;csfConfigFailTimeout;csfConfigFailTimeoutMS;numCharsInField;rootNode;numDateFields;csf;handleOnLoad;handleOnConfigSuccess;handleOnFieldValid;handleOnAllValid;handleOnBrand;handleFocus;handleOnError;handleOnAutoComplete;handleOnNoDataRequired;handleOnTouchstartIOS;state;props;issuingCountryCode;constructor(s){super(s);const t={status:"loading",brand:s.type,errors:{},valid:{},data:{},cvcPolicy:d,expiryDatePolicy:h,isSfpValid:!1,hasKoreanFields:s.hasKoreanFields};this.state=t,this.csfLoadFailTimeout=null,this.csfLoadFailTimeoutMS=3e4,this.csfConfigFailTimeout=null,this.csfConfigFailTimeoutMS=15e3,this.numCharsInField={},this.handleOnLoad=r.handleOnLoad.bind(this),this.handleOnConfigSuccess=r.handleOnConfigSuccess.bind(this),this.handleOnFieldValid=r.handleOnFieldValid.bind(this),this.handleOnAllValid=r.handleOnAllValid.bind(this),this.handleOnBrand=r.handleOnBrand.bind(this),this.handleFocus=r.handleFocus.bind(this),this.handleOnError=r.handleOnError.bind(this),this.handleOnNoDataRequired=r.handleOnNoDataRequired.bind(this),this.handleOnAutoComplete=r.handleOnAutoComplete.bind(this),this.handleOnTouchstartIOS=r.handleOnTouchstartIOS.bind(this),this.processBinLookupResponse=this.processBinLookupResponse.bind(this),this.setFocusOn=this.setFocusOn.bind(this),this.updateStyles=this.updateStyles.bind(this),this.handleUnsupportedCard=this.handleUnsupportedCard.bind(this),this.showValidation=this.showValidation.bind(this),this.destroy=this.destroy.bind(this)}static defaultProps=a;componentDidMount(){this.props.rootNode&&this.setRootNode(this.props.rootNode);const s=t(this.rootNode),i=s.reduce(e,{});this.setState({valid:i}),s.forEach((s=>{this.numCharsInField[s]=0})),this.numDateFields=s.filter((s=>s.match(/Expiry/))).length,s.length?(this.destroy(),this.initializeCSF(this.rootNode)):this.handleOnNoDataRequired()}componentDidUpdate(){this.checkForKCPFields()}componentWillUnmount(){this.csf=null,clearTimeout(this.csfLoadFailTimeout),clearTimeout(this.csfConfigFailTimeout)}initializeCSF(s){let t=this.props.loadingContext;const e={rootNode:s,type:this.props.type,clientKey:this.props.clientKey,cardGroupTypes:this.props.brands,autoFocus:this.props.autoFocus,trimTrailingSeparator:this.props.trimTrailingSeparator,loadingContext:t,keypadFix:this.props.keypadFix,showWarnings:this.props.showWarnings,iframeUIConfig:{sfStyles:this.props.styles},i18n:this.props.i18n,callbacks:{onLoad:this.handleOnLoad,onConfigSuccess:this.handleOnConfigSuccess,onFieldValid:this.handleOnFieldValid,onAllValid:this.handleOnAllValid,onBrand:this.handleOnBrand,onError:this.handleOnError,onFocus:this.handleFocus,onBinValue:this.props.onBinValue,onAutoComplete:this.handleOnAutoComplete,onAdditionalSFConfig:this.props.onAdditionalSFConfig,onAdditionalSFRemoved:this.props.onAdditionalSFRemoved,onTouchstartIOS:this.handleOnTouchstartIOS},isKCP:this.state.hasKoreanFields,legacyInputMode:this.props.legacyInputMode,minimumExpiryDate:this.props.minimumExpiryDate,implementationType:this.props.implementationType||"components",forceCompat:this.props.forceCompat,maskSecurityCode:this.props.maskSecurityCode,shouldDisableIOSArrowKeys:!!this.props.disableIOSArrowKeys,placeholders:this.props.placeholders??{},showContextualElement:this.props.showContextualElement};this.csf=n(e),this.csfLoadFailTimeout=setTimeout((()=>{"ready"!==this.state.status&&(this.setState({status:"csfLoadFailure"}),this.props.onError(new u("ERROR","secured field iframes have failed to load")))}),this.csfLoadFailTimeoutMS)}checkForKCPFields(){let s=!1;if(this.props.koreanAuthenticationRequired&&(s=this.issuingCountryCode?"kr"===this.issuingCountryCode:"kr"===this.props.countryCode),this.state.hasKoreanFields&&!s){const s=s=>({data:{...s.data,[l]:void 0},valid:{...s.valid,[l]:!1},errors:{...s.errors,[l]:!1},hasKoreanFields:!1});this.setState(s,(()=>{this.props.onChange(this.state)})),this.csf.removeSecuredField(l),this.csf.setKCPStatus(!1)}if(!this.state.hasKoreanFields&&s){const s=s=>({valid:{...s.valid,[l]:!1},hasKoreanFields:!0,isSfpValid:!1});this.setState(s,(()=>{this.props.onChange(this.state)})),this.csf.addSecuredField(l),this.csf.setKCPStatus(!0)}}getChildContext(){return{i18n:this.props.i18n}}handleUnsupportedCard(s){const t=!!s.error;return t&&this.setState({detectedUnsupportedBrands:s.detectedBrands}),s.rootNode=this.rootNode,this.handleOnError(s,t),this.csf&&this.csf.hasUnsupportedCard(p,s.error),t}setFocusOn(s){this.csf&&this.csf.setFocusOnFrame(s)}updateStyles(s){this.csf&&this.csf.updateStyles(s)}sfIsOptionalOrHidden(s){return this.csf.sfIsOptionalOrHidden(s)}destroy(){this.csf&&this.csf.destroy()}showValidation(){const{numDateFields:s,state:t}=this;Object.keys(t.valid).reduce(i(s,t),[]).forEach((s=>{const e=o(s,this.rootNode,t);this.handleOnError(e,!!t.detectedUnsupportedBrands),this.csf&&this.csf.isValidated&&this.csf.isValidated(s,e.error)}))}mapErrorsToValidationRuleResult(){return Object.keys(this.state.errors).reduce(((s,t)=>{const e=this.state.errors[t];return s[t]=e?{isValid:!1,errorMessage:f(e,m),errorI18n:this.props.i18n.get(e),error:e,rootNode:this.rootNode,...this.state.detectedUnsupportedBrands&&{detectedBrands:this.state.detectedUnsupportedBrands}}:null,s}),{})}processBinLookupResponse(s,t){if(this.state.detectedUnsupportedBrands&&(this.setState((s=>({errors:{...s.errors,[p]:!1},detectedUnsupportedBrands:null}))),this.csf&&s)){const s={type:"card",fieldType:"encryptedCardNumber",error:""};this.handleUnsupportedCard(s)}this.issuingCountryCode=s?.issuingCountryCode?.toLowerCase();const e=t?.brand,i=e&&c.includes(t.brand);i&&this.setState(t,(()=>{this.props.onChange(this.state)})),this.csf&&this.csf.brandsFromBinLookup(s,i?t:null)}setRootNode=s=>{this.rootNode=s};render(s,t){return s.render({setRootNode:this.setRootNode,setFocusOn:this.setFocusOn},t)}}export{F as default};
|
|
1
|
+
import{Component as s}from"../../../../external/preact/dist/preact.js";import{getFields as t,validFieldsReducer as e,getErrorReducer as i,getErrorObject as o}from"./SFPUtils.js";import n from"../lib/CSF/initCSF.js";import r from"./SecuredFieldsProviderHandlers.js";import a from"./defaultProps.js";import{CVC_POLICY_REQUIRED as d,DATE_POLICY_REQUIRED as h,ENCRYPTED_PWD_FIELD as l,ENCRYPTED_CARD_NUMBER as p,DEDICATED_CARD_COMPONENTS as c}from"../lib/constants.js";import u from"../../../../core/Errors/AdyenCheckoutError.js";import{getErrorMessageFromCode as f}from"../../../../core/Errors/utils.js";import{SF_ErrorCodes as m}from"../../../../core/Errors/constants.js";class F extends s{csfLoadFailTimeout;csfLoadFailTimeoutMS;csfConfigFailTimeout;csfConfigFailTimeoutMS;numCharsInField;rootNode;numDateFields;csf;handleOnLoad;handleOnConfigSuccess;handleOnFieldValid;handleOnAllValid;handleOnBrand;handleFocus;handleOnError;handleOnAutoComplete;handleOnNoDataRequired;handleOnTouchstartIOS;state;props;issuingCountryCode;constructor(s){super(s);const t={status:"loading",brand:s.type,errors:{},valid:{},data:{},cvcPolicy:d,expiryDatePolicy:h,isSfpValid:!1,hasKoreanFields:s.hasKoreanFields};this.state=t,this.csfLoadFailTimeout=null,this.csfLoadFailTimeoutMS=3e4,this.csfConfigFailTimeout=null,this.csfConfigFailTimeoutMS=15e3,this.numCharsInField={},this.handleOnLoad=r.handleOnLoad.bind(this),this.handleOnConfigSuccess=r.handleOnConfigSuccess.bind(this),this.handleOnFieldValid=r.handleOnFieldValid.bind(this),this.handleOnAllValid=r.handleOnAllValid.bind(this),this.handleOnBrand=r.handleOnBrand.bind(this),this.handleFocus=r.handleFocus.bind(this),this.handleOnError=r.handleOnError.bind(this),this.handleOnNoDataRequired=r.handleOnNoDataRequired.bind(this),this.handleOnAutoComplete=r.handleOnAutoComplete.bind(this),this.handleOnTouchstartIOS=r.handleOnTouchstartIOS.bind(this),this.processBinLookupResponse=this.processBinLookupResponse.bind(this),this.setFocusOn=this.setFocusOn.bind(this),this.updateStyles=this.updateStyles.bind(this),this.handleUnsupportedCard=this.handleUnsupportedCard.bind(this),this.showValidation=this.showValidation.bind(this),this.destroy=this.destroy.bind(this)}static defaultProps=a;componentDidMount(){this.props.rootNode&&this.setRootNode(this.props.rootNode);const s=t(this.rootNode),i=s.reduce(e,{});this.setState({valid:i}),s.forEach((s=>{this.numCharsInField[s]=0})),this.numDateFields=s.filter((s=>s.match(/Expiry/))).length,s.length?(this.destroy(),this.initializeCSF(this.rootNode)):this.handleOnNoDataRequired()}componentDidUpdate(){this.checkForKCPFields()}componentWillUnmount(){this.csf=null,clearTimeout(this.csfLoadFailTimeout),clearTimeout(this.csfConfigFailTimeout)}initializeCSF(s){let t=this.props.loadingContext;const e={rootNode:s,type:this.props.type,clientKey:this.props.clientKey,cardGroupTypes:this.props.brands,autoFocus:this.props.autoFocus,trimTrailingSeparator:this.props.trimTrailingSeparator,loadingContext:t,keypadFix:this.props.keypadFix,showWarnings:this.props.showWarnings,iframeUIConfig:{sfStyles:this.props.styles},i18n:this.props.i18n,callbacks:{onLoad:this.handleOnLoad,onConfigSuccess:this.handleOnConfigSuccess,onFieldValid:this.handleOnFieldValid,onAllValid:this.handleOnAllValid,onBrand:this.handleOnBrand,onError:this.handleOnError,onFocus:this.handleFocus,onBinValue:this.props.onBinValue,onAutoComplete:this.handleOnAutoComplete,onAdditionalSFConfig:this.props.onAdditionalSFConfig,onAdditionalSFRemoved:this.props.onAdditionalSFRemoved,onTouchstartIOS:this.handleOnTouchstartIOS},isKCP:this.state.hasKoreanFields,legacyInputMode:this.props.legacyInputMode,minimumExpiryDate:this.props.minimumExpiryDate,implementationType:this.props.implementationType||"components",forceCompat:this.props.forceCompat,maskSecurityCode:this.props.maskSecurityCode,exposeExpiryDate:this.props.exposeExpiryDate,shouldDisableIOSArrowKeys:!!this.props.disableIOSArrowKeys,placeholders:this.props.placeholders??{},showContextualElement:this.props.showContextualElement};this.csf=n(e),this.csfLoadFailTimeout=setTimeout((()=>{"ready"!==this.state.status&&(this.setState({status:"csfLoadFailure"}),this.props.onError(new u("ERROR","secured field iframes have failed to load")))}),this.csfLoadFailTimeoutMS)}checkForKCPFields(){let s=!1;if(this.props.koreanAuthenticationRequired&&(s=this.issuingCountryCode?"kr"===this.issuingCountryCode:"kr"===this.props.countryCode),this.state.hasKoreanFields&&!s){const s=s=>({data:{...s.data,[l]:void 0},valid:{...s.valid,[l]:!1},errors:{...s.errors,[l]:!1},hasKoreanFields:!1});this.setState(s,(()=>{this.props.onChange(this.state)})),this.csf.removeSecuredField(l),this.csf.setKCPStatus(!1)}if(!this.state.hasKoreanFields&&s){const s=s=>({valid:{...s.valid,[l]:!1},hasKoreanFields:!0,isSfpValid:!1});this.setState(s,(()=>{this.props.onChange(this.state)})),this.csf.addSecuredField(l),this.csf.setKCPStatus(!0)}}getChildContext(){return{i18n:this.props.i18n}}handleUnsupportedCard(s){const t=!!s.error;return t&&this.setState({detectedUnsupportedBrands:s.detectedBrands}),s.rootNode=this.rootNode,this.handleOnError(s,t),this.csf&&this.csf.hasUnsupportedCard(p,s.error),t}setFocusOn(s){this.csf&&this.csf.setFocusOnFrame(s)}updateStyles(s){this.csf&&this.csf.updateStyles(s)}sfIsOptionalOrHidden(s){return this.csf.sfIsOptionalOrHidden(s)}destroy(){this.csf&&this.csf.destroy()}showValidation(){const{numDateFields:s,state:t}=this;Object.keys(t.valid).reduce(i(s,t),[]).forEach((s=>{const e=o(s,this.rootNode,t);this.handleOnError(e,!!t.detectedUnsupportedBrands),this.csf&&this.csf.isValidated&&this.csf.isValidated(s,e.error)}))}mapErrorsToValidationRuleResult(){return Object.keys(this.state.errors).reduce(((s,t)=>{const e=this.state.errors[t];return s[t]=e?{isValid:!1,errorMessage:f(e,m),errorI18n:this.props.i18n.get(e),error:e,rootNode:this.rootNode,...this.state.detectedUnsupportedBrands&&{detectedBrands:this.state.detectedUnsupportedBrands}}:null,s}),{})}processBinLookupResponse(s,t){if(this.state.detectedUnsupportedBrands&&(this.setState((s=>({errors:{...s.errors,[p]:!1},detectedUnsupportedBrands:null}))),this.csf&&s)){const s={type:"card",fieldType:"encryptedCardNumber",error:""};this.handleUnsupportedCard(s)}this.issuingCountryCode=s?.issuingCountryCode?.toLowerCase();const e=t?.brand,i=e&&c.includes(t.brand);i&&this.setState(t,(()=>{this.props.onChange(this.state)})),this.csf&&this.csf.brandsFromBinLookup(s,i?t:null)}setRootNode=s=>{this.rootNode=s};render(s,t){return s.render({setRootNode:this.setRootNode,setFocusOn:this.setFocusOn},t)}}export{F as default};
|
|
2
2
|
//# sourceMappingURL=SecuredFieldsProvider.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SecuredFieldsProvider.js","sources":["../../../../../../src/components/internal/SecuredFields/SFP/SecuredFieldsProvider.ts"],"sourcesContent":["import { Component } from 'preact';\nimport { getErrorObject, getFields, getErrorReducer, validFieldsReducer } from './SFPUtils';\nimport initCSF from '../lib/CSF';\nimport handlers from './SecuredFieldsProviderHandlers';\nimport defaultProps from './defaultProps';\nimport { SFPProps, SFPState, SingleBrandResetObject } from './types';\nimport {\n StylesObject,\n CbObjOnError,\n CbObjOnFocus,\n CbObjOnBrand,\n CbObjOnAllValid,\n CbObjOnFieldValid,\n CbObjOnAutoComplete,\n CbObjOnConfigSuccess,\n CbObjOnLoad\n} from '../lib/types';\nimport { CSFReturnObject, CSFSetupObject } from '../lib/CSF/types';\nimport { CVC_POLICY_REQUIRED, DATE_POLICY_REQUIRED, DEDICATED_CARD_COMPONENTS, ENCRYPTED_CARD_NUMBER, ENCRYPTED_PWD_FIELD } from '../lib/constants';\nimport { BinLookupResponse } from '../../../Card/types';\nimport AdyenCheckoutError from '../../../../core/Errors/AdyenCheckoutError';\nimport { SFStateErrorObj } from '../../../Card/components/CardInput/types';\nimport { getErrorMessageFromCode } from '../../../../core/Errors/utils';\nimport { SF_ErrorCodes } from '../../../../core/Errors/constants';\n\n/**\n * SecuredFieldsProvider:\n * Initialises & handles the client-side part of SecuredFields\n */\nclass SecuredFieldsProvider extends Component<SFPProps, SFPState> {\n private csfLoadFailTimeout: number;\n private csfLoadFailTimeoutMS: number;\n private csfConfigFailTimeout: number;\n private csfConfigFailTimeoutMS: number;\n private numCharsInField: object;\n private rootNode;\n private numDateFields: number;\n private csf: CSFReturnObject;\n private handleOnLoad: (obj: CbObjOnLoad) => void;\n private handleOnConfigSuccess: (obj: CbObjOnConfigSuccess) => void;\n private handleOnFieldValid: (obj: CbObjOnFieldValid) => void;\n private handleOnAllValid: (obj: CbObjOnAllValid) => void;\n private handleOnBrand: (obj: CbObjOnBrand) => void;\n private handleFocus: (obj: CbObjOnFocus) => void;\n private handleOnError: (obj: CbObjOnError, hasUnsupportedCard?: boolean) => void;\n private handleOnAutoComplete: (obj: CbObjOnAutoComplete) => void;\n private handleOnNoDataRequired: () => void;\n private handleOnTouchstartIOS: (obj) => void;\n public state: SFPState;\n public props;\n private issuingCountryCode;\n\n constructor(props: SFPProps) {\n super(props);\n\n const stateObj: SFPState = {\n status: 'loading',\n brand: props.type,\n errors: {},\n valid: {},\n data: {},\n cvcPolicy: CVC_POLICY_REQUIRED,\n expiryDatePolicy: DATE_POLICY_REQUIRED,\n isSfpValid: false,\n hasKoreanFields: props.hasKoreanFields\n };\n this.state = stateObj;\n\n this.csfLoadFailTimeout = null;\n this.csfLoadFailTimeoutMS = 30000;\n\n this.csfConfigFailTimeout = null;\n this.csfConfigFailTimeoutMS = 15000;\n\n this.numCharsInField = {};\n\n // Handlers\n this.handleOnLoad = handlers.handleOnLoad.bind(this);\n this.handleOnConfigSuccess = handlers.handleOnConfigSuccess.bind(this);\n this.handleOnFieldValid = handlers.handleOnFieldValid.bind(this);\n this.handleOnAllValid = handlers.handleOnAllValid.bind(this);\n this.handleOnBrand = handlers.handleOnBrand.bind(this);\n this.handleFocus = handlers.handleFocus.bind(this);\n this.handleOnError = handlers.handleOnError.bind(this);\n this.handleOnNoDataRequired = handlers.handleOnNoDataRequired.bind(this);\n this.handleOnAutoComplete = handlers.handleOnAutoComplete.bind(this);\n this.handleOnTouchstartIOS = handlers.handleOnTouchstartIOS.bind(this); // Only called when iOS detected\n\n this.processBinLookupResponse = this.processBinLookupResponse.bind(this);\n\n // Bindings for functions exposed to users of this component: SecuredFields & CardInput\n this.setFocusOn = this.setFocusOn.bind(this);\n this.updateStyles = this.updateStyles.bind(this);\n this.handleUnsupportedCard = this.handleUnsupportedCard.bind(this);\n this.showValidation = this.showValidation.bind(this);\n this.destroy = this.destroy.bind(this);\n }\n\n public static defaultProps = defaultProps;\n\n public componentDidMount(): void {\n // When SFP instantiated through SecuredFieldsInput c.f. CardInput\n if (this.props.rootNode) {\n this.setRootNode(this.props.rootNode);\n }\n\n // Find encryptedFields and map them to the values we use to store valid states\n const fields = getFields(this.rootNode);\n const valid = fields.reduce(validFieldsReducer, {});\n\n this.setState({ valid });\n\n // Populate numCharsInField object\n fields.forEach(field => {\n this.numCharsInField[field] = 0;\n });\n\n // Store how many dateFields we are dealing with visually\n this.numDateFields = fields.filter(f => f.match(/Expiry/)).length;\n\n if (fields.length) {\n this.destroy(); // TODO test if this solves the React double render problem.\n this.initializeCSF(this.rootNode);\n } else {\n this.handleOnNoDataRequired();\n }\n }\n\n public componentDidUpdate() {\n this.checkForKCPFields();\n }\n\n public componentWillUnmount(): void {\n this.csf = null;\n clearTimeout(this.csfLoadFailTimeout);\n clearTimeout(this.csfConfigFailTimeout);\n }\n\n private initializeCSF(root: HTMLElement): void {\n let loadingContext = this.props.loadingContext;\n\n // For loading securedFields from local server during development\n if (process.env.NODE_ENV === 'development' && process.env.__SF_ENV__ !== 'build') {\n loadingContext = process.env.__SF_ENV__;\n }\n\n // TODO\n // if(!this.props.keypadFix){\n // send analytics action because to know if anyone *ever* sets this config prop\n // }\n\n const csfSetupObj: CSFSetupObject = {\n rootNode: root,\n type: this.props.type,\n clientKey: this.props.clientKey,\n cardGroupTypes: this.props.brands,\n autoFocus: this.props.autoFocus,\n trimTrailingSeparator: this.props.trimTrailingSeparator,\n loadingContext,\n keypadFix: this.props.keypadFix,\n showWarnings: this.props.showWarnings,\n iframeUIConfig: {\n sfStyles: this.props.styles\n },\n i18n: this.props.i18n,\n callbacks: {\n onLoad: this.handleOnLoad,\n onConfigSuccess: this.handleOnConfigSuccess,\n onFieldValid: this.handleOnFieldValid,\n onAllValid: this.handleOnAllValid,\n onBrand: this.handleOnBrand,\n onError: this.handleOnError,\n onFocus: this.handleFocus,\n onBinValue: this.props.onBinValue,\n onAutoComplete: this.handleOnAutoComplete,\n onAdditionalSFConfig: this.props.onAdditionalSFConfig,\n onAdditionalSFRemoved: this.props.onAdditionalSFRemoved,\n onTouchstartIOS: this.handleOnTouchstartIOS\n },\n isKCP: this.state.hasKoreanFields,\n legacyInputMode: this.props.legacyInputMode,\n minimumExpiryDate: this.props.minimumExpiryDate,\n implementationType: this.props.implementationType || 'components', // to distinguish between 'regular' and 'custom' card component\n forceCompat: this.props.forceCompat,\n maskSecurityCode: this.props.maskSecurityCode,\n shouldDisableIOSArrowKeys: !!this.props.disableIOSArrowKeys, // convert whether function has been defined into a boolean\n placeholders: this.props.placeholders ?? {},\n showContextualElement: this.props.showContextualElement\n };\n\n this.csf = initCSF(csfSetupObj);\n\n /**\n * Expect to at least have had the handleOnLoad callback called within this time\n * - if this hasn't happened then something has happened to interrupt the loading of the securedFields\n * So we need to clear the loading spinner to see if the securedFields are reporting anything\n */\n // @ts-ignore - timout 'type' is a number\n this.csfLoadFailTimeout = setTimeout(() => {\n if (this.state.status !== 'ready') {\n // Hide the spinner\n this.setState({ status: 'csfLoadFailure' });\n // Report the error\n this.props.onError(new AdyenCheckoutError('ERROR', 'secured field iframes have failed to load'));\n }\n }, this.csfLoadFailTimeoutMS);\n }\n\n private checkForKCPFields() {\n let needsKoreanFields = false;\n if (this.props.koreanAuthenticationRequired) {\n needsKoreanFields = this.issuingCountryCode ? this.issuingCountryCode === 'kr' : this.props.countryCode === 'kr';\n }\n\n // Was korean, now isn't - hide password field\n if (this.state.hasKoreanFields && !needsKoreanFields) {\n // Clear any stored data\n const setRemovedFieldState = prevState => ({\n data: { ...prevState.data, [ENCRYPTED_PWD_FIELD]: undefined },\n valid: { ...prevState.valid, [ENCRYPTED_PWD_FIELD]: false },\n errors: { ...prevState.errors, [ENCRYPTED_PWD_FIELD]: false },\n hasKoreanFields: false\n });\n\n this.setState(setRemovedFieldState, () => {\n this.props.onChange(this.state);\n });\n\n this.csf.removeSecuredField(ENCRYPTED_PWD_FIELD);\n this.csf.setKCPStatus(false);\n }\n\n // Wasn't korean, now is - show password field\n if (!this.state.hasKoreanFields && needsKoreanFields) {\n const setAddedFieldState = prevState => ({\n valid: { ...prevState.valid, [ENCRYPTED_PWD_FIELD]: false },\n hasKoreanFields: true,\n isSfpValid: false\n });\n\n this.setState(setAddedFieldState, () => {\n this.props.onChange(this.state);\n });\n\n this.csf.addSecuredField(ENCRYPTED_PWD_FIELD);\n this.csf.setKCPStatus(true);\n }\n }\n\n public getChildContext(): object {\n return { i18n: this.props.i18n };\n }\n\n public handleUnsupportedCard(errObj: CbObjOnError): boolean {\n const hasUnsupportedCard = !!errObj.error;\n\n // Store the brand(s) we detected and which we don't support\n if (hasUnsupportedCard) {\n this.setState({ detectedUnsupportedBrands: errObj.detectedBrands });\n }\n\n errObj.rootNode = this.rootNode; // Needed for CustomCard\n this.handleOnError(errObj, hasUnsupportedCard);\n // Inform CSF that the number field has an unsupportedCard error (or that it has been cleared)\n if (this.csf) {\n this.csf.hasUnsupportedCard(ENCRYPTED_CARD_NUMBER, errObj.error);\n }\n return hasUnsupportedCard;\n }\n\n public setFocusOn(frame: string): void {\n if (this.csf) this.csf.setFocusOnFrame(frame);\n }\n\n public updateStyles(stylesObj: StylesObject): void {\n if (this.csf) this.csf.updateStyles(stylesObj);\n }\n\n public sfIsOptionalOrHidden(fieldType: string): boolean {\n return this.csf.sfIsOptionalOrHidden(fieldType);\n }\n\n public destroy(): void {\n if (this.csf) this.csf.destroy();\n }\n\n public showValidation(): void {\n const { numDateFields, state }: SecuredFieldsProvider = this;\n\n Object.keys(state.valid)\n .reduce(getErrorReducer(numDateFields, state), [])\n .forEach(field => {\n // For each detected error pass an error object to the handler (calls error callback & sets state)\n const errorObj: CbObjOnError = getErrorObject(field, this.rootNode, state);\n this.handleOnError(errorObj, !!state.detectedUnsupportedBrands);\n // Inform the secured-fields instance of which fields have been found to have errors\n if (this.csf && this.csf.isValidated) {\n this.csf.isValidated(field, errorObj.error);\n }\n });\n }\n\n /**\n * Map SF errors to ValidationRuleResult-like objects, for CardInput component\n */\n public mapErrorsToValidationRuleResult(): SFStateErrorObj {\n const fieldNames: string[] = Object.keys(this.state.errors);\n\n const sfStateErrorsObj = fieldNames.reduce((acc, fieldName) => {\n const errorCode = this.state.errors[fieldName];\n if (errorCode) {\n acc[fieldName] = {\n isValid: false,\n errorMessage: getErrorMessageFromCode(errorCode, SF_ErrorCodes), // this is the human-readable, untranslated, explanation of the error that will exist on the error object in card.state.errors\n // For v5 the object found in state.errors should also contain the additional properties that used to be sent to the onError callback\n // namely: translation, errorCode, a ref to rootNode &, in the case of failed binLookup, an array of the detectedBrands\n errorI18n: this.props.i18n.get(errorCode),\n error: errorCode,\n rootNode: this.rootNode,\n ...(this.state.detectedUnsupportedBrands && { detectedBrands: this.state.detectedUnsupportedBrands })\n };\n } else {\n acc[fieldName] = null;\n }\n return acc;\n }, {});\n return sfStateErrorsObj;\n }\n\n public processBinLookupResponse(binLookupResponse: BinLookupResponse, resetObject: SingleBrandResetObject): void {\n // If we were dealing with an unsupported card & now we have a valid /binLookup response (or a response triggering a reset of the UI),\n // - reset state to clear the error & the stored unsupportedBrands and, in the case of a valid /binLookup response, inform CSF (via handleUnsupportedCard)\n // (Scenario: from an unsupportedCard state the shopper has pasted another number long enough to trigger a /binLookup)\n if (this.state.detectedUnsupportedBrands) {\n this.setState(prevState => ({\n errors: { ...prevState.errors, [ENCRYPTED_CARD_NUMBER]: false },\n detectedUnsupportedBrands: null\n }));\n\n // If we have some sort of binLookupResponse object then this isn't the reset caused by digits dropping below a threshold\n // - so call handleUnsupportedCard to clear the error\n if (this.csf && binLookupResponse) {\n const errObj: CbObjOnError = {\n type: 'card',\n fieldType: 'encryptedCardNumber',\n error: ''\n };\n this.handleUnsupportedCard(errObj);\n }\n }\n\n this.issuingCountryCode = binLookupResponse?.issuingCountryCode?.toLowerCase();\n\n const hasBrandedResetObj = resetObject?.brand;\n\n /**\n * Are we dealing with a \"dedicated\" card scenario i.e a card component created as: checkout.create('bcmc') but which can accept multiple brands\n * - in which case we will need to reset brand and pass on the resetObj to CSF\n */\n const mustResetDedicatedBrand = hasBrandedResetObj && DEDICATED_CARD_COMPONENTS.includes(resetObject.brand);\n\n if (mustResetDedicatedBrand) {\n // resetObject.brand will be the value of the brand whose logo we want to reshow in the UI\n this.setState(resetObject, () => {\n this.props.onChange(this.state);\n });\n }\n\n /**\n * Scenarios:\n *\n * - RESET (binLookupResponse === null): The number of digits in number field has dropped below threshold for BIN lookup\n * - RESULT (binLookupResponse.supportedBrands.length === 1): binLookup has found a result so inform CSF\n *\n * In the RESET scenario, for \"dedicated\" card components we also need to pass on the resetObject since this contains information about\n * the brand that CSF needs to reset to, internally.\n */\n if (this.csf) this.csf.brandsFromBinLookup(binLookupResponse, mustResetDedicatedBrand ? resetObject : null);\n }\n\n private setRootNode = (input: HTMLElement): void => {\n this.rootNode = input;\n };\n\n public render(props, state) {\n return props.render({ setRootNode: this.setRootNode, setFocusOn: this.setFocusOn }, state);\n }\n}\n\nexport default SecuredFieldsProvider;\n"],"names":["SecuredFieldsProvider","Component","csfLoadFailTimeout","csfLoadFailTimeoutMS","csfConfigFailTimeout","csfConfigFailTimeoutMS","numCharsInField","rootNode","numDateFields","csf","handleOnLoad","handleOnConfigSuccess","handleOnFieldValid","handleOnAllValid","handleOnBrand","handleFocus","handleOnError","handleOnAutoComplete","handleOnNoDataRequired","handleOnTouchstartIOS","state","props","issuingCountryCode","constructor","super","stateObj","status","brand","type","errors","valid","data","cvcPolicy","CVC_POLICY_REQUIRED","expiryDatePolicy","DATE_POLICY_REQUIRED","isSfpValid","hasKoreanFields","this","handlers","bind","processBinLookupResponse","setFocusOn","updateStyles","handleUnsupportedCard","showValidation","destroy","static","defaultProps","componentDidMount","setRootNode","fields","getFields","reduce","validFieldsReducer","setState","forEach","field","filter","f","match","length","initializeCSF","componentDidUpdate","checkForKCPFields","componentWillUnmount","clearTimeout","root","loadingContext","csfSetupObj","clientKey","cardGroupTypes","brands","autoFocus","trimTrailingSeparator","keypadFix","showWarnings","iframeUIConfig","sfStyles","styles","i18n","callbacks","onLoad","onConfigSuccess","onFieldValid","onAllValid","onBrand","onError","onFocus","onBinValue","onAutoComplete","onAdditionalSFConfig","onAdditionalSFRemoved","onTouchstartIOS","isKCP","legacyInputMode","minimumExpiryDate","implementationType","forceCompat","maskSecurityCode","shouldDisableIOSArrowKeys","disableIOSArrowKeys","placeholders","showContextualElement","initCSF","setTimeout","AdyenCheckoutError","needsKoreanFields","koreanAuthenticationRequired","countryCode","setRemovedFieldState","prevState","ENCRYPTED_PWD_FIELD","undefined","onChange","removeSecuredField","setKCPStatus","setAddedFieldState","addSecuredField","getChildContext","errObj","hasUnsupportedCard","error","detectedUnsupportedBrands","detectedBrands","ENCRYPTED_CARD_NUMBER","frame","setFocusOnFrame","stylesObj","sfIsOptionalOrHidden","fieldType","Object","keys","getErrorReducer","errorObj","getErrorObject","isValidated","mapErrorsToValidationRuleResult","acc","fieldName","errorCode","isValid","errorMessage","getErrorMessageFromCode","SF_ErrorCodes","errorI18n","get","binLookupResponse","resetObject","toLowerCase","hasBrandedResetObj","mustResetDedicatedBrand","DEDICATED_CARD_COMPONENTS","includes","brandsFromBinLookup","input","render"],"mappings":"8pBA6BA,MAAMA,UAA8BC,EACxBC,mBACAC,qBACAC,qBACAC,uBACAC,gBACAC,SACAC,cACAC,IACAC,aACAC,sBACAC,mBACAC,iBACAC,cACAC,YACAC,cACAC,qBACAC,uBACAC,sBACDC,MACAC,MACCC,mBAERC,WAAAA,CAAYF,GACRG,MAAMH,GAEN,MAAMI,EAAqB,CACvBC,OAAQ,UACRC,MAAON,EAAMO,KACbC,OAAQ,CAAC,EACTC,MAAO,CAAC,EACRC,KAAM,C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C,GADJC,EACiB,CACbC,SAAS,EACTC,aAAcC,EAAwBH,EAAWI,GAGjDC,UAAW3G,KAAKjB,MAAM2D,KAAKkE,IAAIN,GAC/BlB,MAAOkB,EACPrI,SAAU+B,KAAK/B,YACX+B,KAAKlB,MAAMuG,2BAA6B,CAAEC,eAAgBtF,KAAKlB,MAAMuG,4BAG5D,KAEde,CAAAA,GACR,CAAC,EAER,CAEOjG,wBAAAA,CAAyB0G,EAAsCC,GAIlE,GAAI9G,KAAKlB,MAAMuG,4BACXrF,KAAKiB,UAASwD,IAAc,CACxBlF,OAAQ,IAAKkF,EAAUlF,OAAQgG,CAACA,IAAwB,GACxDF,0BAA2B,SAK3BrF,KAAK7B,KAAO0I,GAAmB,CAC/B,MAAM3B,EAAuB,CACzB5F,KAAM,OACNsG,UAAW,sBACXR,MAAO,IAEXpF,KAAKM,sBAAsB4E,EAC/B,CAGJlF,KAAKhB,mBAAqB6H,GAAmB7H,oBAAoB+H,cAEjE,MAAMC,EAAqBF,GAAazH,MAMlC4H,EAA0BD,GAAsBE,EAA0BC,SAASL,EAAYzH,OAEjG4H,GAEAjH,KAAKiB,SAAS6F,GAAa,KACvB9G,KAAKjB,MAAM6F,SAAS5E,KAAKlB,MAAK,IAalCkB,KAAK7B,KAAK6B,KAAK7B,IAAIiJ,oBAAoBP,EAAmBI,EAA0BH,EAAc,KAC1G,CAEQlG,YAAeyG,IACnBrH,KAAK/B,SAAWoJ,CAAAA,EAGbC,MAAAA,CAAOvI,EAAOD,GACjB,OAAOC,EAAMuI,OAAO,CAAE1G,YAAaZ,KAAKY,YAAaR,WAAYJ,KAAKI,YAActB,EACxF"}
|
|
1
|
+
{"version":3,"file":"SecuredFieldsProvider.js","sources":["../../../../../../src/components/internal/SecuredFields/SFP/SecuredFieldsProvider.ts"],"sourcesContent":["import { Component } from 'preact';\nimport { getErrorObject, getFields, getErrorReducer, validFieldsReducer } from './SFPUtils';\nimport initCSF from '../lib/CSF';\nimport handlers from './SecuredFieldsProviderHandlers';\nimport defaultProps from './defaultProps';\nimport { SFPProps, SFPState, SingleBrandResetObject } from './types';\nimport {\n StylesObject,\n CbObjOnError,\n CbObjOnFocus,\n CbObjOnBrand,\n CbObjOnAllValid,\n CbObjOnFieldValid,\n CbObjOnAutoComplete,\n CbObjOnConfigSuccess,\n CbObjOnLoad\n} from '../lib/types';\nimport { CSFReturnObject, CSFSetupObject } from '../lib/CSF/types';\nimport { CVC_POLICY_REQUIRED, DATE_POLICY_REQUIRED, DEDICATED_CARD_COMPONENTS, ENCRYPTED_CARD_NUMBER, ENCRYPTED_PWD_FIELD } from '../lib/constants';\nimport { BinLookupResponse } from '../../../Card/types';\nimport AdyenCheckoutError from '../../../../core/Errors/AdyenCheckoutError';\nimport { SFStateErrorObj } from '../../../Card/components/CardInput/types';\nimport { getErrorMessageFromCode } from '../../../../core/Errors/utils';\nimport { SF_ErrorCodes } from '../../../../core/Errors/constants';\n\n/**\n * SecuredFieldsProvider:\n * Initialises & handles the client-side part of SecuredFields\n */\nclass SecuredFieldsProvider extends Component<SFPProps, SFPState> {\n private csfLoadFailTimeout: number;\n private csfLoadFailTimeoutMS: number;\n private csfConfigFailTimeout: number;\n private csfConfigFailTimeoutMS: number;\n private numCharsInField: object;\n private rootNode;\n private numDateFields: number;\n private csf: CSFReturnObject;\n private handleOnLoad: (obj: CbObjOnLoad) => void;\n private handleOnConfigSuccess: (obj: CbObjOnConfigSuccess) => void;\n private handleOnFieldValid: (obj: CbObjOnFieldValid) => void;\n private handleOnAllValid: (obj: CbObjOnAllValid) => void;\n private handleOnBrand: (obj: CbObjOnBrand) => void;\n private handleFocus: (obj: CbObjOnFocus) => void;\n private handleOnError: (obj: CbObjOnError, hasUnsupportedCard?: boolean) => void;\n private handleOnAutoComplete: (obj: CbObjOnAutoComplete) => void;\n private handleOnNoDataRequired: () => void;\n private handleOnTouchstartIOS: (obj) => void;\n public state: SFPState;\n public props;\n private issuingCountryCode;\n\n constructor(props: SFPProps) {\n super(props);\n\n const stateObj: SFPState = {\n status: 'loading',\n brand: props.type,\n errors: {},\n valid: {},\n data: {},\n cvcPolicy: CVC_POLICY_REQUIRED,\n expiryDatePolicy: DATE_POLICY_REQUIRED,\n isSfpValid: false,\n hasKoreanFields: props.hasKoreanFields\n };\n this.state = stateObj;\n\n this.csfLoadFailTimeout = null;\n this.csfLoadFailTimeoutMS = 30000;\n\n this.csfConfigFailTimeout = null;\n this.csfConfigFailTimeoutMS = 15000;\n\n this.numCharsInField = {};\n\n // Handlers\n this.handleOnLoad = handlers.handleOnLoad.bind(this);\n this.handleOnConfigSuccess = handlers.handleOnConfigSuccess.bind(this);\n this.handleOnFieldValid = handlers.handleOnFieldValid.bind(this);\n this.handleOnAllValid = handlers.handleOnAllValid.bind(this);\n this.handleOnBrand = handlers.handleOnBrand.bind(this);\n this.handleFocus = handlers.handleFocus.bind(this);\n this.handleOnError = handlers.handleOnError.bind(this);\n this.handleOnNoDataRequired = handlers.handleOnNoDataRequired.bind(this);\n this.handleOnAutoComplete = handlers.handleOnAutoComplete.bind(this);\n this.handleOnTouchstartIOS = handlers.handleOnTouchstartIOS.bind(this); // Only called when iOS detected\n\n this.processBinLookupResponse = this.processBinLookupResponse.bind(this);\n\n // Bindings for functions exposed to users of this component: SecuredFields & CardInput\n this.setFocusOn = this.setFocusOn.bind(this);\n this.updateStyles = this.updateStyles.bind(this);\n this.handleUnsupportedCard = this.handleUnsupportedCard.bind(this);\n this.showValidation = this.showValidation.bind(this);\n this.destroy = this.destroy.bind(this);\n }\n\n public static defaultProps = defaultProps;\n\n public componentDidMount(): void {\n // When SFP instantiated through SecuredFieldsInput c.f. CardInput\n if (this.props.rootNode) {\n this.setRootNode(this.props.rootNode);\n }\n\n // Find encryptedFields and map them to the values we use to store valid states\n const fields = getFields(this.rootNode);\n const valid = fields.reduce(validFieldsReducer, {});\n\n this.setState({ valid });\n\n // Populate numCharsInField object\n fields.forEach(field => {\n this.numCharsInField[field] = 0;\n });\n\n // Store how many dateFields we are dealing with visually\n this.numDateFields = fields.filter(f => f.match(/Expiry/)).length;\n\n if (fields.length) {\n this.destroy(); // TODO test if this solves the React double render problem.\n this.initializeCSF(this.rootNode);\n } else {\n this.handleOnNoDataRequired();\n }\n }\n\n public componentDidUpdate() {\n this.checkForKCPFields();\n }\n\n public componentWillUnmount(): void {\n this.csf = null;\n clearTimeout(this.csfLoadFailTimeout);\n clearTimeout(this.csfConfigFailTimeout);\n }\n\n private initializeCSF(root: HTMLElement): void {\n let loadingContext = this.props.loadingContext;\n\n // For loading securedFields from local server during development\n if (process.env.NODE_ENV === 'development' && process.env.__SF_ENV__ !== 'build') {\n loadingContext = process.env.__SF_ENV__;\n }\n\n // TODO\n // if(!this.props.keypadFix){\n // send analytics action because to know if anyone *ever* sets this config prop\n // }\n\n const csfSetupObj: CSFSetupObject = {\n rootNode: root,\n type: this.props.type,\n clientKey: this.props.clientKey,\n cardGroupTypes: this.props.brands,\n autoFocus: this.props.autoFocus,\n trimTrailingSeparator: this.props.trimTrailingSeparator,\n loadingContext,\n keypadFix: this.props.keypadFix,\n showWarnings: this.props.showWarnings,\n iframeUIConfig: {\n sfStyles: this.props.styles\n },\n i18n: this.props.i18n,\n callbacks: {\n onLoad: this.handleOnLoad,\n onConfigSuccess: this.handleOnConfigSuccess,\n onFieldValid: this.handleOnFieldValid,\n onAllValid: this.handleOnAllValid,\n onBrand: this.handleOnBrand,\n onError: this.handleOnError,\n onFocus: this.handleFocus,\n onBinValue: this.props.onBinValue,\n onAutoComplete: this.handleOnAutoComplete,\n onAdditionalSFConfig: this.props.onAdditionalSFConfig,\n onAdditionalSFRemoved: this.props.onAdditionalSFRemoved,\n onTouchstartIOS: this.handleOnTouchstartIOS\n },\n isKCP: this.state.hasKoreanFields,\n legacyInputMode: this.props.legacyInputMode,\n minimumExpiryDate: this.props.minimumExpiryDate,\n implementationType: this.props.implementationType || 'components', // to distinguish between 'regular' and 'custom' card component\n forceCompat: this.props.forceCompat,\n maskSecurityCode: this.props.maskSecurityCode,\n exposeExpiryDate: this.props.exposeExpiryDate,\n shouldDisableIOSArrowKeys: !!this.props.disableIOSArrowKeys, // convert whether function has been defined into a boolean\n placeholders: this.props.placeholders ?? {},\n showContextualElement: this.props.showContextualElement\n };\n\n this.csf = initCSF(csfSetupObj);\n\n /**\n * Expect to at least have had the handleOnLoad callback called within this time\n * - if this hasn't happened then something has happened to interrupt the loading of the securedFields\n * So we need to clear the loading spinner to see if the securedFields are reporting anything\n */\n // @ts-ignore - timout 'type' is a number\n this.csfLoadFailTimeout = setTimeout(() => {\n if (this.state.status !== 'ready') {\n // Hide the spinner\n this.setState({ status: 'csfLoadFailure' });\n // Report the error\n this.props.onError(new AdyenCheckoutError('ERROR', 'secured field iframes have failed to load'));\n }\n }, this.csfLoadFailTimeoutMS);\n }\n\n private checkForKCPFields() {\n let needsKoreanFields = false;\n if (this.props.koreanAuthenticationRequired) {\n needsKoreanFields = this.issuingCountryCode ? this.issuingCountryCode === 'kr' : this.props.countryCode === 'kr';\n }\n\n // Was korean, now isn't - hide password field\n if (this.state.hasKoreanFields && !needsKoreanFields) {\n // Clear any stored data\n const setRemovedFieldState = prevState => ({\n data: { ...prevState.data, [ENCRYPTED_PWD_FIELD]: undefined },\n valid: { ...prevState.valid, [ENCRYPTED_PWD_FIELD]: false },\n errors: { ...prevState.errors, [ENCRYPTED_PWD_FIELD]: false },\n hasKoreanFields: false\n });\n\n this.setState(setRemovedFieldState, () => {\n this.props.onChange(this.state);\n });\n\n this.csf.removeSecuredField(ENCRYPTED_PWD_FIELD);\n this.csf.setKCPStatus(false);\n }\n\n // Wasn't korean, now is - show password field\n if (!this.state.hasKoreanFields && needsKoreanFields) {\n const setAddedFieldState = prevState => ({\n valid: { ...prevState.valid, [ENCRYPTED_PWD_FIELD]: false },\n hasKoreanFields: true,\n isSfpValid: false\n });\n\n this.setState(setAddedFieldState, () => {\n this.props.onChange(this.state);\n });\n\n this.csf.addSecuredField(ENCRYPTED_PWD_FIELD);\n this.csf.setKCPStatus(true);\n }\n }\n\n public getChildContext(): object {\n return { i18n: this.props.i18n };\n }\n\n public handleUnsupportedCard(errObj: CbObjOnError): boolean {\n const hasUnsupportedCard = !!errObj.error;\n\n // Store the brand(s) we detected and which we don't support\n if (hasUnsupportedCard) {\n this.setState({ detectedUnsupportedBrands: errObj.detectedBrands });\n }\n\n errObj.rootNode = this.rootNode; // Needed for CustomCard\n this.handleOnError(errObj, hasUnsupportedCard);\n // Inform CSF that the number field has an unsupportedCard error (or that it has been cleared)\n if (this.csf) {\n this.csf.hasUnsupportedCard(ENCRYPTED_CARD_NUMBER, errObj.error);\n }\n return hasUnsupportedCard;\n }\n\n public setFocusOn(frame: string): void {\n if (this.csf) this.csf.setFocusOnFrame(frame);\n }\n\n public updateStyles(stylesObj: StylesObject): void {\n if (this.csf) this.csf.updateStyles(stylesObj);\n }\n\n public sfIsOptionalOrHidden(fieldType: string): boolean {\n return this.csf.sfIsOptionalOrHidden(fieldType);\n }\n\n public destroy(): void {\n if (this.csf) this.csf.destroy();\n }\n\n public showValidation(): void {\n const { numDateFields, state }: SecuredFieldsProvider = this;\n\n Object.keys(state.valid)\n .reduce(getErrorReducer(numDateFields, state), [])\n .forEach(field => {\n // For each detected error pass an error object to the handler (calls error callback & sets state)\n const errorObj: CbObjOnError = getErrorObject(field, this.rootNode, state);\n this.handleOnError(errorObj, !!state.detectedUnsupportedBrands);\n // Inform the secured-fields instance of which fields have been found to have errors\n if (this.csf && this.csf.isValidated) {\n this.csf.isValidated(field, errorObj.error);\n }\n });\n }\n\n /**\n * Map SF errors to ValidationRuleResult-like objects, for CardInput component\n */\n public mapErrorsToValidationRuleResult(): SFStateErrorObj {\n const fieldNames: string[] = Object.keys(this.state.errors);\n\n const sfStateErrorsObj = fieldNames.reduce((acc, fieldName) => {\n const errorCode = this.state.errors[fieldName];\n if (errorCode) {\n acc[fieldName] = {\n isValid: false,\n errorMessage: getErrorMessageFromCode(errorCode, SF_ErrorCodes), // this is the human-readable, untranslated, explanation of the error that will exist on the error object in card.state.errors\n // For v5 the object found in state.errors should also contain the additional properties that used to be sent to the onError callback\n // namely: translation, errorCode, a ref to rootNode &, in the case of failed binLookup, an array of the detectedBrands\n errorI18n: this.props.i18n.get(errorCode),\n error: errorCode,\n rootNode: this.rootNode,\n ...(this.state.detectedUnsupportedBrands && { detectedBrands: this.state.detectedUnsupportedBrands })\n };\n } else {\n acc[fieldName] = null;\n }\n return acc;\n }, {});\n return sfStateErrorsObj;\n }\n\n public processBinLookupResponse(binLookupResponse: BinLookupResponse, resetObject: SingleBrandResetObject): void {\n // If we were dealing with an unsupported card & now we have a valid /binLookup response (or a response triggering a reset of the UI),\n // - reset state to clear the error & the stored unsupportedBrands and, in the case of a valid /binLookup response, inform CSF (via handleUnsupportedCard)\n // (Scenario: from an unsupportedCard state the shopper has pasted another number long enough to trigger a /binLookup)\n if (this.state.detectedUnsupportedBrands) {\n this.setState(prevState => ({\n errors: { ...prevState.errors, [ENCRYPTED_CARD_NUMBER]: false },\n detectedUnsupportedBrands: null\n }));\n\n // If we have some sort of binLookupResponse object then this isn't the reset caused by digits dropping below a threshold\n // - so call handleUnsupportedCard to clear the error\n if (this.csf && binLookupResponse) {\n const errObj: CbObjOnError = {\n type: 'card',\n fieldType: 'encryptedCardNumber',\n error: ''\n };\n this.handleUnsupportedCard(errObj);\n }\n }\n\n this.issuingCountryCode = binLookupResponse?.issuingCountryCode?.toLowerCase();\n\n const hasBrandedResetObj = resetObject?.brand;\n\n /**\n * Are we dealing with a \"dedicated\" card scenario i.e a card component created as: checkout.create('bcmc') but which can accept multiple brands\n * - in which case we will need to reset brand and pass on the resetObj to CSF\n */\n const mustResetDedicatedBrand = hasBrandedResetObj && DEDICATED_CARD_COMPONENTS.includes(resetObject.brand);\n\n if (mustResetDedicatedBrand) {\n // resetObject.brand will be the value of the brand whose logo we want to reshow in the UI\n this.setState(resetObject, () => {\n this.props.onChange(this.state);\n });\n }\n\n /**\n * Scenarios:\n *\n * - RESET (binLookupResponse === null): The number of digits in number field has dropped below threshold for BIN lookup\n * - RESULT (binLookupResponse.supportedBrands.length === 1): binLookup has found a result so inform CSF\n *\n * In the RESET scenario, for \"dedicated\" card components we also need to pass on the resetObject since this contains information about\n * the brand that CSF needs to reset to, internally.\n */\n if (this.csf) this.csf.brandsFromBinLookup(binLookupResponse, mustResetDedicatedBrand ? resetObject : null);\n }\n\n private setRootNode = (input: HTMLElement): void => {\n this.rootNode = input;\n };\n\n public render(props, state) {\n return props.render({ setRootNode: this.setRootNode, setFocusOn: this.setFocusOn }, state);\n }\n}\n\nexport default SecuredFieldsProvider;\n"],"names":["SecuredFieldsProvider","Component","csfLoadFailTimeout","csfLoadFailTimeoutMS","csfConfigFailTimeout","csfConfigFailTimeoutMS","numCharsInField","rootNode","numDateFields","csf","handleOnLoad","handleOnConfigSuccess","handleOnFieldValid","handleOnAllValid","handleOnBrand","handleFocus","handleOnError","handleOnAutoComplete","handleOnNoDataRequired","handleOnTouchstartIOS","state","props","issuingCountryCode","constructor","super","stateObj","status","brand","type","errors","valid","data","cvcPolicy","CVC_POLICY_REQUIRED","expiryDatePolicy","DATE_POLICY_REQUIRED","isSfpValid","hasKoreanFields","this","handlers","bind","processBinLookupResponse","setFocusOn","updateStyles","handleUnsupportedCard","showValidation","destroy","static","defaultProps","componentDidMount","setRootNode","fields","getFields","reduce","validFieldsReducer","setState","forEach","field","filter","f","match","length","initializeCSF","componentDidUpdate","checkForKCPFields","componentWillUnmount","clearTimeout","root","loadingContext","csfSetupObj","clientKey","cardGroupTypes","brands","autoFocus","trimTrailingSeparator","keypadFix","showWarnings","iframeUIConfig","sfStyles","styles","i18n","callbacks","onLoad","onConfigSuccess","onFieldValid","onAllValid","onBrand","onError","onFocus","onBinValue","onAutoComplete","onAdditionalSFConfig","onAdditionalSFRemoved","onTouchstartIOS","isKCP","legacyInputMode","minimumExpiryDate","implementationType","forceCompat","maskSecurityCode","exposeExpiryDate","shouldDisableIOSArrowKeys","disableIOSArrowKeys","placeholders","showContextualElement","initCSF","setTimeout","AdyenCheckoutError","needsKoreanFields","koreanAuthenticationRequired","countryCode","setRemovedFieldState","prevState","ENCRYPTED_PWD_FIELD","undefined","onChange","removeSecuredField","setKCPStatus","setAddedFieldState","addSecuredField","getChildContext","errObj","hasUnsupportedCard","error","detectedUnsupportedBrands","detectedBrands","ENCRYPTED_CARD_NUMBER","frame","setFocusOnFrame","stylesObj","sfIsOptionalOrHidden","fieldType","Object","keys","getErrorReducer","errorObj","getErrorObject","isValidated","mapErrorsToValidationRuleResult","acc","fieldName","errorCode","isValid","errorMessage","getErrorMessageFromCode","SF_ErrorCodes","errorI18n","get","binLookupResponse","resetObject","toLowerCase","hasBrandedResetObj","mustResetDedicatedBrand","DEDICATED_CARD_COMPONENTS","includes","brandsFromBinLookup","input","render"],"mappings":"8pBA6BA,MAAMA,UAA8BC,EACxBC,mBACAC,qBACAC,qBACAC,uBACAC,gBACAC,SACAC,cACAC,IACAC,aACAC,sBACAC,mBACAC,iBACAC,cACAC,YACAC,cACAC,qBACAC,uBACAC,sBACDC,MACAC,MACCC,mBAERC,WAAAA,CAAYF,GACRG,MAAMH,GAEN,MAAMI,EAAqB,CACvBC,OAAQ,UACRC,MAAON,EAAMO,KACbC,OAAQ,CAAC,EACTC,MAAO,CAAC,EACRC,KAAM,CAAC,EACPC,UAAWC,EACXC,iBAAkBC,EAClBC,YAAY,EACZC,gBAAiBhB,EAAMgB,iBAE3BC,KAAKlB,MAAQK,EAEba,KAAKpC,mBAAqB,KAC1BoC,KAAKnC,qBAAuB,IAE5BmC,KAAKlC,qBAAuB,KAC5BkC,KAAKjC,uBAAyB,KAE9BiC,KAAKhC,gBAAkB,GAGvBgC,KAAK5B,aAAe6B,EAAS7B,aAAa8B,KAAKF,MAC/CA,KAAK3B,sBAAwB4B,EAAS5B,sBAAsB6B,KAAKF,MACjEA,KAAK1B,mBAAqB2B,EAAS3B,mBAAmB4B,KAAKF,MAC3DA,KAAKzB,iBAAmB0B,EAAS1B,iBAAiB2B,KAAKF,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DF,0BAA2B,SAK3BtF,KAAK7B,KAAO2I,GAAmB,CAC/B,MAAM3B,EAAuB,CACzB7F,KAAM,OACNuG,UAAW,sBACXR,MAAO,IAEXrF,KAAKM,sBAAsB6E,EAC/B,CAGJnF,KAAKhB,mBAAqB8H,GAAmB9H,oBAAoBgI,cAEjE,MAAMC,EAAqBF,GAAa1H,MAMlC6H,EAA0BD,GAAsBE,EAA0BC,SAASL,EAAY1H,OAEjG6H,GAEAlH,KAAKiB,SAAS8F,GAAa,KACvB/G,KAAKjB,MAAM8F,SAAS7E,KAAKlB,MAAK,IAalCkB,KAAK7B,KAAK6B,KAAK7B,IAAIkJ,oBAAoBP,EAAmBI,EAA0BH,EAAc,KAC1G,CAEQnG,YAAe0G,IACnBtH,KAAK/B,SAAWqJ,CAAAA,EAGbC,MAAAA,CAAOxI,EAAOD,GACjB,OAAOC,EAAMwI,OAAO,CAAE3G,YAAaZ,KAAKY,YAAaR,WAAYJ,KAAKI,YAActB,EACxF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{select as e,getAttribute as t}from"../../utilities/dom.js";import{DATA_ENCRYPTED_FIELD_ATTR as i,CVC_POLICY_REQUIRED as s,DATE_POLICY_REQUIRED as o,ENCRYPTED_EXPIRY_YEAR as n,SF_CONFIG_TIMEOUT as r,ALL_SECURED_FIELDS as a,DATA_INFO as d,DATA_UID as l}from"../../constants.js";import{existy as c}from"../../utilities/commonUtils.js";import h from"../utils/cardType.js";import u from"../../securedField/SecuredField.js";import p from"../../../../../../core/Errors/AdyenCheckoutError.js";function f(){this.encryptedAttrName=i;const n=e(this.props.rootNode,`[${this.encryptedAttrName}]`).filter((e=>{const i=t(e,this.encryptedAttrName),s=a.includes(i);return s||console.warn(`WARNING: '${i}' is not a valid type for the '${this.encryptedAttrName}' attribute. A SecuredField will not be created for this element.`),s})),r=s,d=o;return this.config.isCreditCardType?(this.isSingleBrandedCard=!1,this.securityCode="",this.createCardSecuredFields(n,r,d),n.length):(this.createNonCardSecuredFields(n),n.length)}async function m(e){for(let t=0;t<e.length;t++){const i=e[t];await this.setupSecuredField(i).catch((e=>{window._b$dl&&console.log("Secured fields setup failure. e=",e)}))}}async function y(e,t,i){let n=this.state.type;if("card"===n&&1===this.config.cardGroupTypes.length&&(n=this.config.cardGroupTypes[0],this.state.type=n),this.isSingleBrandedCard="card"!==n,this.isSingleBrandedCard){const e=h.getCardByBrand(n);c(e)?(t=e.cvcPolicy||s,i=e.expiryDatePolicy||o,this.securityCode=e.securityCode):this.state.type="unrecognised-single-brand"}for(let s=0;s<e.length;s++){const o=e[s];window._b$dl&&console.log("\nAbout to set up securedField:",o),await this.setupSecuredField(o,t,i).catch((e=>{window._b$dl&&console.log("Secured fields setup failure. e=",e)})),window._b$dl&&console.log("Finished setting up securedField:",o)}if(window._b$dl&&console.log("Finished setting up all securedFields"),this.isSingleBrandedCard){const e={type:this.state.type,rootNode:this.props.rootNode,brand:n,cvcPolicy:t,expiryDatePolicy:i,cvcText:this.securityCode};setTimeout((()=>{this.callbacks.onBrand(e)}),0)}}function g(e,i,s){return new Promise(((o,a)=>{const c=t(e,this.encryptedAttrName);c===n&&(this.state.hasSeparateDateFields=!0);const h={fieldType:c,extraFieldData:t(e,d),uid:t(e,l),cvcPolicy:i,holderEl:e,expiryDatePolicy:s,txVariant:this.state.type,cardGroupTypes:this.config.cardGroupTypes,iframeUIConfig:this.config.iframeUIConfig,sfLogAtStart:this.config.sfLogAtStart,trimTrailingSeparator:this.config.trimTrailingSeparator,isCreditCardType:this.config.isCreditCardType,iframeSrc:this.config.iframeSrc,loadingContext:this.config.loadingContext,showWarnings:this.config.showWarnings,legacyInputMode:this.config.legacyInputMode,minimumExpiryDate:this.config.minimumExpiryDate,maskSecurityCode:this.props.maskSecurityCode,disableIOSArrowKeys:this.props.shouldDisableIOSArrowKeys,implementationType:this.props.implementationType,showContextualElement:this.props.showContextualElement,placeholders:this.props.placeholders},f=new u(h,this.props.i18n).onIframeLoaded((()=>{if(this.state.iframeCount+=1,window._b$dl&&console.log("### createSecuredFields::onIframeLoaded:: this.state.iframeCount=",this.state.iframeCount),this.state.iframeCount>this.state.numIframes)throw this.destroySecuredFields(),new p("ERROR",`One or more securedFields has just loaded new content. This should never happen. securedFields have been removed.\n iframe load count=${this.state.iframeCount}. Expected count:${this.state.numIframes}`);if(f.loadToConfigTimeout=setTimeout((()=>{a({type:h.fieldType,failReason:"sf took too long to config"})}),r),this.state.iframeCount===this.state.originalNumIframes){const e={iframesLoaded:!0};this.callbacks.onLoad(e)}})).onConfig((e=>{this.handleIframeConfigFeedback(e),clearTimeout(f.loadToConfigTimeout),f.loadToConfigTimeout=null,o(e)})).onFocus((e=>{this.handleFocus(e)})).onBinValue((e=>{this.handleBinValue(e)})).onTouchstart((e=>{this.props.shouldDisableIOSArrowKeys&&(this.hasGenuineTouchEvents||e.hasGenuineTouchEvents)&&this.callbacks.onTouchstartIOS({fieldType:e.fieldType}),(e.hasGenuineTouchEvents||this.hasGenuineTouchEvents)&&this.postMessageToAllIframes({fieldType:e.fieldType,fieldClick:!0})})).onShiftTab((e=>{this.handleSFShiftTab(e.fieldType)})).onEncryption((e=>{this.handleEncryption(e)})).onValidation((e=>{this.handleValidation(e)})).onAutoComplete((e=>{this.processAutoComplete(e)}));this.state.securedFields[c]=f}))}export{y as createCardSecuredFields,m as createNonCardSecuredFields,f as createSecuredFields,g as setupSecuredField};
|
|
1
|
+
import{select as e,getAttribute as t}from"../../utilities/dom.js";import{DATA_ENCRYPTED_FIELD_ATTR as i,CVC_POLICY_REQUIRED as s,DATE_POLICY_REQUIRED as o,ENCRYPTED_EXPIRY_YEAR as n,SF_CONFIG_TIMEOUT as r,ALL_SECURED_FIELDS as a,DATA_INFO as d,DATA_UID as l}from"../../constants.js";import{existy as c}from"../../utilities/commonUtils.js";import h from"../utils/cardType.js";import u from"../../securedField/SecuredField.js";import p from"../../../../../../core/Errors/AdyenCheckoutError.js";function f(){this.encryptedAttrName=i;const n=e(this.props.rootNode,`[${this.encryptedAttrName}]`).filter((e=>{const i=t(e,this.encryptedAttrName),s=a.includes(i);return s||console.warn(`WARNING: '${i}' is not a valid type for the '${this.encryptedAttrName}' attribute. A SecuredField will not be created for this element.`),s})),r=s,d=o;return this.config.isCreditCardType?(this.isSingleBrandedCard=!1,this.securityCode="",this.createCardSecuredFields(n,r,d),n.length):(this.createNonCardSecuredFields(n),n.length)}async function m(e){for(let t=0;t<e.length;t++){const i=e[t];await this.setupSecuredField(i).catch((e=>{window._b$dl&&console.log("Secured fields setup failure. e=",e)}))}}async function y(e,t,i){let n=this.state.type;if("card"===n&&1===this.config.cardGroupTypes.length&&(n=this.config.cardGroupTypes[0],this.state.type=n),this.isSingleBrandedCard="card"!==n,this.isSingleBrandedCard){const e=h.getCardByBrand(n);c(e)?(t=e.cvcPolicy||s,i=e.expiryDatePolicy||o,this.securityCode=e.securityCode):this.state.type="unrecognised-single-brand"}for(let s=0;s<e.length;s++){const o=e[s];window._b$dl&&console.log("\nAbout to set up securedField:",o),await this.setupSecuredField(o,t,i).catch((e=>{window._b$dl&&console.log("Secured fields setup failure. e=",e)})),window._b$dl&&console.log("Finished setting up securedField:",o)}if(window._b$dl&&console.log("Finished setting up all securedFields"),this.isSingleBrandedCard){const e={type:this.state.type,rootNode:this.props.rootNode,brand:n,cvcPolicy:t,expiryDatePolicy:i,cvcText:this.securityCode};setTimeout((()=>{this.callbacks.onBrand(e)}),0)}}function g(e,i,s){return new Promise(((o,a)=>{const c=t(e,this.encryptedAttrName);c===n&&(this.state.hasSeparateDateFields=!0);const h={fieldType:c,extraFieldData:t(e,d),uid:t(e,l),cvcPolicy:i,holderEl:e,expiryDatePolicy:s,txVariant:this.state.type,cardGroupTypes:this.config.cardGroupTypes,iframeUIConfig:this.config.iframeUIConfig,sfLogAtStart:this.config.sfLogAtStart,trimTrailingSeparator:this.config.trimTrailingSeparator,isCreditCardType:this.config.isCreditCardType,iframeSrc:this.config.iframeSrc,loadingContext:this.config.loadingContext,showWarnings:this.config.showWarnings,legacyInputMode:this.config.legacyInputMode,minimumExpiryDate:this.config.minimumExpiryDate,maskSecurityCode:this.props.maskSecurityCode,exposeExpiryDate:this.props.exposeExpiryDate,disableIOSArrowKeys:this.props.shouldDisableIOSArrowKeys,implementationType:this.props.implementationType,showContextualElement:this.props.showContextualElement,placeholders:this.props.placeholders},f=new u(h,this.props.i18n).onIframeLoaded((()=>{if(this.state.iframeCount+=1,window._b$dl&&console.log("### createSecuredFields::onIframeLoaded:: this.state.iframeCount=",this.state.iframeCount),this.state.iframeCount>this.state.numIframes)throw this.destroySecuredFields(),new p("ERROR",`One or more securedFields has just loaded new content. This should never happen. securedFields have been removed.\n iframe load count=${this.state.iframeCount}. Expected count:${this.state.numIframes}`);if(f.loadToConfigTimeout=setTimeout((()=>{a({type:h.fieldType,failReason:"sf took too long to config"})}),r),this.state.iframeCount===this.state.originalNumIframes){const e={iframesLoaded:!0};this.callbacks.onLoad(e)}})).onConfig((e=>{this.handleIframeConfigFeedback(e),clearTimeout(f.loadToConfigTimeout),f.loadToConfigTimeout=null,o(e)})).onFocus((e=>{this.handleFocus(e)})).onBinValue((e=>{this.handleBinValue(e)})).onTouchstart((e=>{this.props.shouldDisableIOSArrowKeys&&(this.hasGenuineTouchEvents||e.hasGenuineTouchEvents)&&this.callbacks.onTouchstartIOS({fieldType:e.fieldType}),(e.hasGenuineTouchEvents||this.hasGenuineTouchEvents)&&this.postMessageToAllIframes({fieldType:e.fieldType,fieldClick:!0})})).onShiftTab((e=>{this.handleSFShiftTab(e.fieldType)})).onEncryption((e=>{this.handleEncryption(e)})).onValidation((e=>{this.handleValidation(e)})).onAutoComplete((e=>{this.processAutoComplete(e)}));this.state.securedFields[c]=f}))}export{y as createCardSecuredFields,m as createNonCardSecuredFields,f as createSecuredFields,g as setupSecuredField};
|
|
2
2
|
//# sourceMappingURL=createSecuredFields.js.map
|