@adyen/adyen-web 6.19.0 → 6.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/adyen.css +5 -5
  3. package/dist/cjs/adyen.css.map +1 -1
  4. package/dist/cjs/index.cjs +1 -1
  5. package/dist/cjs/index.cjs.map +1 -1
  6. package/dist/cjs/index.d.cts +29 -62
  7. package/dist/es/adyen.css +5 -5
  8. package/dist/es/adyen.css.map +1 -1
  9. package/dist/es/components/Ach/components/useSRPanelForACHErrors.js.map +1 -1
  10. package/dist/es/components/Card/components/CardInput/components/Installments/Installments.js +1 -1
  11. package/dist/es/components/Card/components/CardInput/components/Installments/Installments.js.map +1 -1
  12. package/dist/es/components/Card/components/CardInput/handlers.js.map +1 -1
  13. package/dist/es/components/Card/components/CardInput/useSRPanelForCardInputErrors.js.map +1 -1
  14. package/dist/es/components/Dropin/Dropin.js +1 -1
  15. package/dist/es/components/Dropin/Dropin.js.map +1 -1
  16. package/dist/es/components/Giftcard/components/useSRPanelForGiftcardErrors.js.map +1 -1
  17. package/dist/es/components/PayPal/utils/get-paypal-styles.js.map +1 -1
  18. package/dist/es/components/PayPalFastlane/FastlaneSDK.js.map +1 -1
  19. package/dist/es/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.js.map +1 -1
  20. package/dist/es/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.js.map +1 -1
  21. package/dist/es/components/UPI/UPI.js +1 -1
  22. package/dist/es/components/UPI/UPI.js.map +1 -1
  23. package/dist/es/components/UPI/components/UPIComponent/UPIComponent.js +1 -1
  24. package/dist/es/components/UPI/components/UPIComponent/UPIComponent.js.map +1 -1
  25. package/dist/es/components/UPI/components/UPIIntentAppList/UPIIntentAppItem/UPIIntentAppItem.js +1 -1
  26. package/dist/es/components/UPI/components/UPIIntentAppList/UPIIntentAppItem/UPIIntentAppItem.js.map +1 -1
  27. package/dist/es/components/UPI/components/UPIIntentAppList/UPIIntentAppList.js +1 -1
  28. package/dist/es/components/UPI/components/UPIIntentAppList/UPIIntentAppList.js.map +1 -1
  29. package/dist/es/components/UPI/constants.js +2 -0
  30. package/dist/es/components/UPI/constants.js.map +1 -0
  31. package/dist/es/components/internal/Address/Address.js.map +1 -1
  32. package/dist/es/components/internal/Alert/Alert.js +1 -1
  33. package/dist/es/components/internal/Alert/Alert.js.map +1 -1
  34. package/dist/es/components/internal/ClickToPay/models/ShopperCard.js +1 -1
  35. package/dist/es/components/internal/ClickToPay/models/ShopperCard.js.map +1 -1
  36. package/dist/es/components/internal/IbanInput/IbanInput.js.map +1 -1
  37. package/dist/es/components/internal/OpenInvoice/useSRPanelForOpenInvoiceErrors.js.map +1 -1
  38. package/dist/es/components/internal/SecuredFields/SFP/SecuredFieldsProvider.js.map +1 -1
  39. package/dist/es/components/internal/SecuredFields/binLookup/extensions.js.map +1 -1
  40. package/dist/es/components/internal/SecuredFields/binLookup/triggerBinLookUp.js.map +1 -1
  41. package/dist/es/components/internal/SecuredFields/lib/CSF/extensions/handleIOSTouchEvents.js.map +1 -1
  42. package/dist/es/components/internal/SegmentedControl/SegmentedControl.js.map +1 -1
  43. package/dist/es/components/internal/UIElement/UIElement.js +1 -1
  44. package/dist/es/components/internal/UIElement/UIElement.js.map +1 -1
  45. package/dist/es/components/internal/UIElement/utils.js.map +1 -1
  46. package/dist/es/core/Analytics/utils.js.map +1 -1
  47. package/dist/es/core/Errors/SRPanel.js.map +1 -1
  48. package/dist/es/core/Errors/utils.js.map +1 -1
  49. package/dist/es/core/Services/analytics/collect-id.js +1 -1
  50. package/dist/es/core/core.js +1 -1
  51. package/dist/es/core/core.registry.js.map +1 -1
  52. package/dist/es/core/utils.js.map +1 -1
  53. package/dist/es/external/preact/compat/dist/compat.js.map +1 -1
  54. package/dist/es/external/preact/dist/preact.js.map +1 -1
  55. package/dist/es/index.d.ts +29 -62
  56. package/dist/es/language/utils.js.map +1 -1
  57. package/dist/es/utils/clipboard.js.map +1 -1
  58. package/dist/es/utils/setFocus.js.map +1 -1
  59. package/dist/es/utils/useForm/reducer.js.map +1 -1
  60. package/dist/es-legacy/adyen.css +5 -5
  61. package/dist/es-legacy/adyen.css.map +1 -1
  62. package/dist/es-legacy/components/Ach/components/useSRPanelForACHErrors.js.map +1 -1
  63. package/dist/es-legacy/components/Card/components/CardInput/components/Installments/Installments.js +1 -1
  64. package/dist/es-legacy/components/Card/components/CardInput/components/Installments/Installments.js.map +1 -1
  65. package/dist/es-legacy/components/Card/components/CardInput/handlers.js.map +1 -1
  66. package/dist/es-legacy/components/Card/components/CardInput/useSRPanelForCardInputErrors.js.map +1 -1
  67. package/dist/es-legacy/components/Dropin/Dropin.js +1 -1
  68. package/dist/es-legacy/components/Dropin/Dropin.js.map +1 -1
  69. package/dist/es-legacy/components/Giftcard/components/useSRPanelForGiftcardErrors.js.map +1 -1
  70. package/dist/es-legacy/components/PayPal/utils/get-paypal-styles.js.map +1 -1
  71. package/dist/es-legacy/components/PayPalFastlane/FastlaneSDK.js.map +1 -1
  72. package/dist/es-legacy/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.js.map +1 -1
  73. package/dist/es-legacy/components/ThreeDS2/components/DeviceFingerprint/PrepareFingerprint3DS2.js.map +1 -1
  74. package/dist/es-legacy/components/UPI/UPI.js +1 -1
  75. package/dist/es-legacy/components/UPI/UPI.js.map +1 -1
  76. package/dist/es-legacy/components/UPI/components/UPIComponent/UPIComponent.js +1 -1
  77. package/dist/es-legacy/components/UPI/components/UPIComponent/UPIComponent.js.map +1 -1
  78. package/dist/es-legacy/components/UPI/components/UPIIntentAppList/UPIIntentAppItem/UPIIntentAppItem.js +1 -1
  79. package/dist/es-legacy/components/UPI/components/UPIIntentAppList/UPIIntentAppItem/UPIIntentAppItem.js.map +1 -1
  80. package/dist/es-legacy/components/UPI/components/UPIIntentAppList/UPIIntentAppList.js +1 -1
  81. package/dist/es-legacy/components/UPI/components/UPIIntentAppList/UPIIntentAppList.js.map +1 -1
  82. package/dist/es-legacy/components/UPI/constants.js +2 -0
  83. package/dist/es-legacy/components/UPI/constants.js.map +1 -0
  84. package/dist/es-legacy/components/internal/Address/Address.js.map +1 -1
  85. package/dist/es-legacy/components/internal/Alert/Alert.js +1 -1
  86. package/dist/es-legacy/components/internal/Alert/Alert.js.map +1 -1
  87. package/dist/es-legacy/components/internal/ClickToPay/models/ShopperCard.js +1 -1
  88. package/dist/es-legacy/components/internal/ClickToPay/models/ShopperCard.js.map +1 -1
  89. package/dist/es-legacy/components/internal/IbanInput/IbanInput.js.map +1 -1
  90. package/dist/es-legacy/components/internal/OpenInvoice/useSRPanelForOpenInvoiceErrors.js.map +1 -1
  91. package/dist/es-legacy/components/internal/SecuredFields/SFP/SecuredFieldsProvider.js.map +1 -1
  92. package/dist/es-legacy/components/internal/SecuredFields/binLookup/extensions.js.map +1 -1
  93. package/dist/es-legacy/components/internal/SecuredFields/binLookup/triggerBinLookUp.js.map +1 -1
  94. package/dist/es-legacy/components/internal/SecuredFields/lib/CSF/extensions/handleIOSTouchEvents.js.map +1 -1
  95. package/dist/es-legacy/components/internal/SegmentedControl/SegmentedControl.js.map +1 -1
  96. package/dist/es-legacy/components/internal/UIElement/UIElement.js +1 -1
  97. package/dist/es-legacy/components/internal/UIElement/UIElement.js.map +1 -1
  98. package/dist/es-legacy/components/internal/UIElement/utils.js.map +1 -1
  99. package/dist/es-legacy/core/Analytics/utils.js.map +1 -1
  100. package/dist/es-legacy/core/Errors/SRPanel.js.map +1 -1
  101. package/dist/es-legacy/core/Errors/utils.js.map +1 -1
  102. package/dist/es-legacy/core/Services/analytics/collect-id.js +1 -1
  103. package/dist/es-legacy/core/core.js +1 -1
  104. package/dist/es-legacy/core/core.registry.js.map +1 -1
  105. package/dist/es-legacy/core/utils.js.map +1 -1
  106. package/dist/es-legacy/external/preact/compat/dist/compat.js.map +1 -1
  107. package/dist/es-legacy/external/preact/dist/preact.js.map +1 -1
  108. package/dist/es-legacy/language/utils.js.map +1 -1
  109. package/dist/es-legacy/utils/clipboard.js.map +1 -1
  110. package/dist/es-legacy/utils/setFocus.js.map +1 -1
  111. package/dist/es-legacy/utils/useForm/reducer.js.map +1 -1
  112. package/package.json +159 -159
  113. package/styles/adyen.css +5 -5
  114. package/dist/es/components/UPI/components/UPIComponent/constants.js +0 -2
  115. package/dist/es/components/UPI/components/UPIComponent/constants.js.map +0 -1
  116. package/dist/es/components/UPI/components/UPIComponent/useUpiSegmentedControlOptions.js +0 -2
  117. package/dist/es/components/UPI/components/UPIComponent/useUpiSegmentedControlOptions.js.map +0 -1
  118. package/dist/es-legacy/components/UPI/components/UPIComponent/constants.js +0 -2
  119. package/dist/es-legacy/components/UPI/components/UPIComponent/constants.js.map +0 -1
  120. package/dist/es-legacy/components/UPI/components/UPIComponent/useUpiSegmentedControlOptions.js +0 -2
  121. package/dist/es-legacy/components/UPI/components/UPIComponent/useUpiSegmentedControlOptions.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"useSRPanelForACHErrors.js","sources":["../../../../../src/components/Ach/components/useSRPanelForACHErrors.ts"],"sourcesContent":["import { useEffect, useState, MutableRef } from 'preact/hooks';\nimport { SetSRMessagesReturnObject } from '../../../core/Errors/types';\nimport useSRPanelContext from '../../../core/Errors/useSRPanelContext';\nimport { SetSRMessagesReturnFn } from '../../../core/Errors/SRPanelProvider';\nimport { usePrevious } from '../../../utils/hookUtils';\nimport { ERROR_ACTION_BLUR_SCENARIO, ERROR_ACTION_FOCUS_FIELD } from '../../../core/Errors/constants';\nimport { setFocusOnField } from '../../../utils/setFocus';\nimport { getArrayDifferences } from '../../../utils/arrayUtils';\nimport { ValidationRuleResult } from '../../../utils/Validator/ValidationRuleResult';\n\nexport interface AchStateErrors {\n selectedAccountType: ValidationRuleResult;\n ownerName: ValidationRuleResult;\n routingNumber: ValidationRuleResult;\n accountNumber: ValidationRuleResult;\n accountNumberVerification: ValidationRuleResult;\n}\n\ninterface UseSRPanelForErrorsProps {\n errors: AchStateErrors;\n data: AchStateData;\n isValidating: MutableRef<boolean>;\n}\n\ninterface AchStateData {\n selectedAccountType: string;\n ownerName: string;\n routingNumber: string;\n accountNumber: string;\n accountNumberVerification: string;\n}\n\nconst useSRPanelForACHErrors = ({ errors, data, isValidating }: UseSRPanelForErrorsProps) => {\n // Relates to onBlur errors\n const [sortedErrorList, setSortedErrorList] = useState(null);\n // Get the previous value (Relates to onBlur errors)\n const previousSortedErrors = usePrevious(sortedErrorList);\n const { setSRMessagesFromObjects, setSRMessagesFromStrings, clearSRPanel, shouldMoveFocusSR } = useSRPanelContext();\n const setSRMessages: SetSRMessagesReturnFn = setSRMessagesFromObjects?.({});\n\n // Fixed layout for the ACH comp\n const layout = ['selectedAccountType', 'ownerName', 'routingNumber', 'accountNumber', 'accountNumberVerification'];\n\n useEffect(() => {\n try {\n const srPanelResp: SetSRMessagesReturnObject = setSRMessages?.({ errors, isValidating: isValidating.current, layout });\n\n // Relates to onBlur errors\n const currentErrorsSortedByLayout = srPanelResp?.currentErrorsSortedByLayout;\n // Store the array of sorted error objects separately so that we can use it to make comparisons between the old and new arrays\n setSortedErrorList(currentErrorsSortedByLayout);\n\n /**\n * Need extra actions after setting SRPanel messages in order to focus field (if required) and because we have some errors that are fired onBlur\n */\n switch (srPanelResp?.action) {\n // A call to focus the first field in error will always follow the call to validate the whole form\n case ERROR_ACTION_FOCUS_FIELD:\n // Focus field in error, if required\n if (shouldMoveFocusSR) setFocusOnField('.adyen-checkout__ach', srPanelResp.fieldToFocus);\n // Remove 'showValidation' mode - allowing time for collation of all the fields in error whilst it is 'showValidation' mode (some errors come in a second render pass)\n setTimeout(() => {\n isValidating.current = false;\n }, 300);\n break;\n\n /**\n * Relates to errors triggered by a field blurring (some pm forms have this, some don't) - check if there is an error to either set or to clear\n */\n case ERROR_ACTION_BLUR_SCENARIO: {\n const difference = getArrayDifferences(currentErrorsSortedByLayout, previousSortedErrors, 'field');\n\n const latestErrorMsg = difference?.[0];\n\n if (latestErrorMsg) {\n // Is error actually a blur based one - depends on the specific fields in a component as to whether they validate on blur\n // In the case of the ACH form currently all the fields validate on blur\n const isBlurBasedError = true;\n\n // Only add blur based errors to the error panel - doing this step prevents the non-blur based errors from being read out twice\n const latestSRError = isBlurBasedError ? latestErrorMsg.errorMessage : null;\n setSRMessagesFromStrings(latestSRError);\n } else {\n // called when previousSortedErrors.length >= currentErrorsSortedByLayout.length\n clearSRPanel();\n }\n break;\n }\n default:\n break;\n }\n } catch (_) {\n // We don't handle the error related to the sr panel, let it fail silently.\n }\n }, [errors, data]);\n};\n\nexport default useSRPanelForACHErrors;\n"],"names":["useSRPanelForACHErrors","errors","data","isValidating","sortedErrorList","setSortedErrorList","useState","previousSortedErrors","usePrevious","setSRMessagesFromObjects","setSRMessagesFromStrings","clearSRPanel","shouldMoveFocusSR","useSRPanelContext","setSRMessages","layout","useEffect","srPanelResp","current","currentErrorsSortedByLayout","action","ERROR_ACTION_FOCUS_FIELD","setFocusOnField","fieldToFocus","setTimeout","ERROR_ACTION_BLUR_SCENARIO","difference","getArrayDifferences","latestErrorMsg","latestSRError","errorMessage","_"],"mappings":"ubAgCA,MAAMA,EAAyB,EAAGC,SAAQC,OAAMC,mBAE5C,MAAOC,EAAiBC,GAAsBC,EAAS,MAEjDC,EAAuBC,EAAYJ,IACnCK,yBAAEA,EAAwBC,yBAAEA,EAAwBC,aAAEA,EAAYC,kBAAEA,GAAsBC,IAC1FC,EAAuCL,IAA2B,IAGlEM,EAAS,CAAC,sBAAuB,YAAa,gBAAiB,gBAAiB,6BAEtFC,EAAU,KACN,IACI,MAAMC,EAAyCH,IAAgB,CAAEb,SAAQE,aAAcA,EAAae,QAASH,WAGvGI,EAA8BF,GAAaE,4BAOjD,OALAd,EAAmBc,GAKXF,GAAaG,QAEjB,KAAKC,EAEGT,GAAmBU,EAAgB,uBAAwBL,EAAYM,cAE3EC,WAAW,KACPrB,EAAae,SAAU,GACxB,KACH,MAKJ,KAAKO,EAA4B,CAC7B,MAAMC,EAAaC,EAAoBR,EAA6BZ,EAAsB,SAEpFqB,EAAiBF,IAAa,GAEpC,GAAIE,EAAgB,CAGhB,MAGMC,GAHmB,EAGgBD,EAAeE,aAAe,KACvEpB,EAAyBmB,QAGzBlB,IAEJ,KACJ,EAIR,CAAE,MAAOoB,GAET,GACD,CAAC9B,EAAQC"}
1
+ {"version":3,"file":"useSRPanelForACHErrors.js","sources":["../../../../../src/components/Ach/components/useSRPanelForACHErrors.ts"],"sourcesContent":["import { useEffect, useState, MutableRef } from 'preact/hooks';\nimport { SetSRMessagesReturnObject } from '../../../core/Errors/types';\nimport useSRPanelContext from '../../../core/Errors/useSRPanelContext';\nimport { SetSRMessagesReturnFn } from '../../../core/Errors/SRPanelProvider';\nimport { usePrevious } from '../../../utils/hookUtils';\nimport { ERROR_ACTION_BLUR_SCENARIO, ERROR_ACTION_FOCUS_FIELD } from '../../../core/Errors/constants';\nimport { setFocusOnField } from '../../../utils/setFocus';\nimport { getArrayDifferences } from '../../../utils/arrayUtils';\nimport { ValidationRuleResult } from '../../../utils/Validator/ValidationRuleResult';\n\nexport interface AchStateErrors {\n selectedAccountType: ValidationRuleResult;\n ownerName: ValidationRuleResult;\n routingNumber: ValidationRuleResult;\n accountNumber: ValidationRuleResult;\n accountNumberVerification: ValidationRuleResult;\n}\n\ninterface UseSRPanelForErrorsProps {\n errors: AchStateErrors;\n data: AchStateData;\n isValidating: MutableRef<boolean>;\n}\n\ninterface AchStateData {\n selectedAccountType: string;\n ownerName: string;\n routingNumber: string;\n accountNumber: string;\n accountNumberVerification: string;\n}\n\nconst useSRPanelForACHErrors = ({ errors, data, isValidating }: UseSRPanelForErrorsProps) => {\n // Relates to onBlur errors\n const [sortedErrorList, setSortedErrorList] = useState(null);\n // Get the previous value (Relates to onBlur errors)\n const previousSortedErrors = usePrevious(sortedErrorList);\n const { setSRMessagesFromObjects, setSRMessagesFromStrings, clearSRPanel, shouldMoveFocusSR } = useSRPanelContext();\n const setSRMessages: SetSRMessagesReturnFn = setSRMessagesFromObjects?.({});\n\n // Fixed layout for the ACH comp\n const layout = ['selectedAccountType', 'ownerName', 'routingNumber', 'accountNumber', 'accountNumberVerification'];\n\n useEffect(() => {\n try {\n const srPanelResp: SetSRMessagesReturnObject = setSRMessages?.({ errors, isValidating: isValidating.current, layout });\n\n // Relates to onBlur errors\n const currentErrorsSortedByLayout = srPanelResp?.currentErrorsSortedByLayout;\n // Store the array of sorted error objects separately so that we can use it to make comparisons between the old and new arrays\n setSortedErrorList(currentErrorsSortedByLayout);\n\n /**\n * Need extra actions after setting SRPanel messages in order to focus field (if required) and because we have some errors that are fired onBlur\n */\n switch (srPanelResp?.action) {\n // A call to focus the first field in error will always follow the call to validate the whole form\n case ERROR_ACTION_FOCUS_FIELD:\n // Focus field in error, if required\n if (shouldMoveFocusSR) setFocusOnField('.adyen-checkout__ach', srPanelResp.fieldToFocus);\n // Remove 'showValidation' mode - allowing time for collation of all the fields in error whilst it is 'showValidation' mode (some errors come in a second render pass)\n setTimeout(() => {\n isValidating.current = false;\n }, 300);\n break;\n\n /**\n * Relates to errors triggered by a field blurring (some pm forms have this, some don't) - check if there is an error to either set or to clear\n */\n case ERROR_ACTION_BLUR_SCENARIO: {\n const difference = getArrayDifferences(currentErrorsSortedByLayout, previousSortedErrors, 'field');\n\n const latestErrorMsg = difference?.[0];\n\n if (latestErrorMsg) {\n // Is error actually a blur based one - depends on the specific fields in a component as to whether they validate on blur\n // In the case of the ACH form currently all the fields validate on blur\n const isBlurBasedError = true;\n\n // Only add blur based errors to the error panel - doing this step prevents the non-blur based errors from being read out twice\n const latestSRError = isBlurBasedError ? latestErrorMsg.errorMessage : null;\n setSRMessagesFromStrings(latestSRError);\n } else {\n // called when previousSortedErrors.length >= currentErrorsSortedByLayout.length\n clearSRPanel();\n }\n break;\n }\n default:\n break;\n }\n } catch (_) {\n // We don't handle the error related to the sr panel, let it fail silently.\n }\n }, [errors, data]);\n};\n\nexport default useSRPanelForACHErrors;\n"],"names":["useSRPanelForACHErrors","errors","data","isValidating","sortedErrorList","setSortedErrorList","useState","previousSortedErrors","usePrevious","setSRMessagesFromObjects","setSRMessagesFromStrings","clearSRPanel","shouldMoveFocusSR","useSRPanelContext","setSRMessages","layout","useEffect","srPanelResp","current","currentErrorsSortedByLayout","action","ERROR_ACTION_FOCUS_FIELD","setFocusOnField","fieldToFocus","setTimeout","ERROR_ACTION_BLUR_SCENARIO","difference","getArrayDifferences","latestErrorMsg","latestSRError","errorMessage","_"],"mappings":"ubAgCA,MAAMA,EAAyB,EAAGC,SAAQC,OAAMC,mBAE5C,MAAOC,EAAiBC,GAAsBC,EAAS,MAEjDC,EAAuBC,EAAYJ,IACnCK,yBAAEA,EAAwBC,yBAAEA,EAAwBC,aAAEA,EAAYC,kBAAEA,GAAsBC,IAC1FC,EAAuCL,IAA2B,IAGlEM,EAAS,CAAC,sBAAuB,YAAa,gBAAiB,gBAAiB,6BAEtFC,EAAU,KACN,IACI,MAAMC,EAAyCH,IAAgB,CAAEb,SAAQE,aAAcA,EAAae,QAASH,WAGvGI,EAA8BF,GAAaE,4BAOjD,OALAd,EAAmBc,GAKXF,GAAaG,QAEjB,KAAKC,EAEGT,GAAmBU,EAAgB,uBAAwBL,EAAYM,cAE3EC,WAAW,KACPrB,EAAae,SAAU,GACxB,KACH,MAKJ,KAAKO,EAA4B,CAC7B,MAAMC,EAAaC,EAAoBR,EAA6BZ,EAAsB,SAEpFqB,EAAiBF,IAAa,GAEpC,GAAIE,EAAgB,CAGhB,MAGMC,GAHmB,EAGgBD,EAAeE,aAAe,KACvEpB,EAAyBmB,EAC7B,MAEIlB,IAEJ,KACJ,EAIR,CAAE,MAAOoB,GAET,GACD,CAAC9B,EAAQC"}
@@ -1,2 +1,2 @@
1
- import{createElement as e}from"../../../../../../external/preact/dist/preact.js";import{useState as l,useEffect as t}from"../../../../../../external/preact/hooks/dist/hooks.js";import n from"../../../../../internal/FormFields/Field/Field.js";import{useCoreContext as a}from"../../../../../../core/Context/CoreProvider.js";import s from"../../../../../internal/FormFields/Fieldset/Fieldset.js";import i from"../../../../../internal/FormFields/RadioGroup/RadioGroup.js";import o from"../../../../../internal/FormFields/Select/Select.js";import{alternativeLabelContent as m}from"../FieldLabelAlternative.js";function r(r){const{i18n:u}=a(),{amount:d,brand:v,onChange:c,type:p}=r,g=r.installmentOptions[v]||r.installmentOptions.card,f=1===g?.values?.length,[b,h]=l(g?.preselectedValue||g?.values[0]),[F,C]=l("onetime"),j=g?.plans?.includes("revolving"),x=e=>{const l=e.target.value;h(Number(l))},E=e=>{const l=e.currentTarget.getAttribute("value");C(l)},N=e=>{let l,t;var n;return"amount"===p?(l="installmentOption",t={count:e,values:{times:e,partialValue:(n=e,u.amount(d.value/n,d.currency))}}):(l="installmentOptionMonths",t={count:e,values:{times:e}}),{id:e,name:d.value?u.get(l,t):`${e}`}};return t(()=>{g?.values?.includes(b)||h(g?.preselectedValue??g?.values[0])},[v]),t(()=>{const e={value:b,...j&&"revolving"===F&&{plan:F,value:1},...j&&"onetime"===F&&{value:1}};c(g?e:{value:null})},[b,g,F]),g?0===d.value?null:e("div",{className:"adyen-checkout__installments"},j?e(n,{label:u.get("installments"),classNameModifiers:["installments"],name:"installmentsPseudoLabel",useLabelElement:!1,showContextualElement:!1,renderAlternativeToLabel:m},e(s,{classNameModifiers:["revolving-plan"],label:""},e(i,{items:[{id:"onetime",name:"installments.oneTime"},{id:"installments",name:"installments.installments"},{id:"revolving",name:"installments.revolving"}],onChange:E,value:F,ariaLabel:u.get("installments")}),e(n,{className:"installments"!==F?"revolving-plan-installments__disabled":"revolving-plan-installments",classNameModifiers:["revolving-plan-installments"],name:"",useLabelElement:!1,showContextualElement:!1},e(o,{filterable:!1,items:g.values.map(N),selectedValue:b,onChange:x,name:"installments",disabled:"installments"!==F})))):e(n,{label:u.get("installments"),classNameModifiers:["installments"],name:"installments",showContextualElement:!1},e(o,{filterable:!1,items:g.values.map(N),selectedValue:b,onChange:x,name:"installments",readonly:f,allowIdOnButton:!0}))):null}r.defaultProps={brand:"",amount:{},onChange:()=>{}};export{r as default};
1
+ import{createElement as e}from"../../../../../../external/preact/dist/preact.js";import{useState as l,useEffect as t}from"../../../../../../external/preact/hooks/dist/hooks.js";import n from"../../../../../internal/FormFields/Field/Field.js";import{useCoreContext as a}from"../../../../../../core/Context/CoreProvider.js";import s from"../../../../../internal/FormFields/Fieldset/Fieldset.js";import i from"../../../../../internal/FormFields/RadioGroup/RadioGroup.js";import o from"../../../../../internal/FormFields/Select/Select.js";import{alternativeLabelContent as m}from"../FieldLabelAlternative.js";function r(r){const{i18n:u}=a(),{amount:d,brand:v,onChange:c,type:p}=r,g=r.installmentOptions[v]||r.installmentOptions.card,f=1===g?.values?.length,[b,h]=l(g?.preselectedValue||g?.values[0]),[F,C]=l("onetime"),j=g?.plans?.includes("revolving"),N=e=>{const l=e.target.value;h(Number(l))},_=e=>{const l=e.currentTarget.getAttribute("value");C(l)},x=e=>{let l,t;var n;return"amount"===p?(l="installmentOption",t={count:e,values:{times:e,partialValue:(n=e,u.amount(d.value/n,d.currency))}}):(l="installmentOptionMonths",t={count:e,values:{times:e}}),{id:e,name:d.value?u.get(l,t):`${e}`}};return t(()=>{g?.values?.includes(b)||h(g?.preselectedValue??g?.values[0])},[v]),t(()=>{const e={value:b,...j&&"revolving"===F&&{plan:F,value:1},...j&&"onetime"===F&&{value:1}};c(g?e:{value:null})},[b,g,F]),g?0===d.value?null:j?e("div",{className:"adyen-checkout__installments adyen-checkout__installments--revolving-plan"},e(n,{label:u.get("installments"),classNameModifiers:["installments"],name:"installmentsPseudoLabel",useLabelElement:!1,showContextualElement:!1,renderAlternativeToLabel:m},e(s,{classNameModifiers:["revolving-plan"],label:""},e(i,{items:[{id:"onetime",name:"installments.oneTime"},{id:"installments",name:"installments.installments"},{id:"revolving",name:"installments.revolving"}],onChange:_,value:F,ariaLabel:u.get("installments")}),e(n,{className:"installments"!==F?"revolving-plan-installments__disabled":"revolving-plan-installments",classNameModifiers:["revolving-plan-installments"],name:"",useLabelElement:!1,showContextualElement:!1},e(o,{filterable:!1,items:g.values.map(x),selectedValue:b,onChange:N,name:"installments",disabled:"installments"!==F}))))):e("div",{className:"adyen-checkout__installments"},e(n,{label:u.get("installments"),classNameModifiers:["installments"],name:"installments",showContextualElement:!1},e(o,{filterable:!1,items:g.values.map(x),selectedValue:b,onChange:N,name:"installments",readonly:f,allowIdOnButton:!0}))):null}r.defaultProps={brand:"",amount:{},onChange:()=>{}};export{r as default};
2
2
  //# sourceMappingURL=Installments.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Installments.js","sources":["../../../../../../../../src/components/Card/components/CardInput/components/Installments/Installments.tsx"],"sourcesContent":["import { h } from 'preact';\nimport { useState, useEffect } from 'preact/hooks';\nimport Field from '../../../../../internal/FormFields/Field';\nimport { useCoreContext } from '../../../../../../core/Context/CoreProvider';\nimport { InstallmentsItem, InstallmentsProps } from '../types';\nimport Fieldset from '../../../../../internal/FormFields/Fieldset/Fieldset';\nimport RadioGroup from '../../../../../internal/FormFields/RadioGroup';\nimport Select from '../../../../../internal/FormFields/Select';\nimport { alternativeLabelContent } from '../FieldLabelAlternative';\nimport './Installments.scss';\n\nexport interface InstallmentsObj {\n value: number;\n plan?: 'revolving';\n}\n\n/**\n * Installments generic dropdown\n */\nfunction Installments(props: InstallmentsProps) {\n const { i18n } = useCoreContext();\n const { amount, brand, onChange, type } = props;\n const installmentOptions = props.installmentOptions[brand] || props.installmentOptions.card;\n const readOnly = installmentOptions?.values?.length === 1;\n const [installmentAmount, setInstallmentAmount] = useState(installmentOptions?.preselectedValue || installmentOptions?.values[0]);\n const [radioBtnValue, setRadioBtnValue] = useState('onetime');\n\n // hasRadioButtonUI determines if we have 3 radio buttons in the UI ('onetime', 'installments' and 'revolving')\n const hasRadioButtonUI = installmentOptions?.plans?.includes('revolving');\n const getPartialAmount = (divider: number): string => i18n.amount(amount.value / divider, amount.currency);\n\n const onSelectInstallment = e => {\n const selectedInstallments = e.target.value;\n setInstallmentAmount(Number(selectedInstallments));\n };\n\n const onRadioSelect = e => {\n const selectedBtn = e.currentTarget.getAttribute('value');\n setRadioBtnValue(selectedBtn);\n };\n\n const installmentItemsMapper = (value: number): InstallmentsItem => {\n let translationKey;\n let translationObj;\n\n if (type === 'amount') {\n translationKey = 'installmentOption';\n translationObj = { count: value, values: { times: value, partialValue: getPartialAmount(value) } };\n } else {\n translationKey = `installmentOptionMonths`;\n translationObj = { count: value, values: { times: value } };\n }\n\n return {\n id: value,\n name: amount.value ? i18n.get(translationKey, translationObj) : `${value}`\n };\n };\n\n useEffect(() => {\n if (installmentOptions?.values?.includes(installmentAmount)) {\n return;\n }\n\n setInstallmentAmount(installmentOptions?.preselectedValue ?? installmentOptions?.values[0]);\n }, [brand]);\n\n useEffect(() => {\n const stateObj: InstallmentsObj = {\n value: installmentAmount, // No radio button interface or \"installments\" radio button selected\n ...(hasRadioButtonUI && radioBtnValue === 'revolving' && { plan: radioBtnValue, value: 1 }),\n ...(hasRadioButtonUI && radioBtnValue === 'onetime' && { value: 1 })\n };\n\n onChange(installmentOptions ? stateObj : { value: null });\n }, [installmentAmount, installmentOptions, radioBtnValue]);\n\n if (!installmentOptions) return null;\n if (amount.value === 0) return null;\n\n // Alternate interface for installments with the possibility of a \"revolving\" plan\n if (hasRadioButtonUI) {\n return (\n <div className=\"adyen-checkout__installments\">\n <Field\n label={i18n.get('installments')}\n classNameModifiers={['installments']}\n name={'installmentsPseudoLabel'}\n useLabelElement={false}\n showContextualElement={false}\n renderAlternativeToLabel={alternativeLabelContent}\n >\n <Fieldset classNameModifiers={['revolving-plan']} label={''}>\n <RadioGroup\n items={[\n { id: 'onetime', name: 'installments.oneTime' },\n { id: 'installments', name: 'installments.installments' },\n { id: 'revolving', name: 'installments.revolving' }\n ]}\n onChange={onRadioSelect}\n value={radioBtnValue}\n ariaLabel={i18n.get('installments')}\n />\n\n <Field\n className={radioBtnValue !== 'installments' ? 'revolving-plan-installments__disabled' : 'revolving-plan-installments'}\n classNameModifiers={['revolving-plan-installments']}\n name={''}\n useLabelElement={false}\n showContextualElement={false}\n >\n <Select\n filterable={false}\n items={installmentOptions.values.map(installmentItemsMapper)}\n selectedValue={installmentAmount}\n onChange={onSelectInstallment}\n name={'installments'}\n disabled={radioBtnValue !== 'installments'}\n />\n </Field>\n </Fieldset>\n </Field>\n </div>\n );\n }\n\n return (\n <div className=\"adyen-checkout__installments\">\n <Field label={i18n.get('installments')} classNameModifiers={['installments']} name={'installments'} showContextualElement={false}>\n <Select\n filterable={false}\n items={installmentOptions.values.map(installmentItemsMapper)}\n selectedValue={installmentAmount}\n onChange={onSelectInstallment}\n name={'installments'}\n readonly={readOnly}\n allowIdOnButton={true}\n />\n </Field>\n </div>\n );\n}\n\nInstallments.defaultProps = {\n brand: '',\n amount: {},\n onChange: () => {}\n};\n\nexport default Installments;\n"],"names":["Installments","props","i18n","useCoreContext","amount","brand","onChange","type","installmentOptions","card","readOnly","values","length","installmentAmount","setInstallmentAmount","useState","preselectedValue","radioBtnValue","setRadioBtnValue","hasRadioButtonUI","plans","includes","onSelectInstallment","e","selectedInstallments","target","value","Number","onRadioSelect","selectedBtn","currentTarget","getAttribute","installmentItemsMapper","translationKey","translationObj","divider","count","times","partialValue","currency","id","name","get","useEffect","stateObj","plan","h","div","className","Field","label","classNameModifiers","useLabelElement","showContextualElement","renderAlternativeToLabel","alternativeLabelContent","Fieldset","RadioGroup","items","ariaLabel","Select","filterable","map","selectedValue","disabled","readonly","allowIdOnButton","defaultProps"],"mappings":"6lBAmBA,SAASA,EAAaC,GAClB,MAAMC,KAAEA,GAASC,KACXC,OAAEA,EAAMC,MAAEA,EAAKC,SAAEA,EAAQC,KAAEA,GAASN,EACpCO,EAAqBP,EAAMO,mBAAmBH,IAAUJ,EAAMO,mBAAmBC,KACjFC,EAAkD,IAAvCF,GAAoBG,QAAQC,QACtCC,EAAmBC,GAAwBC,EAASP,GAAoBQ,kBAAoBR,GAAoBG,OAAO,KACvHM,EAAeC,GAAo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AAA,CACGC,MAAO,CACH,CAAElB,GAAI,UAAWC,KAAM,wBACvB,CAAED,GAAI,eAAgBC,KAAM,6BAC5B,CAAED,GAAI,YAAaC,KAAM,2BAE7BnC,SAAUsB,EACVF,MAAOT,EACP0C,UAAWzD,EAAKwC,IAAI,kBAGxBI,EAACG,EAAAA,CACGD,UAA6B,iBAAlB/B,EAAmC,wCAA0C,8BACxFkC,mBAAoB,CAAC,+BACrBV,KAAM,GACNW,iBAAiB,EACjBC,uBAAuB,GAEvBP,EAACc,EAAAA,CACGC,YAAY,EACZH,MAAOlD,EAAmBG,OAAOmD,IAAI9B,GACrC+B,cAAelD,EACfP,SAAUgB,EACVmB,KAAM,eACNuB,SAA4B,iBAAlB/C,OAW9B6B,EAACG,EAAAA,CAAMC,MAAOhD,EAAKwC,IAAI,gBAAiBS,mBAAoB,CAAC,gBAAiBV,KAAM,eAAgBY,uBAAuB,GACvHP,EAACc,EAAAA,CACGC,YAAY,EACZH,MAAOlD,EAAmBG,OAAOmD,IAAI9B,GACrC+B,cAAelD,EACfP,SAAUgB,EACVmB,KAAM,eACNwB,SAAUvD,EACVwD,iBAAiB,MA3DD,IAgEpC,CAEAlE,EAAamE,aAAe,CACxB9D,MAAO,GACPD,OAAQ,CAAA,EACRE,SAAU"}
1
+ {"version":3,"file":"Installments.js","sources":["../../../../../../../../src/components/Card/components/CardInput/components/Installments/Installments.tsx"],"sourcesContent":["import { h } from 'preact';\nimport { useState, useEffect } from 'preact/hooks';\nimport Field from '../../../../../internal/FormFields/Field';\nimport { useCoreContext } from '../../../../../../core/Context/CoreProvider';\nimport { InstallmentsItem, InstallmentsProps } from '../types';\nimport Fieldset from '../../../../../internal/FormFields/Fieldset/Fieldset';\nimport RadioGroup from '../../../../../internal/FormFields/RadioGroup';\nimport Select from '../../../../../internal/FormFields/Select';\nimport { alternativeLabelContent } from '../FieldLabelAlternative';\nimport './Installments.scss';\n\nexport interface InstallmentsObj {\n value: number;\n plan?: 'revolving';\n}\n\n/**\n * Installments generic dropdown\n */\nfunction Installments(props: InstallmentsProps) {\n const { i18n } = useCoreContext();\n const { amount, brand, onChange, type } = props;\n const installmentOptions = props.installmentOptions[brand] || props.installmentOptions.card;\n const readOnly = installmentOptions?.values?.length === 1;\n const [installmentAmount, setInstallmentAmount] = useState(installmentOptions?.preselectedValue || installmentOptions?.values[0]);\n const [radioBtnValue, setRadioBtnValue] = useState('onetime');\n\n // hasRadioButtonUI determines if we have 3 radio buttons in the UI ('onetime', 'installments' and 'revolving')\n const hasRadioButtonUI = installmentOptions?.plans?.includes('revolving');\n const getPartialAmount = (divider: number): string => i18n.amount(amount.value / divider, amount.currency);\n\n const onSelectInstallment = e => {\n const selectedInstallments = e.target.value;\n setInstallmentAmount(Number(selectedInstallments));\n };\n\n const onRadioSelect = e => {\n const selectedBtn = e.currentTarget.getAttribute('value');\n setRadioBtnValue(selectedBtn);\n };\n\n const installmentItemsMapper = (value: number): InstallmentsItem => {\n let translationKey;\n let translationObj;\n\n if (type === 'amount') {\n translationKey = 'installmentOption';\n translationObj = { count: value, values: { times: value, partialValue: getPartialAmount(value) } };\n } else {\n translationKey = `installmentOptionMonths`;\n translationObj = { count: value, values: { times: value } };\n }\n\n return {\n id: value,\n name: amount.value ? i18n.get(translationKey, translationObj) : `${value}`\n };\n };\n\n useEffect(() => {\n if (installmentOptions?.values?.includes(installmentAmount)) {\n return;\n }\n\n setInstallmentAmount(installmentOptions?.preselectedValue ?? installmentOptions?.values[0]);\n }, [brand]);\n\n useEffect(() => {\n const stateObj: InstallmentsObj = {\n value: installmentAmount, // No radio button interface or \"installments\" radio button selected\n ...(hasRadioButtonUI && radioBtnValue === 'revolving' && { plan: radioBtnValue, value: 1 }),\n ...(hasRadioButtonUI && radioBtnValue === 'onetime' && { value: 1 })\n };\n\n onChange(installmentOptions ? stateObj : { value: null });\n }, [installmentAmount, installmentOptions, radioBtnValue]);\n\n if (!installmentOptions) return null;\n if (amount.value === 0) return null;\n\n // Alternate interface for installments with the possibility of a \"revolving\" plan\n if (hasRadioButtonUI) {\n return (\n <div className=\"adyen-checkout__installments adyen-checkout__installments--revolving-plan\">\n <Field\n label={i18n.get('installments')}\n classNameModifiers={['installments']}\n name={'installmentsPseudoLabel'}\n useLabelElement={false}\n showContextualElement={false}\n renderAlternativeToLabel={alternativeLabelContent}\n >\n <Fieldset classNameModifiers={['revolving-plan']} label={''}>\n <RadioGroup\n items={[\n { id: 'onetime', name: 'installments.oneTime' },\n { id: 'installments', name: 'installments.installments' },\n { id: 'revolving', name: 'installments.revolving' }\n ]}\n onChange={onRadioSelect}\n value={radioBtnValue}\n ariaLabel={i18n.get('installments')}\n />\n\n <Field\n className={radioBtnValue !== 'installments' ? 'revolving-plan-installments__disabled' : 'revolving-plan-installments'}\n classNameModifiers={['revolving-plan-installments']}\n name={''}\n useLabelElement={false}\n showContextualElement={false}\n >\n <Select\n filterable={false}\n items={installmentOptions.values.map(installmentItemsMapper)}\n selectedValue={installmentAmount}\n onChange={onSelectInstallment}\n name={'installments'}\n disabled={radioBtnValue !== 'installments'}\n />\n </Field>\n </Fieldset>\n </Field>\n </div>\n );\n }\n\n return (\n <div className=\"adyen-checkout__installments\">\n <Field label={i18n.get('installments')} classNameModifiers={['installments']} name={'installments'} showContextualElement={false}>\n <Select\n filterable={false}\n items={installmentOptions.values.map(installmentItemsMapper)}\n selectedValue={installmentAmount}\n onChange={onSelectInstallment}\n name={'installments'}\n readonly={readOnly}\n allowIdOnButton={true}\n />\n </Field>\n </div>\n );\n}\n\nInstallments.defaultProps = {\n brand: '',\n amount: {},\n onChange: () => {}\n};\n\nexport default Installments;\n"],"names":["Installments","props","i18n","useCoreContext","amount","brand","onChange","type","installmentOptions","card","readOnly","values","length","installmentAmount","setInstallmentAmount","useState","preselectedValue","radioBtnValue","setRadioBtnValue","hasRadioButtonUI","plans","includes","onSelectInstallment","e","selectedInstallments","target","value","Number","onRadioSelect","selectedBtn","currentTarget","getAttribute","installmentItemsMapper","translationKey","translationObj","divider","count","times","partialValue","currency","id","name","get","useEffect","stateObj","plan","h","div","className","Field","label","classNameModifiers","useLabelElement","showContextualElement","renderAlternativeToLabel","alternativeLabelContent","Fieldset","RadioGroup","items","ariaLabel","Select","filterable","map","selectedValue","disabled","readonly","allowIdOnButton","defaultProps"],"mappings":"6lBAmBA,SAASA,EAAaC,GAClB,MAAMC,KAAEA,GAASC,KACXC,OAAEA,EAAMC,MAAEA,EAAKC,SAAEA,EAAQC,KAAEA,GAASN,EACpCO,EAAqBP,EAAMO,mBAAmBH,IAAUJ,EAAMO,mBAAmBC,KACjFC,EAAkD,IAAvCF,GAAoBG,QAAQC,QACtCC,EAAmBC,GAAwBC,EAASP,GAAoBQ,kBAAoBR,GAAoBG,OAAO,KACvHM,EAAeC,GAAoBH,EAAS,WAG7CI,EAAmBX,GAAoBY,OAAOC,SAAS,aAGvDC,EAAsBC,IACxB,MAAMC,EAAuBD,EAAEE,OAAOC,MACtCZ,EAAqBa,OAAOH,KAG1BI,EAAgBL,IAClB,MAAMM,EAAcN,EAAEO,cAAcC,aAAa,SACjDb,EAAiBW,IAGfG,EAA0BN,IAC5B,IAAIO,EACAC,EAdiB,IAACC,EAwBtB,MARa,WAAT5B,GACA0B,EAAiB,oBACjBC,EAAiB,CAAEE,MAAOV,EAAOf,OAAQ,CAAE0B,MAAOX,EAAOY,cAlBvCH,EAkBsET,EAlB1CxB,EAAKE,OAAOA,EAAOsB,MAAQS,EAAS/B,EAAOmC,eAoBzFN,EAAiB,0BACjBC,EAAiB,CAAEE,MAAOV,EAAOf,OAAQ,CAAE0B,MAAOX,KAG/C,CACHc,GAAId,EACJe,KAAMrC,EAAOsB,MAAQxB,EAAKwC,IAAIT,EAAgBC,GAAkB,GAAGR,MAsB3E,OAlBAiB,EAAU,KACFnC,GAAoBG,QAAQU,SAASR,IAIzCC,EAAqBN,GAAoBQ,kBAAoBR,GAAoBG,OAAO,KACzF,CAACN,IAEJsC,EAAU,KACN,MAAMC,EAA4B,CAC9BlB,MAAOb,KACHM,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,aAAe,CACxB9D,MAAO,GACPD,OAAQ,CAAA,EACRE,SAAU"}
@@ -1 +1 @@
1
- {"version":3,"file":"handlers.js","sources":["../../../../../../src/components/Card/components/CardInput/handlers.ts"],"sourcesContent":["import { ENCRYPTED_CARD_NUMBER, CREDIT_CARD_SF_FIELDS } from '../../../internal/SecuredFields/lib/constants';\nimport { selectOne } from '../../../internal/SecuredFields/lib/utilities/dom';\nimport { CardFocusData } from '../../../internal/SecuredFields/lib/types';\n\n/**\n * Helper for CardInput - gets a field name and sets focus on it\n */\nexport const setFocusOnFirstField = (isValidating, sfp, fieldToFocus) => {\n if (isValidating) {\n // If not a cardInput related securedField - find field and set focus on it\n if (!CREDIT_CARD_SF_FIELDS.includes(fieldToFocus)) {\n setFocusOnNonSF(fieldToFocus, sfp);\n } else {\n // Is a securedField - so it has its own focus procedures\n sfp.current.setFocusOn(fieldToFocus);\n }\n }\n};\n\nexport const getAddressHandler = (setFormData, setFormValid, setFormErrors) => {\n // Return Handler fn:\n return address => {\n setFormData('billingAddress', address.data);\n setFormValid('billingAddress', address.isValid);\n setFormErrors('billingAddress', address.errors);\n };\n};\n\nexport const getFocusHandler = (setFocusedElement, onFocus, onBlur) => {\n // Return Handler fn:\n return (e: CardFocusData) => {\n setFocusedElement(e.currentFocusObject);\n e.focus === true ? onFocus(e.fieldType, e) : onBlur(e.fieldType, e);\n };\n};\n\nexport const getAutoJumpHandler = (isAutoJumping, sfp, layout) => {\n return () => {\n if (!isAutoJumping.current) {\n isAutoJumping.current = true;\n\n // CardInput can call this more than once in quick succession\n // e.g. if field was in error (error + fieldValid) or other SFs are optional (fieldValid + allValid) etc\n // - so make async to avoid double setFocus call\n void Promise.resolve().then(() => {\n const panIndex = layout.findIndex(elem => elem === ENCRYPTED_CARD_NUMBER);\n const subsequentFields = layout.slice(panIndex + 1);\n\n /**\n * Investigate subsequent fields to see if they can/should accept focus\n */\n for (const field of subsequentFields) {\n // Is the next field a credit card related securedField?\n if (CREDIT_CARD_SF_FIELDS.includes(field)) {\n const isOptionalOrHidden = sfp.current.sfIsOptionalOrHidden(field);\n if (!isOptionalOrHidden) {\n sfp.current.setFocusOn(field);\n break;\n }\n } else {\n // If it isn't an SF - shift focus to it (we're currently not concerned with whether the field is optional)\n\n setFocusOnNonSF(field, sfp);\n break;\n }\n }\n\n isAutoJumping.current = false;\n });\n }\n };\n};\n\nconst setFocusOnNonSF = (field, sfp) => {\n let nameVal: string = field;\n\n // We have an exception with the kcp taxNumber where the name of the field ('kcpTaxNumberOrDOB') doesn't match\n // the value by which the field is referred to internally ('taxNumber')\n if (nameVal === 'taxNumber') nameVal = 'kcpTaxNumberOrDOB';\n\n if (nameVal === 'country' || nameVal === 'stateOrProvince') {\n // Set focus on dropdown\n const field: HTMLElement = selectOne(sfp.current.rootNode, `.adyen-checkout__field--${nameVal} .adyen-checkout__filter-input`);\n field?.focus();\n } else {\n // Set focus on input\n const field: HTMLElement = selectOne(sfp.current.rootNode, `[name=\"${nameVal}\"]`);\n field?.focus();\n }\n};\n"],"names":["setFocusOnFirstField","isValidating","sfp","fieldToFocus","CREDIT_CARD_SF_FIELDS","includes","current","setFocusOn","setFocusOnNonSF","getAddressHandler","setFormData","setFormValid","setFormErrors","address","data","isValid","errors","getFocusHandler","setFocusedElement","onFocus","onBlur","e","currentFocusObject","focus","fieldType","getAutoJumpHandler","isAutoJumping","layout","Promise","resolve","then","panIndex","findIndex","elem","ENCRYPTED_CARD_NUMBER","subsequentFields","slice","field","sfIsOptionalOrHidden","nameVal","selectOne","rootNode"],"mappings":"qMAOO,MAAMA,EAAuB,CAACC,EAAcC,EAAKC,KAChDF,IAEKG,EAAsBC,SAASF,GAIhCD,EAAII,QAAQC,WAAWJ,GAHvBK,EAAgBL,EAAcD,KAQ7BO,EAAoB,CAACC,EAAaC,EAAcC,IAElDC,IACHH,EAAY,iBAAkBG,EAAQC,MACtCH,EAAa,iBAAkBE,EAAQE,SACvCH,EAAc,iBAAkBC,EAAQG,SAInCC,EAAkB,CAACC,EAAmBC,EAASC,IAEhDC,IACJH,EAAkBG,EAAEC,qBACR,IAAZD,EAAEE,MAAiBJ,EAAQE,EAAEG,UAAWH,GAAKD,EAAOC,EAAEG,UAAWH,IAI5DI,EAAqB,CAACC,EAAexB,EAAKyB,IAC5C,KACED,EAAcpB,UACfoB,EAAcpB,SAAU,EAKnBsB,QAAQC,UAAUC,KAAK,KACxB,MAAMC,EAAWJ,EAAOK,UAAUC,GAAQA,IAASC,GAC7CC,EAAmBR,EAAOS,MAAML,EAAW,GAKjD,IAAK,MAAMM,KAASF,EAAkB,CAElC,IAAI/B,EAAsBC,SAASgC,GAM5B,CAGH7B,EAAgB6B,EAAOnC,GACvB,KACJ,CATI,IAD2BA,EAAII,QAAQgC,qBAAqBD,GACnC,CACrBnC,EAAII,QAAQC,WAAW8B,GACvB,KACJ,CAOR,CAEAX,EAAcpB,SAAU,MAMlCE,EAAkB,CAAC6B,EAAOnC,KAC5B,IAAIqC,EAAkBF,EAMtB,GAFgB,cAAZE,IAAyBA,EAAU,qBAEvB,YAAZA,GAAqC,oBAAZA,EAA+B,CAExD,MAAMF,EAAqBG,EAAUtC,EAAII,QAAQmC,SAAU,2BAA2BF,mCACtFF,GAAOd,YACJ,CAEH,MAAMc,EAAqBG,EAAUtC,EAAII,QAAQmC,SAAU,UAAUF,OACrEF,GAAOd,OACX"}
1
+ {"version":3,"file":"handlers.js","sources":["../../../../../../src/components/Card/components/CardInput/handlers.ts"],"sourcesContent":["import { ENCRYPTED_CARD_NUMBER, CREDIT_CARD_SF_FIELDS } from '../../../internal/SecuredFields/lib/constants';\nimport { selectOne } from '../../../internal/SecuredFields/lib/utilities/dom';\nimport { CardFocusData } from '../../../internal/SecuredFields/lib/types';\n\n/**\n * Helper for CardInput - gets a field name and sets focus on it\n */\nexport const setFocusOnFirstField = (isValidating, sfp, fieldToFocus) => {\n if (isValidating) {\n // If not a cardInput related securedField - find field and set focus on it\n if (!CREDIT_CARD_SF_FIELDS.includes(fieldToFocus)) {\n setFocusOnNonSF(fieldToFocus, sfp);\n } else {\n // Is a securedField - so it has its own focus procedures\n sfp.current.setFocusOn(fieldToFocus);\n }\n }\n};\n\nexport const getAddressHandler = (setFormData, setFormValid, setFormErrors) => {\n // Return Handler fn:\n return address => {\n setFormData('billingAddress', address.data);\n setFormValid('billingAddress', address.isValid);\n setFormErrors('billingAddress', address.errors);\n };\n};\n\nexport const getFocusHandler = (setFocusedElement, onFocus, onBlur) => {\n // Return Handler fn:\n return (e: CardFocusData) => {\n setFocusedElement(e.currentFocusObject);\n e.focus === true ? onFocus(e.fieldType, e) : onBlur(e.fieldType, e);\n };\n};\n\nexport const getAutoJumpHandler = (isAutoJumping, sfp, layout) => {\n return () => {\n if (!isAutoJumping.current) {\n isAutoJumping.current = true;\n\n // CardInput can call this more than once in quick succession\n // e.g. if field was in error (error + fieldValid) or other SFs are optional (fieldValid + allValid) etc\n // - so make async to avoid double setFocus call\n void Promise.resolve().then(() => {\n const panIndex = layout.findIndex(elem => elem === ENCRYPTED_CARD_NUMBER);\n const subsequentFields = layout.slice(panIndex + 1);\n\n /**\n * Investigate subsequent fields to see if they can/should accept focus\n */\n for (const field of subsequentFields) {\n // Is the next field a credit card related securedField?\n if (CREDIT_CARD_SF_FIELDS.includes(field)) {\n const isOptionalOrHidden = sfp.current.sfIsOptionalOrHidden(field);\n if (!isOptionalOrHidden) {\n sfp.current.setFocusOn(field);\n break;\n }\n } else {\n // If it isn't an SF - shift focus to it (we're currently not concerned with whether the field is optional)\n\n setFocusOnNonSF(field, sfp);\n break;\n }\n }\n\n isAutoJumping.current = false;\n });\n }\n };\n};\n\nconst setFocusOnNonSF = (field, sfp) => {\n let nameVal: string = field;\n\n // We have an exception with the kcp taxNumber where the name of the field ('kcpTaxNumberOrDOB') doesn't match\n // the value by which the field is referred to internally ('taxNumber')\n if (nameVal === 'taxNumber') nameVal = 'kcpTaxNumberOrDOB';\n\n if (nameVal === 'country' || nameVal === 'stateOrProvince') {\n // Set focus on dropdown\n const field: HTMLElement = selectOne(sfp.current.rootNode, `.adyen-checkout__field--${nameVal} .adyen-checkout__filter-input`);\n field?.focus();\n } else {\n // Set focus on input\n const field: HTMLElement = selectOne(sfp.current.rootNode, `[name=\"${nameVal}\"]`);\n field?.focus();\n }\n};\n"],"names":["setFocusOnFirstField","isValidating","sfp","fieldToFocus","CREDIT_CARD_SF_FIELDS","includes","current","setFocusOn","setFocusOnNonSF","getAddressHandler","setFormData","setFormValid","setFormErrors","address","data","isValid","errors","getFocusHandler","setFocusedElement","onFocus","onBlur","e","currentFocusObject","focus","fieldType","getAutoJumpHandler","isAutoJumping","layout","Promise","resolve","then","panIndex","findIndex","elem","ENCRYPTED_CARD_NUMBER","subsequentFields","slice","field","sfIsOptionalOrHidden","nameVal","selectOne","rootNode"],"mappings":"qMAOO,MAAMA,EAAuB,CAACC,EAAcC,EAAKC,KAChDF,IAEKG,EAAsBC,SAASF,GAIhCD,EAAII,QAAQC,WAAWJ,GAHvBK,EAAgBL,EAAcD,KAQ7BO,EAAoB,CAACC,EAAaC,EAAcC,IAElDC,IACHH,EAAY,iBAAkBG,EAAQC,MACtCH,EAAa,iBAAkBE,EAAQE,SACvCH,EAAc,iBAAkBC,EAAQG,SAInCC,EAAkB,CAACC,EAAmBC,EAASC,IAEhDC,IACJH,EAAkBG,EAAEC,qBACR,IAAZD,EAAEE,MAAiBJ,EAAQE,EAAEG,UAAWH,GAAKD,EAAOC,EAAEG,UAAWH,IAI5DI,EAAqB,CAACC,EAAexB,EAAKyB,IAC5C,KACED,EAAcpB,UACfoB,EAAcpB,SAAU,EAKnBsB,QAAQC,UAAUC,KAAK,KACxB,MAAMC,EAAWJ,EAAOK,UAAUC,GAAQA,IAASC,GAC7CC,EAAmBR,EAAOS,MAAML,EAAW,GAKjD,IAAK,MAAMM,KAASF,EAAkB,CAElC,IAAI/B,EAAsBC,SAASgC,GAM5B,CAGH7B,EAAgB6B,EAAOnC,GACvB,KACJ,CATI,IAD2BA,EAAII,QAAQgC,qBAAqBD,GACnC,CACrBnC,EAAII,QAAQC,WAAW8B,GACvB,KACJ,CAOR,CAEAX,EAAcpB,SAAU,MAMlCE,EAAkB,CAAC6B,EAAOnC,KAC5B,IAAIqC,EAAkBF,EAMtB,GAFgB,cAAZE,IAAyBA,EAAU,qBAEvB,YAAZA,GAAqC,oBAAZA,EAA+B,CAExD,MAAMF,EAAqBG,EAAUtC,EAAII,QAAQmC,SAAU,2BAA2BF,mCACtFF,GAAOd,OACX,KAAO,CAEH,MAAMc,EAAqBG,EAAUtC,EAAII,QAAQmC,SAAU,UAAUF,OACrEF,GAAOd,OACX"}
@@ -1 +1 @@
1
- {"version":3,"file":"useSRPanelForCardInputErrors.js","sources":["../../../../../../src/components/Card/components/CardInput/useSRPanelForCardInputErrors.ts"],"sourcesContent":["import { useEffect, useState } from 'preact/hooks';\nimport useSRPanelContext from '../../../../core/Errors/useSRPanelContext';\nimport { SetSRMessagesReturnFn } from '../../../../core/Errors/SRPanelProvider';\nimport { handlePartialAddressMode, lookupBlurBasedErrors, mapFieldKey } from './utils';\nimport { usePrevious } from '../../../../utils/hookUtils';\nimport { SetSRMessagesReturnObject, SortedErrorObject } from '../../../../core/Errors/types';\nimport { ERROR_ACTION_BLUR_SCENARIO, ERROR_ACTION_FOCUS_FIELD } from '../../../../core/Errors/constants';\nimport { setFocusOnFirstField } from './handlers';\nimport { getArrayDifferences } from '../../../../utils/arrayUtils';\n\nconst useSRPanelForCardInputErrors = ({ errors, props, isValidating, retrieveLayout, specifications, billingAddress, sfp }) => {\n // Extract fns from context\n const { setSRMessagesFromObjects, setSRMessagesFromStrings, clearSRPanel, shouldMoveFocusSR } = useSRPanelContext();\n\n // Generate a setSRMessages function - implemented as a partial, since the initial set of arguments don't change.\n const setSRMessages: SetSRMessagesReturnFn = setSRMessagesFromObjects?.({\n fieldTypeMappingFn: mapFieldKey\n });\n\n const partialAddressSchema = handlePartialAddressMode(props.billingAddressMode);\n\n const [sortedErrorList, setSortedErrorList] = useState<SortedErrorObject[]>(null);\n\n // Get the previous list of errors\n const previousSortedErrors = usePrevious(sortedErrorList);\n\n const sfStateErrorsObj = sfp.current?.mapErrorsToValidationRuleResult();\n const mergedErrors = { ...errors, ...sfStateErrorsObj };\n\n useEffect(() => {\n try {\n // Extract and then flatten billingAddress errors into a new object with *all* the field errors at top level\n const { billingAddress: extractedAddressErrors, ...errorsWithoutAddress } = mergedErrors;\n\n const errorsForPanel = { ...errorsWithoutAddress, ...extractedAddressErrors };\n\n // Pass dynamic props (errors, layout etc) to SRPanel via partial\n const srPanelResp: SetSRMessagesReturnObject = setSRMessages?.({\n errors: errorsForPanel,\n isValidating: isValidating.current,\n layout: retrieveLayout(),\n // If we don't have country specific address labels, we might have a label related to a partialAddressSchema (i.e. zipCode)\n countrySpecificLabels: specifications.getAddressLabelsForCountry(billingAddress?.country) ?? partialAddressSchema?.default?.labels\n });\n\n // Store the array of sorted error objects separately so that we can use it to make comparisons between the old and new arrays\n const currentErrorsSortedByLayout = srPanelResp?.currentErrorsSortedByLayout;\n setSortedErrorList(currentErrorsSortedByLayout);\n\n /**\n * Need extra actions after setting SRPanel messages in order to focus field (if required) and because we have some errors that are fired onBlur\n */\n switch (srPanelResp?.action) {\n // A call to focus the first field in error will always follow the call to validate the whole form\n case ERROR_ACTION_FOCUS_FIELD:\n if (shouldMoveFocusSR) setFocusOnFirstField(isValidating.current, sfp, srPanelResp?.fieldToFocus);\n // Remove 'showValidation' mode - allowing time for collation of all the fields in error whilst it is 'showValidation' mode (some errors come in a second render pass)\n setTimeout(() => {\n isValidating.current = false;\n }, 300);\n break;\n\n /**\n * Relates to errors triggered by a field blurring (some pm forms have this, some don't) - check if there is an error to either set or to clear\n */\n case ERROR_ACTION_BLUR_SCENARIO: {\n const difference = getArrayDifferences<SortedErrorObject, string>(currentErrorsSortedByLayout, previousSortedErrors, 'field');\n\n const latestErrorMsg = difference?.[0];\n\n if (latestErrorMsg) {\n // Use the error code to look up whether error is actually a blur based one (most are but some SF ones aren't)\n const isBlurBasedError = lookupBlurBasedErrors(latestErrorMsg.errorCode);\n\n /**\n * ONLY ADD BLUR BASED ERRORS TO THE ERROR PANEL - doing this step prevents the non-blur based errors from being read out twice\n * (once from the aria-live, error panel & once from the aria-describedby element)\n */\n const latestSRError = isBlurBasedError ? latestErrorMsg.errorMessage : null;\n // console.log('### CardInput2::componentDidUpdate:: #2 (not validating) single error:: latestSRError', latestSRError);\n setSRMessagesFromStrings(latestSRError);\n } else {\n // called when previousSortedErrors.length >= currentErrorsSortedByLayout.length\n // console.log('### CardInput2::componentDidUpdate:: #3(not validating) clearing errors:: NO latestErrorMsg');\n clearSRPanel();\n }\n break;\n }\n default:\n break;\n }\n } catch (_) {\n // We don't handle the error related to the sr panel, let it fail silently.\n }\n }, [errors]);\n\n return { sortedErrorList, previousSortedErrors, clearSRPanel };\n};\n\nexport default useSRPanelForCardInputErrors;\n"],"names":["useSRPanelForCardInputErrors","errors","props","isValidating","retrieveLayout","specifications","billingAddress","sfp","setSRMessagesFromObjects","setSRMessagesFromStrings","clearSRPanel","shouldMoveFocusSR","useSRPanelContext","setSRMessages","fieldTypeMappingFn","mapFieldKey","partialAddressSchema","handlePartialAddressMode","billingAddressMode","sortedErrorList","setSortedErrorList","useState","previousSortedErrors","usePrevious","sfStateErrorsObj","current","mapErrorsToValidationRuleResult","mergedErrors","useEffect","extractedAddressErrors","errorsWithoutAddress","errorsForPanel","srPanelResp","layout","countrySpecificLabels","getAddressLabelsForCountry","country","default","labels","currentErrorsSortedByLayout","action","ERROR_ACTION_FOCUS_FIELD","setFocusOnFirstField","fieldToFocus","setTimeout","ERROR_ACTION_BLUR_SCENARIO","difference","getArrayDifferences","latestErrorMsg","latestSRError","lookupBlurBasedErrors","errorCode","errorMessage","_"],"mappings":"giBAUA,MAAMA,EAA+B,EAAGC,SAAQC,QAAOC,eAAcC,iBAAgBC,iBAAgBC,iBAAgBC,UAEjH,MAAMC,yBAAEA,EAAwBC,yBAAEA,EAAwBC,aAAEA,EAAYC,kBAAEA,GAAsBC,IAG1FC,EAAuCL,IAA2B,CACpEM,mBAAoBC,IAGlBC,EAAuBC,EAAyBf,EAAMgB,qBAErDC,EAAiBC,GAAsBC,EAA8B,MAGtEC,EAAuBC,EAAYJ,GAEnCK,EAAmBjB,EAAIkB,SAASC,kCAChCC,EAAe,IAAK1B,KAAWuB,GAqErC,OAnEAI,EAAU,KACN,IAEI,MAAQtB,eAAgBuB,KAA2BC,GAAyBH,EAEtEI,EAAiB,IAAKD,KAAyBD,GAG/CG,EAAyCnB,IAAgB,CAC3DZ,OAAQ8B,EACR5B,aAAcA,EAAasB,QAC3BQ,OAAQ7B,IAER8B,sBAAuB7B,EAAe8B,2BAA2B7B,GAAgB8B,UAAYpB,GAAsBqB,SAASC,SAI1HC,EAA8BP,GAAaO,4BAMjD,OALAnB,EAAmBmB,GAKXP,GAAaQ,QAEjB,KAAKC,EACG9B,GAAmB+B,EAAqBvC,EAAasB,QAASlB,EAAKyB,GAAaW,cAEpFC,WAAW,KACPzC,EAAasB,SAAU,GACxB,KACH,MAKJ,KAAKoB,EAA4B,CAC7B,MAAMC,EAAaC,EAA+CR,EAA6BjB,EAAsB,SAE/G0B,EAAiBF,IAAa,GAEpC,GAAIE,EAAgB,CAEhB,MAMMC,EANmBC,EAAsBF,EAAeG,WAMrBH,EAAeI,aAAe,KAEvE3C,EAAyBwC,QAIzBvC,IAEJ,KACJ,EAIR,CAAE,MAAO2C,GAET,GACD,CAACpD,IAEG,CAAEkB,kBAAiBG,uBAAsBZ"}
1
+ {"version":3,"file":"useSRPanelForCardInputErrors.js","sources":["../../../../../../src/components/Card/components/CardInput/useSRPanelForCardInputErrors.ts"],"sourcesContent":["import { useEffect, useState } from 'preact/hooks';\nimport useSRPanelContext from '../../../../core/Errors/useSRPanelContext';\nimport { SetSRMessagesReturnFn } from '../../../../core/Errors/SRPanelProvider';\nimport { handlePartialAddressMode, lookupBlurBasedErrors, mapFieldKey } from './utils';\nimport { usePrevious } from '../../../../utils/hookUtils';\nimport { SetSRMessagesReturnObject, SortedErrorObject } from '../../../../core/Errors/types';\nimport { ERROR_ACTION_BLUR_SCENARIO, ERROR_ACTION_FOCUS_FIELD } from '../../../../core/Errors/constants';\nimport { setFocusOnFirstField } from './handlers';\nimport { getArrayDifferences } from '../../../../utils/arrayUtils';\n\nconst useSRPanelForCardInputErrors = ({ errors, props, isValidating, retrieveLayout, specifications, billingAddress, sfp }) => {\n // Extract fns from context\n const { setSRMessagesFromObjects, setSRMessagesFromStrings, clearSRPanel, shouldMoveFocusSR } = useSRPanelContext();\n\n // Generate a setSRMessages function - implemented as a partial, since the initial set of arguments don't change.\n const setSRMessages: SetSRMessagesReturnFn = setSRMessagesFromObjects?.({\n fieldTypeMappingFn: mapFieldKey\n });\n\n const partialAddressSchema = handlePartialAddressMode(props.billingAddressMode);\n\n const [sortedErrorList, setSortedErrorList] = useState<SortedErrorObject[]>(null);\n\n // Get the previous list of errors\n const previousSortedErrors = usePrevious(sortedErrorList);\n\n const sfStateErrorsObj = sfp.current?.mapErrorsToValidationRuleResult();\n const mergedErrors = { ...errors, ...sfStateErrorsObj };\n\n useEffect(() => {\n try {\n // Extract and then flatten billingAddress errors into a new object with *all* the field errors at top level\n const { billingAddress: extractedAddressErrors, ...errorsWithoutAddress } = mergedErrors;\n\n const errorsForPanel = { ...errorsWithoutAddress, ...extractedAddressErrors };\n\n // Pass dynamic props (errors, layout etc) to SRPanel via partial\n const srPanelResp: SetSRMessagesReturnObject = setSRMessages?.({\n errors: errorsForPanel,\n isValidating: isValidating.current,\n layout: retrieveLayout(),\n // If we don't have country specific address labels, we might have a label related to a partialAddressSchema (i.e. zipCode)\n countrySpecificLabels: specifications.getAddressLabelsForCountry(billingAddress?.country) ?? partialAddressSchema?.default?.labels\n });\n\n // Store the array of sorted error objects separately so that we can use it to make comparisons between the old and new arrays\n const currentErrorsSortedByLayout = srPanelResp?.currentErrorsSortedByLayout;\n setSortedErrorList(currentErrorsSortedByLayout);\n\n /**\n * Need extra actions after setting SRPanel messages in order to focus field (if required) and because we have some errors that are fired onBlur\n */\n switch (srPanelResp?.action) {\n // A call to focus the first field in error will always follow the call to validate the whole form\n case ERROR_ACTION_FOCUS_FIELD:\n if (shouldMoveFocusSR) setFocusOnFirstField(isValidating.current, sfp, srPanelResp?.fieldToFocus);\n // Remove 'showValidation' mode - allowing time for collation of all the fields in error whilst it is 'showValidation' mode (some errors come in a second render pass)\n setTimeout(() => {\n isValidating.current = false;\n }, 300);\n break;\n\n /**\n * Relates to errors triggered by a field blurring (some pm forms have this, some don't) - check if there is an error to either set or to clear\n */\n case ERROR_ACTION_BLUR_SCENARIO: {\n const difference = getArrayDifferences<SortedErrorObject, string>(currentErrorsSortedByLayout, previousSortedErrors, 'field');\n\n const latestErrorMsg = difference?.[0];\n\n if (latestErrorMsg) {\n // Use the error code to look up whether error is actually a blur based one (most are but some SF ones aren't)\n const isBlurBasedError = lookupBlurBasedErrors(latestErrorMsg.errorCode);\n\n /**\n * ONLY ADD BLUR BASED ERRORS TO THE ERROR PANEL - doing this step prevents the non-blur based errors from being read out twice\n * (once from the aria-live, error panel & once from the aria-describedby element)\n */\n const latestSRError = isBlurBasedError ? latestErrorMsg.errorMessage : null;\n // console.log('### CardInput2::componentDidUpdate:: #2 (not validating) single error:: latestSRError', latestSRError);\n setSRMessagesFromStrings(latestSRError);\n } else {\n // called when previousSortedErrors.length >= currentErrorsSortedByLayout.length\n // console.log('### CardInput2::componentDidUpdate:: #3(not validating) clearing errors:: NO latestErrorMsg');\n clearSRPanel();\n }\n break;\n }\n default:\n break;\n }\n } catch (_) {\n // We don't handle the error related to the sr panel, let it fail silently.\n }\n }, [errors]);\n\n return { sortedErrorList, previousSortedErrors, clearSRPanel };\n};\n\nexport default useSRPanelForCardInputErrors;\n"],"names":["useSRPanelForCardInputErrors","errors","props","isValidating","retrieveLayout","specifications","billingAddress","sfp","setSRMessagesFromObjects","setSRMessagesFromStrings","clearSRPanel","shouldMoveFocusSR","useSRPanelContext","setSRMessages","fieldTypeMappingFn","mapFieldKey","partialAddressSchema","handlePartialAddressMode","billingAddressMode","sortedErrorList","setSortedErrorList","useState","previousSortedErrors","usePrevious","sfStateErrorsObj","current","mapErrorsToValidationRuleResult","mergedErrors","useEffect","extractedAddressErrors","errorsWithoutAddress","errorsForPanel","srPanelResp","layout","countrySpecificLabels","getAddressLabelsForCountry","country","default","labels","currentErrorsSortedByLayout","action","ERROR_ACTION_FOCUS_FIELD","setFocusOnFirstField","fieldToFocus","setTimeout","ERROR_ACTION_BLUR_SCENARIO","difference","getArrayDifferences","latestErrorMsg","latestSRError","lookupBlurBasedErrors","errorCode","errorMessage","_"],"mappings":"giBAUA,MAAMA,EAA+B,EAAGC,SAAQC,QAAOC,eAAcC,iBAAgBC,iBAAgBC,iBAAgBC,UAEjH,MAAMC,yBAAEA,EAAwBC,yBAAEA,EAAwBC,aAAEA,EAAYC,kBAAEA,GAAsBC,IAG1FC,EAAuCL,IAA2B,CACpEM,mBAAoBC,IAGlBC,EAAuBC,EAAyBf,EAAMgB,qBAErDC,EAAiBC,GAAsBC,EAA8B,MAGtEC,EAAuBC,EAAYJ,GAEnCK,EAAmBjB,EAAIkB,SAASC,kCAChCC,EAAe,IAAK1B,KAAWuB,GAqErC,OAnEAI,EAAU,KACN,IAEI,MAAQtB,eAAgBuB,KAA2BC,GAAyBH,EAEtEI,EAAiB,IAAKD,KAAyBD,GAG/CG,EAAyCnB,IAAgB,CAC3DZ,OAAQ8B,EACR5B,aAAcA,EAAasB,QAC3BQ,OAAQ7B,IAER8B,sBAAuB7B,EAAe8B,2BAA2B7B,GAAgB8B,UAAYpB,GAAsBqB,SAASC,SAI1HC,EAA8BP,GAAaO,4BAMjD,OALAnB,EAAmBmB,GAKXP,GAAaQ,QAEjB,KAAKC,EACG9B,GAAmB+B,EAAqBvC,EAAasB,QAASlB,EAAKyB,GAAaW,cAEpFC,WAAW,KACPzC,EAAasB,SAAU,GACxB,KACH,MAKJ,KAAKoB,EAA4B,CAC7B,MAAMC,EAAaC,EAA+CR,EAA6BjB,EAAsB,SAE/G0B,EAAiBF,IAAa,GAEpC,GAAIE,EAAgB,CAEhB,MAMMC,EANmBC,EAAsBF,EAAeG,WAMrBH,EAAeI,aAAe,KAEvE3C,EAAyBwC,EAC7B,MAGIvC,IAEJ,KACJ,EAIR,CAAE,MAAO2C,GAET,GACD,CAACpD,IAEG,CAAEkB,kBAAiBG,uBAAsBZ"}
@@ -1,2 +1,2 @@
1
- import{createElement as t}from"../../external/preact/dist/preact.js";import{UIElement as e}from"../internal/UIElement/UIElement.js";import o from"./defaultProps.js";import{DropinComponent as i}from"./components/DropinComponent.js";import{CoreProvider as n}from"../../core/Context/CoreProvider.js";import{getCommonProps as s}from"./components/utils.js";import r from"./elements/createElements.js";import a from"./elements/createStoredElements.js";import h from"./elements/createInstantPaymentElements.js";import{hasOwnProperty as d}from"../../utils/hasOwnProperty.js";import m from"../../core/Errors/SRPanelProvider.js";import p from"./elements/splitPaymentMethods.js";import{TxVariants as l}from"../tx-variants.js";function c(t,e,o){return e in t?Object.defineProperty(t,e,{value:o,enumerable:!0,configurable:!0,writable:!0}):t[e]=o,t}const y=["paywithgoogle","googlepay","applepay"];class f extends e{storeElementRefOnCore(){this.core.storeElementReference(this)}formatProps(t){return{type:"dropin",...super.formatProps(t),instantPaymentTypes:Array.from(new Set(t.instantPaymentTypes)).filter(t=>y.includes(t))}}get isValid(){return!!this.dropinRef&&!!this.dropinRef.state.activePaymentMethod&&!!this.dropinRef.state.activePaymentMethod.isValid}showValidation(){return this.dropinRef.state.activePaymentMethod&&this.dropinRef.state.activePaymentMethod.showValidation(),this}setStatus(t,e={}){return this.dropinRef?.setStatus(t,e),this}get activePaymentMethod(){return this.dropinRef?.state||this.dropinRef?.state.activePaymentMethod?this.dropinRef.state.activePaymentMethod:null}get data(){return this.activePaymentMethod?this.dropinRef.state.activePaymentMethod.data:null}displayFinalAnimation(t){this.props.disableFinalAnimation||this.dropinRef.setStatus(t)}submit(){if(!this.activePaymentMethod)throw new Error("No active payment method.");this.activePaymentMethod.isValid||this.activePaymentMethod.showValidation(),this.activePaymentMethod.isInstantPayment&&this.closeActivePaymentMethod(),this.activePaymentMethod.submit()}handleAction(t,e={}){if(!t||!t.type){if(d(t,"action")&&d(t,"resultCode"))throw new Error('handleAction::Invalid Action - the passed action object itself has an "action" property and a "resultCode": have you passed in the whole response object by mistake?');throw new Error('handleAction::Invalid Action - the passed action object does not have a "type" property')}if("redirect"!==t.type&&this.activePaymentMethod?.updateWithAction)return this.activePaymentMethod.updateWithAction(t);this.elementRef instanceof f&&(e={...this.elementRef.activePaymentMethod?.props,...e});const o=this.core.createFromAction(t,{...e,elementRef:this.elementRef,onAdditionalDetails:this.handleAdditionalDetails,isDropin:!0});return o?(this.setStatus(o.props.statusType,{component:o}),this.componentFromAction=o,this):null}closeActivePaymentMethod(){this.dropinRef.closeActivePaymentMethod()}handleKeyPress(t){if("Enter"===t.key||"Enter"===t.code){if("radio"===document?.activeElement?.getAttribute("role"))return;super.handleKeyPress(t)}}onEnterKeyPressed(t,e){const o=this.activePaymentMethod??e;this.activePaymentMethod?.onEnterKeyPressed(t,o)}render(){return t(n,{i18n:this.props.i18n,loadingContext:this.props.loadingContext,resources:this.resources},t(m,{srPanel:this.props.modules.srPanel},t(i,{...this.props,core:this.core,elementRef:this.elementRef,onCreateElements:this.handleCreate,ref:t=>{this.dropinRef=t}})))}constructor(t,e){super(t,e),c(this,"dropinRef",null),c(this,"paymentMethodsConfiguration",void 0),c(this,"componentFromAction",void 0),c(this,"handleCreate",()=>{const{paymentMethodsConfiguration:t,showStoredPaymentMethods:e,showPaymentMethods:o,instantPaymentTypes:i}=this.props,{paymentMethods:n,storedPaymentMethods:d,instantPaymentMethods:m,fastlanePaymentMethod:l}=p(this.core.paymentMethodsResponse,i),c=s({...this.props,elementRef:this.elementRef}),y=o?r(n,t,c,this.core):[],f=h(m,t,c,this.core);return[e?a(this.props.filterStoredPaymentMethods?.(d)??d,t,c,this.core):[],y,f,l?r([l],t,c,this.core):[]]}),c(this,"handleOrder",({order:t})=>{this.updateParent({order:t})}),this.submit=this.submit.bind(this),this.handleAction=this.handleAction.bind(this),this.props.paymentMethodComponents.forEach(t=>this.core.register(t)),this.paymentMethodsConfiguration=this.props.paymentMethodsConfiguration||{}}}c(f,"type",l.dropin),c(f,"defaultProps",o);export{f as default};
1
+ import{createElement as t}from"../../external/preact/dist/preact.js";import{UIElement as e}from"../internal/UIElement/UIElement.js";import o from"./defaultProps.js";import{DropinComponent as i}from"./components/DropinComponent.js";import{CoreProvider as n}from"../../core/Context/CoreProvider.js";import{getCommonProps as s}from"./components/utils.js";import r from"./elements/createElements.js";import a from"./elements/createStoredElements.js";import h from"./elements/createInstantPaymentElements.js";import{hasOwnProperty as d}from"../../utils/hasOwnProperty.js";import m from"../../core/Errors/SRPanelProvider.js";import p from"./elements/splitPaymentMethods.js";import{TxVariants as l}from"../tx-variants.js";function c(t,e,o){return e in t?Object.defineProperty(t,e,{value:o,enumerable:!0,configurable:!0,writable:!0}):t[e]=o,t}const y=["paywithgoogle","googlepay","applepay"];class f extends e{storeElementRefOnCore(){this.core.storeElementReference(this)}formatProps(t){return{type:"dropin",...super.formatProps(t),instantPaymentTypes:Array.from(new Set(t.instantPaymentTypes)).filter(t=>y.includes(t))}}get isValid(){return!!this.dropinRef&&!!this.dropinRef.state.activePaymentMethod&&!!this.dropinRef.state.activePaymentMethod.isValid}showValidation(){return this.dropinRef.state.activePaymentMethod&&this.dropinRef.state.activePaymentMethod.showValidation(),this}setStatus(t,e={}){return this.dropinRef?.setStatus(t,e),this}get activePaymentMethod(){return this.dropinRef?.state||this.dropinRef?.state.activePaymentMethod?this.dropinRef.state.activePaymentMethod:null}get data(){return this.activePaymentMethod?this.dropinRef.state.activePaymentMethod.data:null}displayFinalAnimation(t){this.props.disableFinalAnimation||this.dropinRef?.setStatus(t)}submit(){if(!this.activePaymentMethod)throw new Error("No active payment method.");this.activePaymentMethod.isValid||this.activePaymentMethod.showValidation(),this.activePaymentMethod.isInstantPayment&&this.closeActivePaymentMethod(),this.activePaymentMethod.submit()}handleAction(t,e={}){if(!t||!t.type){if(d(t,"action")&&d(t,"resultCode"))throw new Error('handleAction::Invalid Action - the passed action object itself has an "action" property and a "resultCode": have you passed in the whole response object by mistake?');throw new Error('handleAction::Invalid Action - the passed action object does not have a "type" property')}if("redirect"!==t.type&&this.activePaymentMethod?.updateWithAction)return this.activePaymentMethod.updateWithAction(t);this.elementRef instanceof f&&(e={...this.elementRef.activePaymentMethod?.props,...e});const o=this.core.createFromAction(t,{...e,elementRef:this.elementRef,onAdditionalDetails:this.handleAdditionalDetails,isDropin:!0});return o?(this.setStatus(o.props.statusType,{component:o}),this.componentFromAction=o,this):null}closeActivePaymentMethod(){this.dropinRef.closeActivePaymentMethod()}handleKeyPress(t){if("Enter"===t.key||"Enter"===t.code){if("radio"===document?.activeElement?.getAttribute("role"))return;super.handleKeyPress(t)}}onEnterKeyPressed(t,e){const o=this.activePaymentMethod??e;this.activePaymentMethod?.onEnterKeyPressed(t,o)}render(){return t(n,{i18n:this.props.i18n,loadingContext:this.props.loadingContext,resources:this.resources},t(m,{srPanel:this.props.modules.srPanel},t(i,{...this.props,core:this.core,elementRef:this.elementRef,onCreateElements:this.handleCreate,ref:t=>{this.dropinRef=t}})))}constructor(t,e){super(t,e),c(this,"dropinRef",null),c(this,"paymentMethodsConfiguration",void 0),c(this,"componentFromAction",void 0),c(this,"handleCreate",()=>{const{paymentMethodsConfiguration:t,showStoredPaymentMethods:e,showPaymentMethods:o,instantPaymentTypes:i}=this.props,{paymentMethods:n,storedPaymentMethods:d,instantPaymentMethods:m,fastlanePaymentMethod:l}=p(this.core.paymentMethodsResponse,i),c=s({...this.props,elementRef:this.elementRef}),y=o?r(n,t,c,this.core):[],f=h(m,t,c,this.core);return[e?a(this.props.filterStoredPaymentMethods?.(d)??d,t,c,this.core):[],y,f,l?r([l],t,c,this.core):[]]}),c(this,"handleOrder",({order:t})=>{this.updateParent({order:t})}),this.submit=this.submit.bind(this),this.handleAction=this.handleAction.bind(this),this.props.paymentMethodComponents.forEach(t=>this.core.register(t)),this.paymentMethodsConfiguration=this.props.paymentMethodsConfiguration||{}}}c(f,"type",l.dropin),c(f,"defaultProps",o);export{f as default};
2
2
  //# sourceMappingURL=Dropin.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Dropin.js","sources":["../../../../src/components/Dropin/Dropin.tsx"],"sourcesContent":["import { h } from 'preact';\nimport UIElement from '../internal/UIElement/UIElement';\nimport defaultProps from './defaultProps';\nimport DropinComponent from '../../components/Dropin/components/DropinComponent';\nimport { CoreProvider } from '../../core/Context/CoreProvider';\nimport { getCommonProps } from './components/utils';\nimport { createElements, createStoredElements } from './elements';\nimport createInstantPaymentElements from './elements/createInstantPaymentElements';\nimport { hasOwnProperty } from '../../utils/hasOwnProperty';\nimport SRPanelProvider from '../../core/Errors/SRPanelProvider';\nimport splitPaymentMethods from './elements/splitPaymentMethods';\nimport { TxVariants } from '../tx-variants';\n\nimport type { DropinConfiguration, InstantPaymentTypes, PaymentMethodsConfiguration } from './types';\nimport type { PaymentAction, PaymentResponseData } from '../../types/global-types';\nimport type { ICore } from '../../core/types';\nimport type { IDropin } from './types';\n\nconst SUPPORTED_INSTANT_PAYMENTS = ['paywithgoogle', 'googlepay', 'applepay'];\n\nclass DropinElement extends UIElement<DropinConfiguration> implements IDropin {\n public static type = TxVariants.dropin;\n\n protected static defaultProps = defaultProps;\n\n public dropinRef = null;\n\n private paymentMethodsConfiguration: PaymentMethodsConfiguration;\n /**\n * Reference to the component created from `handleAction` (Ex.: ThreeDS2Challenge)\n */\n public componentFromAction?: UIElement;\n\n constructor(checkout: ICore, props?: DropinConfiguration) {\n super(checkout, props);\n this.submit = this.submit.bind(this);\n this.handleAction = this.handleAction.bind(this);\n\n this.props.paymentMethodComponents.forEach(PaymentMethod => this.core.register(PaymentMethod));\n this.paymentMethodsConfiguration = this.props.paymentMethodsConfiguration || {};\n }\n\n protected override storeElementRefOnCore() {\n this.core.storeElementReference(this);\n }\n\n formatProps(props) {\n return {\n type: 'dropin', // for analytics\n ...super.formatProps(props),\n instantPaymentTypes: Array.from<InstantPaymentTypes>(new Set(props.instantPaymentTypes)).filter(value =>\n SUPPORTED_INSTANT_PAYMENTS.includes(value)\n )\n };\n }\n\n get isValid() {\n return !!this.dropinRef && !!this.dropinRef.state.activePaymentMethod && !!this.dropinRef.state.activePaymentMethod.isValid;\n }\n\n showValidation() {\n if (this.dropinRef.state.activePaymentMethod) {\n this.dropinRef.state.activePaymentMethod.showValidation();\n }\n\n return this;\n }\n\n public setStatus(status, props = {}): this {\n this.dropinRef?.setStatus(status, props);\n return this;\n }\n\n get activePaymentMethod() {\n if (!this.dropinRef?.state && !this.dropinRef?.state.activePaymentMethod) {\n return null;\n }\n\n return this.dropinRef.state.activePaymentMethod;\n }\n\n get data() {\n if (!this.activePaymentMethod) {\n return null;\n }\n\n return this.dropinRef.state.activePaymentMethod.data;\n }\n\n public displayFinalAnimation(type: 'success' | 'error') {\n if (this.props.disableFinalAnimation) return;\n\n this.dropinRef.setStatus(type);\n }\n\n /**\n * Calls the onSubmit event with the state of the activePaymentMethod\n */\n public override submit(): void {\n if (!this.activePaymentMethod) {\n throw new Error('No active payment method.');\n }\n\n if (!this.activePaymentMethod.isValid) {\n this.activePaymentMethod.showValidation();\n }\n\n if (this.activePaymentMethod.isInstantPayment) {\n this.closeActivePaymentMethod();\n }\n\n this.activePaymentMethod.submit();\n }\n\n /**\n * Creates the Drop-in elements\n */\n private handleCreate = () => {\n const { paymentMethodsConfiguration, showStoredPaymentMethods, showPaymentMethods, instantPaymentTypes } = this.props;\n\n const { paymentMethods, storedPaymentMethods, instantPaymentMethods, fastlanePaymentMethod } = splitPaymentMethods(\n this.core.paymentMethodsResponse,\n instantPaymentTypes\n );\n\n const commonProps = getCommonProps({ ...this.props, elementRef: this.elementRef });\n\n const elements = showPaymentMethods ? createElements(paymentMethods, paymentMethodsConfiguration, commonProps, this.core) : [];\n const instantPaymentElements = createInstantPaymentElements(instantPaymentMethods, paymentMethodsConfiguration, commonProps, this.core);\n const storedElements = showStoredPaymentMethods\n ? createStoredElements(\n this.props.filterStoredPaymentMethods?.(storedPaymentMethods) ?? storedPaymentMethods,\n paymentMethodsConfiguration,\n commonProps,\n this.core\n )\n : [];\n const fastlanePaymentElement = fastlanePaymentMethod\n ? createElements([fastlanePaymentMethod], paymentMethodsConfiguration, commonProps, this.core)\n : [];\n\n return [storedElements, elements, instantPaymentElements, fastlanePaymentElement];\n };\n\n public handleAction(action: PaymentAction, props = {}): this | null {\n if (!action || !action.type) {\n if (hasOwnProperty(action, 'action') && hasOwnProperty(action, 'resultCode')) {\n throw new Error(\n 'handleAction::Invalid Action - the passed action object itself has an \"action\" property and ' +\n 'a \"resultCode\": have you passed in the whole response object by mistake?'\n );\n }\n throw new Error('handleAction::Invalid Action - the passed action object does not have a \"type\" property');\n }\n\n if (action.type !== 'redirect' && this.activePaymentMethod?.updateWithAction) {\n return this.activePaymentMethod.updateWithAction(action);\n }\n\n if (this.elementRef instanceof DropinElement) {\n props = {\n ...this.elementRef.activePaymentMethod?.props,\n ...props\n };\n }\n\n const paymentAction: UIElement = this.core.createFromAction(action, {\n ...props,\n elementRef: this.elementRef, // maintain elementRef for 3DS2 flow\n onAdditionalDetails: this.handleAdditionalDetails,\n isDropin: true\n });\n\n if (paymentAction) {\n this.setStatus(paymentAction.props.statusType, { component: paymentAction });\n this.componentFromAction = paymentAction;\n return this;\n }\n\n return null;\n }\n\n /**\n * handleOrder is implemented so we don't trigger a callback like in the components\n * @param response - PaymentResponse\n */\n protected handleOrder = ({ order }: PaymentResponseData): void => {\n void this.updateParent({ order });\n };\n\n closeActivePaymentMethod() {\n this.dropinRef.closeActivePaymentMethod();\n }\n\n protected handleKeyPress(e: h.JSX.TargetedKeyboardEvent<HTMLInputElement> | KeyboardEvent) {\n if (e.key === 'Enter' || e.code === 'Enter') {\n // If the active element has role=\"radio\", we're on a header in the PMList, in which case we don't want to validate the form, or, prevent the default behaviour\n const isPMHeader = document?.activeElement?.getAttribute('role') === 'radio';\n if (isPMHeader) {\n return;\n }\n super.handleKeyPress(e);\n }\n }\n\n protected onEnterKeyPressed(activeElement: Element, component: UIElement) {\n // We want to have a ref to the activePM, if we can; not a ref to the Dropin\n const pmComponent = this.activePaymentMethod ?? component;\n this.activePaymentMethod?.onEnterKeyPressed(activeElement, pmComponent);\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 <DropinComponent\n {...this.props}\n core={this.core}\n elementRef={this.elementRef}\n onCreateElements={this.handleCreate}\n ref={dropinRef => {\n this.dropinRef = dropinRef;\n }}\n />\n </SRPanelProvider>\n </CoreProvider>\n );\n }\n}\n\nexport default DropinElement;\n"],"names":["SUPPORTED_INSTANT_PAYMENTS","DropinElement","UIElement","storeElementRefOnCore","this","core","storeElementReference","formatProps","props","type","super","instantPaymentTypes","Array","from","Set","filter","value","includes","isValid","dropinRef","state","activePaymentMethod","showValidation","setStatus","status","data","displayFinalAnimation","disableFinalAnimation","submit","Error","isInstantPayment","closeActivePaymentMethod","handleAction","action","hasOwnProperty","updateWithAction","elementRef","paymentAction","createFromAction","onAdditionalDetails","handleAdditionalDetails","isDropin","statusType","component","componentFromAction","handleKeyPress","e","key","code","document","activeElement","getAttribute","onEnterKeyPressed","pmComponent","render","h","CoreProvider","i18n","loadingContext","resources","SRPanelProvider","srPanel","modules","DropinComponent","onCreateElements","handleCreate","ref","constructor","checkout","_define_property","paymentMethodsConfiguration","showStoredPaymentMethods","showPaymentMethods","paymentMethods","storedPaymentMethods","instantPaymentMethods","fastlanePaymentMethod","splitPaymentMethods","paymentMethodsResponse","commonProps","getCommonProps","elements","createElements","instantPaymentElements","createInstantPaymentElements","createStoredElements","filterStoredPaymentMethods","handleOrder","order","updateParent","bind","paymentMethodComponents","forEach","PaymentMethod","register","TxVariants","dropin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,GATpB6D,EAAAjE,KAAOe,YAAY,MAEnBkD,EAAAjE,KAAQkE,mCAAR,GAIAD,EAAAjE,KAAOwC,2BAAP,GAsFAyB,OAAQJ,eAAe,KACnB,MAAMK,4BAAEA,EAA2BC,yBAAEA,EAAwBC,mBAAEA,EAAkB7D,oBAAEA,GAAwBP,KAAKI,OAE1GiE,eAAEA,EAAcC,qBAAEA,EAAoBC,sBAAEA,EAAqBC,sBAAEA,GAA0BC,EAC3FzE,KAAKC,KAAKyE,uBACVnE,GAGEoE,EAAcC,EAAe,IAAK5E,KAAKI,MAAO4B,WAAYhC,KAAKgC,aAE/D6C,EAAWT,EAAqBU,EAAeT,EAAgBH,EAA6BS,EAAa3E,KAAKC,MAAQ,GACtH8E,EAAyBC,EAA6BT,EAAuBL,EAA6BS,EAAa3E,KAAKC,MAalI,MAAO,CAZgBkE,EACjBc,EACIjF,KAAKI,MAAM8E,6BAA6BZ,IAAyBA,EACjEJ,EACAS,EACA3E,KAAKC,MAET,GAKkB4E,EAAUE,EAJHP,EACzBM,EAAe,CAACN,GAAwBN,EAA6BS,EAAa3E,KAAKC,MACvF,MA+CVgE,EAAAjE,KAAUmF,cAAc,EAAGC,YAClBpF,KAAKqF,aAAa,CAAED,YAxJzBpF,KAAKwB,OAASxB,KAAKwB,OAAO8D,KAAKtF,MAC/BA,KAAK4B,aAAe5B,KAAK4B,aAAa0D,KAAKtF,MAE3CA,KAAKI,MAAMmF,wBAAwBC,QAAQC,GAAiBzF,KAAKC,KAAKyF,SAASD,IAC/EzF,KAAKkE,4BAA8BlE,KAAKI,MAAM8D,6BAA+B,CAAA,CACjF,EAnBAD,EADEpE,EACYQ,OAAOsF,EAAWC,QAEhC3B,EAHEpE,EAGegG,eAAeA"}
1
+ {"version":3,"file":"Dropin.js","sources":["../../../../src/components/Dropin/Dropin.tsx"],"sourcesContent":["import { h } from 'preact';\nimport UIElement from '../internal/UIElement/UIElement';\nimport defaultProps from './defaultProps';\nimport DropinComponent from '../../components/Dropin/components/DropinComponent';\nimport { CoreProvider } from '../../core/Context/CoreProvider';\nimport { getCommonProps } from './components/utils';\nimport { createElements, createStoredElements } from './elements';\nimport createInstantPaymentElements from './elements/createInstantPaymentElements';\nimport { hasOwnProperty } from '../../utils/hasOwnProperty';\nimport SRPanelProvider from '../../core/Errors/SRPanelProvider';\nimport splitPaymentMethods from './elements/splitPaymentMethods';\nimport { TxVariants } from '../tx-variants';\n\nimport type { DropinConfiguration, InstantPaymentTypes, PaymentMethodsConfiguration } from './types';\nimport type { PaymentAction, PaymentResponseData } from '../../types/global-types';\nimport type { ICore } from '../../core/types';\nimport type { IDropin } from './types';\n\nconst SUPPORTED_INSTANT_PAYMENTS = ['paywithgoogle', 'googlepay', 'applepay'];\n\nclass DropinElement extends UIElement<DropinConfiguration> implements IDropin {\n public static type = TxVariants.dropin;\n\n protected static defaultProps = defaultProps;\n\n public dropinRef = null;\n\n private paymentMethodsConfiguration: PaymentMethodsConfiguration;\n /**\n * Reference to the component created from `handleAction` (Ex.: ThreeDS2Challenge)\n */\n public componentFromAction?: UIElement;\n\n constructor(checkout: ICore, props?: DropinConfiguration) {\n super(checkout, props);\n this.submit = this.submit.bind(this);\n this.handleAction = this.handleAction.bind(this);\n\n this.props.paymentMethodComponents.forEach(PaymentMethod => this.core.register(PaymentMethod));\n this.paymentMethodsConfiguration = this.props.paymentMethodsConfiguration || {};\n }\n\n protected override storeElementRefOnCore() {\n this.core.storeElementReference(this);\n }\n\n formatProps(props) {\n return {\n type: 'dropin', // for analytics\n ...super.formatProps(props),\n instantPaymentTypes: Array.from<InstantPaymentTypes>(new Set(props.instantPaymentTypes)).filter(value =>\n SUPPORTED_INSTANT_PAYMENTS.includes(value)\n )\n };\n }\n\n get isValid() {\n return !!this.dropinRef && !!this.dropinRef.state.activePaymentMethod && !!this.dropinRef.state.activePaymentMethod.isValid;\n }\n\n showValidation() {\n if (this.dropinRef.state.activePaymentMethod) {\n this.dropinRef.state.activePaymentMethod.showValidation();\n }\n\n return this;\n }\n\n public setStatus(status, props = {}): this {\n this.dropinRef?.setStatus(status, props);\n return this;\n }\n\n get activePaymentMethod() {\n if (!this.dropinRef?.state && !this.dropinRef?.state.activePaymentMethod) {\n return null;\n }\n\n return this.dropinRef.state.activePaymentMethod;\n }\n\n get data() {\n if (!this.activePaymentMethod) {\n return null;\n }\n\n return this.dropinRef.state.activePaymentMethod.data;\n }\n\n public displayFinalAnimation(type: 'success' | 'error') {\n if (this.props.disableFinalAnimation) return;\n\n this.dropinRef?.setStatus(type);\n }\n\n /**\n * Calls the onSubmit event with the state of the activePaymentMethod\n */\n public override submit(): void {\n if (!this.activePaymentMethod) {\n throw new Error('No active payment method.');\n }\n\n if (!this.activePaymentMethod.isValid) {\n this.activePaymentMethod.showValidation();\n }\n\n if (this.activePaymentMethod.isInstantPayment) {\n this.closeActivePaymentMethod();\n }\n\n this.activePaymentMethod.submit();\n }\n\n /**\n * Creates the Drop-in elements\n */\n private handleCreate = () => {\n const { paymentMethodsConfiguration, showStoredPaymentMethods, showPaymentMethods, instantPaymentTypes } = this.props;\n\n const { paymentMethods, storedPaymentMethods, instantPaymentMethods, fastlanePaymentMethod } = splitPaymentMethods(\n this.core.paymentMethodsResponse,\n instantPaymentTypes\n );\n\n const commonProps = getCommonProps({ ...this.props, elementRef: this.elementRef });\n\n const elements = showPaymentMethods ? createElements(paymentMethods, paymentMethodsConfiguration, commonProps, this.core) : [];\n const instantPaymentElements = createInstantPaymentElements(instantPaymentMethods, paymentMethodsConfiguration, commonProps, this.core);\n const storedElements = showStoredPaymentMethods\n ? createStoredElements(\n this.props.filterStoredPaymentMethods?.(storedPaymentMethods) ?? storedPaymentMethods,\n paymentMethodsConfiguration,\n commonProps,\n this.core\n )\n : [];\n const fastlanePaymentElement = fastlanePaymentMethod\n ? createElements([fastlanePaymentMethod], paymentMethodsConfiguration, commonProps, this.core)\n : [];\n\n return [storedElements, elements, instantPaymentElements, fastlanePaymentElement];\n };\n\n public handleAction(action: PaymentAction, props = {}): this | null {\n if (!action || !action.type) {\n if (hasOwnProperty(action, 'action') && hasOwnProperty(action, 'resultCode')) {\n throw new Error(\n 'handleAction::Invalid Action - the passed action object itself has an \"action\" property and ' +\n 'a \"resultCode\": have you passed in the whole response object by mistake?'\n );\n }\n throw new Error('handleAction::Invalid Action - the passed action object does not have a \"type\" property');\n }\n\n if (action.type !== 'redirect' && this.activePaymentMethod?.updateWithAction) {\n return this.activePaymentMethod.updateWithAction(action);\n }\n\n if (this.elementRef instanceof DropinElement) {\n props = {\n ...this.elementRef.activePaymentMethod?.props,\n ...props\n };\n }\n\n const paymentAction: UIElement = this.core.createFromAction(action, {\n ...props,\n elementRef: this.elementRef, // maintain elementRef for 3DS2 flow\n onAdditionalDetails: this.handleAdditionalDetails,\n isDropin: true\n });\n\n if (paymentAction) {\n this.setStatus(paymentAction.props.statusType, { component: paymentAction });\n this.componentFromAction = paymentAction;\n return this;\n }\n\n return null;\n }\n\n /**\n * handleOrder is implemented so we don't trigger a callback like in the components\n * @param response - PaymentResponse\n */\n protected handleOrder = ({ order }: PaymentResponseData): void => {\n void this.updateParent({ order });\n };\n\n closeActivePaymentMethod() {\n this.dropinRef.closeActivePaymentMethod();\n }\n\n protected handleKeyPress(e: h.JSX.TargetedKeyboardEvent<HTMLInputElement> | KeyboardEvent) {\n if (e.key === 'Enter' || e.code === 'Enter') {\n // If the active element has role=\"radio\", we're on a header in the PMList, in which case we don't want to validate the form, or, prevent the default behaviour\n const isPMHeader = document?.activeElement?.getAttribute('role') === 'radio';\n if (isPMHeader) {\n return;\n }\n super.handleKeyPress(e);\n }\n }\n\n protected onEnterKeyPressed(activeElement: Element, component: UIElement) {\n // We want to have a ref to the activePM, if we can; not a ref to the Dropin\n const pmComponent = this.activePaymentMethod ?? component;\n this.activePaymentMethod?.onEnterKeyPressed(activeElement, pmComponent);\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 <DropinComponent\n {...this.props}\n core={this.core}\n elementRef={this.elementRef}\n onCreateElements={this.handleCreate}\n ref={dropinRef => {\n this.dropinRef = dropinRef;\n }}\n />\n </SRPanelProvider>\n </CoreProvider>\n );\n }\n}\n\nexport default DropinElement;\n"],"names":["SUPPORTED_INSTANT_PAYMENTS","DropinElement","UIElement","storeElementRefOnCore","this","core","storeElementReference","formatProps","props","type","super","instantPaymentTypes","Array","from","Set","filter","value","includes","isValid","dropinRef","state","activePaymentMethod","showValidation","setStatus","status","data","displayFinalAnimation","disableFinalAnimation","submit","Error","isInstantPayment","closeActivePaymentMethod","handleAction","action","hasOwnProperty","updateWithAction","elementRef","paymentAction","createFromAction","onAdditionalDetails","handleAdditionalDetails","isDropin","statusType","component","componentFromAction","handleKeyPress","e","key","code","document","activeElement","getAttribute","onEnterKeyPressed","pmComponent","render","h","CoreProvider","i18n","loadingContext","resources","SRPanelProvider","srPanel","modules","DropinComponent","onCreateElements","handleCreate","ref","constructor","checkout","_define_property","paymentMethodsConfiguration","showStoredPaymentMethods","showPaymentMethods","paymentMethods","storedPaymentMethods","instantPaymentMethods","fastlanePaymentMethod","splitPaymentMethods","paymentMethodsResponse","commonProps","getCommonProps","elements","createElements","instantPaymentElements","createInstantPaymentElements","createStoredElements","filterStoredPaymentMethods","handleOrder","order","updateParent","bind","paymentMethodComponents","forEach","PaymentMethod","register","TxVariants","dropin","defaultProps"],"mappings":"m0BAkBA,MAAMA,EAA6B,CAAC,gBAAiB,YAAa,YAElE,MAAMC,UAAsBC,EAsBLC,qBAAAA,GACfC,KAAKC,KAAKC,sBAAsBF,KACpC,CAEAG,WAAAA,CAAYC,GACR,MAAO,CACHC,KAAM,YACHC,MAAMH,YAAYC,GACrBG,oBAAqBC,MAAMC,KAA0B,IAAIC,IAAIN,EAAMG,sBAAsBI,OAAOC,GAC5FhB,EAA2BiB,SAASD,IAGhD,CAEA,WAAIE,GACA,QAASd,KAAKe,aAAef,KAAKe,UAAUC,MAAMC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B,WAAYhC,KAAKgC,aAE/D6C,EAAWT,EAAqBU,EAAeT,EAAgBH,EAA6BS,EAAa3E,KAAKC,MAAQ,GACtH8E,EAAyBC,EAA6BT,EAAuBL,EAA6BS,EAAa3E,KAAKC,MAalI,MAAO,CAZgBkE,EACjBc,EACIjF,KAAKI,MAAM8E,6BAA6BZ,IAAyBA,EACjEJ,EACAS,EACA3E,KAAKC,MAET,GAKkB4E,EAAUE,EAJHP,EACzBM,EAAe,CAACN,GAAwBN,EAA6BS,EAAa3E,KAAKC,MACvF,MA+CVgE,EAAAjE,KAAUmF,cAAc,EAAGC,YAClBpF,KAAKqF,aAAa,CAAED,YAxJzBpF,KAAKwB,OAASxB,KAAKwB,OAAO8D,KAAKtF,MAC/BA,KAAK4B,aAAe5B,KAAK4B,aAAa0D,KAAKtF,MAE3CA,KAAKI,MAAMmF,wBAAwBC,QAAQC,GAAiBzF,KAAKC,KAAKyF,SAASD,IAC/EzF,KAAKkE,4BAA8BlE,KAAKI,MAAM8D,6BAA+B,CAAA,CACjF,EAnBAD,EADEpE,EACYQ,OAAOsF,EAAWC,QAEhC3B,EAHEpE,EAGegG,eAAeA"}
@@ -1 +1 @@
1
- {"version":3,"file":"useSRPanelForGiftcardErrors.js","sources":["../../../../../src/components/Giftcard/components/useSRPanelForGiftcardErrors.ts"],"sourcesContent":["import { useEffect, useState } from 'preact/hooks';\nimport { SetSRMessagesReturnObject } from '../../../core/Errors/types';\nimport useSRPanelContext from '../../../core/Errors/useSRPanelContext';\nimport { usePrevious } from '../../../utils/hookUtils';\nimport { ERROR_ACTION_BLUR_SCENARIO, ERROR_ACTION_FOCUS_FIELD } from '../../../core/Errors/constants';\nimport { getArrayDifferences } from '../../../utils/arrayUtils';\nimport { SetSRMessagesReturnFn } from '../../../core/Errors/SRPanelProvider';\nimport SecuredFieldsProvider from '../../internal/SecuredFields/SFP/SecuredFieldsProvider';\n\n/**\n * Interface for transformed error objects returned from mapErrorsToValidationRuleResult\n */\ninterface TransformedError {\n isValid: boolean;\n errorMessage: string;\n errorI18n: string;\n error: string;\n rootNode: HTMLElement;\n}\n\n/**\n * Interface for errors object with transformed error entries\n */\ninterface TransformedErrorsObj {\n [key: string]: TransformedError | null;\n}\n\n/**\n * Props interface for the error handling hook\n */\ninterface UseSRPanelForGiftcardErrorsProps {\n errors: TransformedErrorsObj;\n isValidating: boolean;\n sfp: SecuredFieldsProvider;\n}\n\n/**\n * Interface for sorted error objects used for comparison\n */\ninterface SortedErrorObject {\n field: string;\n errorMessage: string;\n}\n\n/**\n * Custom hook for handling gift card component errors and screen reader announcements\n *\n * This hook manages both visual and screen reader error announcements for the gift card component,\n * handling both blur-based validation errors and form-wide validation errors.\n */\nconst useSRPanelForGiftcardErrors = ({ errors, isValidating, sfp }: UseSRPanelForGiftcardErrorsProps) => {\n // Track sorted list of errors for comparison with previous state\n const [sortedErrorList, setSortedErrorList] = useState<SortedErrorObject[]>(null);\n // Track previous error list for detecting changes\n const previousSortedErrors = usePrevious(sortedErrorList);\n\n // Get SRPanel context for managing screen reader messages\n const { setSRMessagesFromObjects, setSRMessagesFromStrings, clearSRPanel, shouldMoveFocusSR } = useSRPanelContext();\n\n // Fixed layout array defining the order of fields for error sorting\n // Assume fields in this order, and adds encryptedExpiryDate for MealVoucher, this is ignored in giftcard\n const layout = ['encryptedCardNumber', 'encryptedExpiryDate', 'encryptedSecurityCode'];\n\n useEffect(() => {\n try {\n // Create a partial function for setting SR messages with fixed configuration\n const setMessages: SetSRMessagesReturnFn = setSRMessagesFromObjects?.({});\n // Set messages with current errors and layout\n\n // Unlike Card SR Panel, isValidating is a boolean\n const srPanelResp: SetSRMessagesReturnObject = setMessages?.({\n errors,\n isValidating,\n layout\n });\n\n // Store the sorted list of errors for comparison\n const currentErrorsSortedByLayout = srPanelResp?.currentErrorsSortedByLayout;\n setSortedErrorList(currentErrorsSortedByLayout);\n\n // Handle different error scenarios based on the action type\n switch (srPanelResp?.action) {\n case ERROR_ACTION_FOCUS_FIELD:\n // When a field needs to be focused due to validation error\n if (shouldMoveFocusSR) {\n sfp?.setFocusOn(srPanelResp?.fieldToFocus);\n }\n // Remove 'showValidation' mode - allowing time for collation of all the fields in error whilst it is 'showValidation' mode (some errors come in a second render pass)\n setTimeout(() => {\n if (typeof isValidating === 'boolean') {\n isValidating = false;\n }\n }, 300);\n break;\n\n case ERROR_ACTION_BLUR_SCENARIO: {\n // Handle blur-based validation errors\n const difference = getArrayDifferences(currentErrorsSortedByLayout, previousSortedErrors, 'field');\n const latestErrorMsg = difference?.[0];\n\n if (latestErrorMsg) {\n // Only announce blur-based errors to screen reader\n const isBlurBasedError = true;\n const latestSRError = isBlurBasedError ? latestErrorMsg.errorMessage : null;\n setSRMessagesFromStrings(latestSRError);\n } else {\n // Clear SR panel if there are no more errors\n clearSRPanel();\n }\n break;\n }\n }\n } catch (_) {\n // Fail silently - we don't want to break the component if SRPanel fails\n }\n }, [errors]);\n};\n\n// Export all interfaces and the hook\nexport type { TransformedError, TransformedErrorsObj };\n\nexport { useSRPanelForGiftcardErrors };\n"],"names":["useSRPanelForGiftcardErrors","errors","isValidating","sfp","sortedErrorList","setSortedErrorList","useState","previousSortedErrors","usePrevious","setSRMessagesFromObjects","setSRMessagesFromStrings","clearSRPanel","shouldMoveFocusSR","useSRPanelContext","layout","useEffect","setMessages","srPanelResp","currentErrorsSortedByLayout","action","ERROR_ACTION_FOCUS_FIELD","setFocusOn","fieldToFocus","setTimeout","ERROR_ACTION_BLUR_SCENARIO","difference","getArrayDifferences","latestErrorMsg","latestSRError","errorMessage","_"],"mappings":"0XAkDA,MAAMA,EAA8B,EAAGC,SAAQC,eAAcC,UAEzD,MAAOC,EAAiBC,GAAsBC,EAA8B,MAEtEC,EAAuBC,EAAYJ,IAGnCK,yBAAEA,EAAwBC,yBAAEA,EAAwBC,aAAEA,EAAYC,kBAAEA,GAAsBC,IAI1FC,EAAS,CAAC,sBAAuB,sBAAuB,yBAE9DC,EAAU,KACN,IAEI,MAAMC,EAAqCP,IAA2B,IAIhEQ,EAAyCD,IAAc,CACzDf,SACAC,eACAY,WAIEI,EAA8BD,GAAaC,4BAIjD,OAHAb,EAAmBa,GAGXD,GAAaE,QACjB,KAAKC,EAEGR,GACAT,GAAKkB,WAAWJ,GAAaK,cAGjCC,WAAW,KACqB,kBAAjBrB,IACPA,GAAe,IAEpB,KACH,MAEJ,KAAKsB,EAA4B,CAE7B,MAAMC,EAAaC,EAAoBR,EAA6BX,EAAsB,SACpFoB,EAAiBF,IAAa,GAEpC,GAAIE,EAAgB,CAEhB,MACMC,GADmB,EACgBD,EAAeE,aAAe,KACvEnB,EAAyBkB,QAGzBjB,IAEJ,KACJ,EAER,CAAE,MAAOmB,GAET,GACD,CAAC7B"}
1
+ {"version":3,"file":"useSRPanelForGiftcardErrors.js","sources":["../../../../../src/components/Giftcard/components/useSRPanelForGiftcardErrors.ts"],"sourcesContent":["import { useEffect, useState } from 'preact/hooks';\nimport { SetSRMessagesReturnObject } from '../../../core/Errors/types';\nimport useSRPanelContext from '../../../core/Errors/useSRPanelContext';\nimport { usePrevious } from '../../../utils/hookUtils';\nimport { ERROR_ACTION_BLUR_SCENARIO, ERROR_ACTION_FOCUS_FIELD } from '../../../core/Errors/constants';\nimport { getArrayDifferences } from '../../../utils/arrayUtils';\nimport { SetSRMessagesReturnFn } from '../../../core/Errors/SRPanelProvider';\nimport SecuredFieldsProvider from '../../internal/SecuredFields/SFP/SecuredFieldsProvider';\n\n/**\n * Interface for transformed error objects returned from mapErrorsToValidationRuleResult\n */\ninterface TransformedError {\n isValid: boolean;\n errorMessage: string;\n errorI18n: string;\n error: string;\n rootNode: HTMLElement;\n}\n\n/**\n * Interface for errors object with transformed error entries\n */\ninterface TransformedErrorsObj {\n [key: string]: TransformedError | null;\n}\n\n/**\n * Props interface for the error handling hook\n */\ninterface UseSRPanelForGiftcardErrorsProps {\n errors: TransformedErrorsObj;\n isValidating: boolean;\n sfp: SecuredFieldsProvider;\n}\n\n/**\n * Interface for sorted error objects used for comparison\n */\ninterface SortedErrorObject {\n field: string;\n errorMessage: string;\n}\n\n/**\n * Custom hook for handling gift card component errors and screen reader announcements\n *\n * This hook manages both visual and screen reader error announcements for the gift card component,\n * handling both blur-based validation errors and form-wide validation errors.\n */\nconst useSRPanelForGiftcardErrors = ({ errors, isValidating, sfp }: UseSRPanelForGiftcardErrorsProps) => {\n // Track sorted list of errors for comparison with previous state\n const [sortedErrorList, setSortedErrorList] = useState<SortedErrorObject[]>(null);\n // Track previous error list for detecting changes\n const previousSortedErrors = usePrevious(sortedErrorList);\n\n // Get SRPanel context for managing screen reader messages\n const { setSRMessagesFromObjects, setSRMessagesFromStrings, clearSRPanel, shouldMoveFocusSR } = useSRPanelContext();\n\n // Fixed layout array defining the order of fields for error sorting\n // Assume fields in this order, and adds encryptedExpiryDate for MealVoucher, this is ignored in giftcard\n const layout = ['encryptedCardNumber', 'encryptedExpiryDate', 'encryptedSecurityCode'];\n\n useEffect(() => {\n try {\n // Create a partial function for setting SR messages with fixed configuration\n const setMessages: SetSRMessagesReturnFn = setSRMessagesFromObjects?.({});\n // Set messages with current errors and layout\n\n // Unlike Card SR Panel, isValidating is a boolean\n const srPanelResp: SetSRMessagesReturnObject = setMessages?.({\n errors,\n isValidating,\n layout\n });\n\n // Store the sorted list of errors for comparison\n const currentErrorsSortedByLayout = srPanelResp?.currentErrorsSortedByLayout;\n setSortedErrorList(currentErrorsSortedByLayout);\n\n // Handle different error scenarios based on the action type\n switch (srPanelResp?.action) {\n case ERROR_ACTION_FOCUS_FIELD:\n // When a field needs to be focused due to validation error\n if (shouldMoveFocusSR) {\n sfp?.setFocusOn(srPanelResp?.fieldToFocus);\n }\n // Remove 'showValidation' mode - allowing time for collation of all the fields in error whilst it is 'showValidation' mode (some errors come in a second render pass)\n setTimeout(() => {\n if (typeof isValidating === 'boolean') {\n isValidating = false;\n }\n }, 300);\n break;\n\n case ERROR_ACTION_BLUR_SCENARIO: {\n // Handle blur-based validation errors\n const difference = getArrayDifferences(currentErrorsSortedByLayout, previousSortedErrors, 'field');\n const latestErrorMsg = difference?.[0];\n\n if (latestErrorMsg) {\n // Only announce blur-based errors to screen reader\n const isBlurBasedError = true;\n const latestSRError = isBlurBasedError ? latestErrorMsg.errorMessage : null;\n setSRMessagesFromStrings(latestSRError);\n } else {\n // Clear SR panel if there are no more errors\n clearSRPanel();\n }\n break;\n }\n }\n } catch (_) {\n // Fail silently - we don't want to break the component if SRPanel fails\n }\n }, [errors]);\n};\n\n// Export all interfaces and the hook\nexport type { TransformedError, TransformedErrorsObj };\n\nexport { useSRPanelForGiftcardErrors };\n"],"names":["useSRPanelForGiftcardErrors","errors","isValidating","sfp","sortedErrorList","setSortedErrorList","useState","previousSortedErrors","usePrevious","setSRMessagesFromObjects","setSRMessagesFromStrings","clearSRPanel","shouldMoveFocusSR","useSRPanelContext","layout","useEffect","setMessages","srPanelResp","currentErrorsSortedByLayout","action","ERROR_ACTION_FOCUS_FIELD","setFocusOn","fieldToFocus","setTimeout","ERROR_ACTION_BLUR_SCENARIO","difference","getArrayDifferences","latestErrorMsg","latestSRError","errorMessage","_"],"mappings":"0XAkDA,MAAMA,EAA8B,EAAGC,SAAQC,eAAcC,UAEzD,MAAOC,EAAiBC,GAAsBC,EAA8B,MAEtEC,EAAuBC,EAAYJ,IAGnCK,yBAAEA,EAAwBC,yBAAEA,EAAwBC,aAAEA,EAAYC,kBAAEA,GAAsBC,IAI1FC,EAAS,CAAC,sBAAuB,sBAAuB,yBAE9DC,EAAU,KACN,IAEI,MAAMC,EAAqCP,IAA2B,IAIhEQ,EAAyCD,IAAc,CACzDf,SACAC,eACAY,WAIEI,EAA8BD,GAAaC,4BAIjD,OAHAb,EAAmBa,GAGXD,GAAaE,QACjB,KAAKC,EAEGR,GACAT,GAAKkB,WAAWJ,GAAaK,cAGjCC,WAAW,KACqB,kBAAjBrB,IACPA,GAAe,IAEpB,KACH,MAEJ,KAAKsB,EAA4B,CAE7B,MAAMC,EAAaC,EAAoBR,EAA6BX,EAAsB,SACpFoB,EAAiBF,IAAa,GAEpC,GAAIE,EAAgB,CAEhB,MACMC,GADmB,EACgBD,EAAeE,aAAe,KACvEnB,EAAyBkB,EAC7B,MAEIjB,IAEJ,KACJ,EAER,CAAE,MAAOmB,GAET,GACD,CAAC7B"}
@@ -1 +1 @@
1
- {"version":3,"file":"get-paypal-styles.js","sources":["../../../../../src/components/PayPal/utils/get-paypal-styles.ts"],"sourcesContent":["import { SUPPORTED_COLORS_FOR_CREDIT } from '../config';\nimport type { FundingSource } from '../types';\n\n/**\n * Processes and returns a new style object.\n */\nexport const getStyle = (fundingSource: FundingSource, style = {}) => {\n if (fundingSource === 'paypal') return { ...style };\n\n return Object.keys(style).reduce((acc, prop) => {\n const value = style[prop];\n if (prop !== 'color' || SUPPORTED_COLORS_FOR_CREDIT.includes(value)) {\n acc[prop] = value;\n }\n return acc;\n }, {});\n};\n"],"names":["getStyle","fundingSource","style","Object","keys","reduce","acc","prop","value","SUPPORTED_COLORS_FOR_CREDIT","includes"],"mappings":"2DAMO,MAAMA,EAAW,CAACC,EAA8BC,EAAQ,CAAA,IACrC,WAAlBD,EAAmC,IAAKC,GAErCC,OAAOC,KAAKF,GAAOG,OAAO,CAACC,EAAKC,KACnC,MAAMC,EAAQN,EAAMK,GAIpB,OAHa,UAATA,GAAoBE,EAA4BC,SAASF,MACzDF,EAAIC,GAAQC,GAETF,GACR"}
1
+ {"version":3,"file":"get-paypal-styles.js","sources":["../../../../../src/components/PayPal/utils/get-paypal-styles.ts"],"sourcesContent":["import { SUPPORTED_COLORS_FOR_CREDIT } from '../config';\nimport type { FundingSource } from '../types';\n\n/**\n * Processes and returns a new style object.\n */\nexport const getStyle = (fundingSource: FundingSource, style = {}) => {\n if (fundingSource === 'paypal') return { ...style };\n\n return Object.keys(style).reduce((acc, prop) => {\n const value = style[prop];\n if (prop !== 'color' || SUPPORTED_COLORS_FOR_CREDIT.includes(value)) {\n acc[prop] = value;\n }\n return acc;\n }, {});\n};\n"],"names":["getStyle","fundingSource","style","Object","keys","reduce","acc","prop","value","SUPPORTED_COLORS_FOR_CREDIT","includes"],"mappings":"2DAMO,MAAMA,EAAW,CAACC,EAA8BC,EAAQ,CAAA,IACrC,WAAlBD,EAAmC,IAAKC,GAErCC,OAAOC,KAAKF,GAAOG,OAAO,CAACC,EAAKC,KACnC,MAAMC,EAAQN,EAAMK,GAIpB,OAHa,UAATA,GAAoBE,EAA4BC,SAASF,MACzDF,EAAIC,GAAQC,GAETF,GACR,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"FastlaneSDK.js","sources":["../../../../src/components/PayPalFastlane/FastlaneSDK.ts"],"sourcesContent":["import { resolveEnvironments } from '../../core/Environment';\nimport requestFastlaneToken from './services/request-fastlane-token';\nimport { convertAdyenLocaleToFastlaneLocale } from './utils/convert-locale';\nimport Script from '../../utils/Script';\nimport AdyenCheckoutError from '../../core/Errors/AdyenCheckoutError';\nimport type {\n FastlanePaymentMethodConfiguration,\n FastlaneWindowInstance,\n FastlaneAuthenticatedCustomerResult,\n FastlaneShippingAddressSelectorResult,\n FastlaneSDKConfiguration,\n FastlaneConsentRenderState\n} from './types';\nimport type { FastlaneTokenData } from './services/request-fastlane-token';\n\nclass FastlaneSDK {\n private readonly clientKey: string;\n private readonly checkoutShopperURL: string;\n private readonly locale: string;\n private readonly forceConsentDetails: boolean;\n\n private fastlaneSdk?: FastlaneWindowInstance;\n private latestShopperDetails?: { email: string; customerId: string };\n private fastlaneSessionId?: string;\n\n constructor(configuration: FastlaneSDKConfiguration) {\n if (!configuration?.environment) throw new AdyenCheckoutError('IMPLEMENTATION_ERROR', \"FastlaneSDK: 'environment' property is required\");\n if (!configuration?.clientKey) throw new AdyenCheckoutError('IMPLEMENTATION_ERROR', \"FastlaneSDK: 'clientKey' property is required\");\n\n if (configuration.forceConsentDetails && configuration.environment.includes('live'))\n console.warn(\"Fastlane SDK: 'forceConsentDetails' should not be used on 'live' environment\");\n\n const { apiUrl } = resolveEnvironments(configuration.environment);\n\n this.checkoutShopperURL = apiUrl;\n this.clientKey = configuration.clientKey;\n this.forceConsentDetails = configuration.forceConsentDetails || false;\n this.locale = convertAdyenLocaleToFastlaneLocale(configuration.locale || 'en-US');\n }\n\n /**\n * Initializes the Fastlane SDK\n */\n public async initialize(): Promise<FastlaneSDK> {\n const tokenData = await this.requestClientToken();\n await this.fetchSdk(tokenData.value, tokenData.clientId);\n await this.initializeFastlaneInstance();\n return this;\n }\n\n /**\n * Triggers the authentication for Fastlane using shopper's email.\n * If shopper is recognized, the OTP flow is initialized.\n *\n * @param email\n */\n public async authenticate(email: string): Promise<FastlaneAuthenticatedCustomerResult> {\n if (!this.fastlaneSdk) {\n throw new AdyenCheckoutError('IMPLEMENTATION_ERROR', 'authenticate(): Fastlane SDK is not initialized');\n }\n\n const { customerContextId } = await this.fastlaneSdk.identity.lookupCustomerByEmail(email);\n\n if (customerContextId) {\n this.latestShopperDetails = { email, customerId: customerContextId };\n return this.fastlaneSdk.identity.triggerAuthenticationFlow(customerContextId);\n } else {\n return {\n authenticationState: 'not_found',\n profileData: undefined\n };\n }\n }\n\n /**\n * Creates the Adyen Component configuration based on the Fastlane authentication result.\n *\n * In case the shopper authenticated successfully, it returns config to be used in the Fastlane component\n * Otherwise, it returns the configuration to be used in the Card component\n *\n * @param authResult\n */\n public async getComponentConfiguration(authResult: FastlaneAuthenticatedCustomerResult): Promise<FastlanePaymentMethodConfiguration> {\n if (!authResult) {\n throw new AdyenCheckoutError(\n 'IMPLEMENTATION_ERROR',\n 'FastlaneSDK: you must pass the authentication result to get the component configuration'\n );\n }\n\n if (authResult.authenticationState === 'succeeded') {\n const hasCard = !!authResult.profileData?.card;\n\n if (!hasCard) {\n throw new AdyenCheckoutError('ERROR', 'getComponentConfiguration(): There is no card associated with the authenticated profile');\n }\n\n return {\n paymentType: 'fastlane',\n configuration: {\n fastlaneSessionId: this.fastlaneSessionId,\n email: this.latestShopperDetails.email,\n tokenId: authResult.profileData.card.id,\n lastFour: authResult.profileData.card.paymentSource.card.lastDigits,\n brand: authResult.profileData.card.paymentSource.card.brand.toLowerCase()\n }\n };\n } else {\n const consentDetails = await this.fetchConsentDetails();\n return {\n paymentType: 'card',\n configuration: {\n ...(consentDetails && {\n fastlaneConfiguration: {\n fastlaneSessionId: this.fastlaneSessionId,\n ...consentDetails\n }\n })\n }\n };\n }\n }\n\n /**\n * Displays the Fastlane Shipping Address selector UI\n */\n public showShippingAddressSelector(): Promise<FastlaneShippingAddressSelectorResult> {\n return this.fastlaneSdk.profile.showShippingAddressSelector();\n }\n\n /**\n * Render the \"Fastlane by PayPal\" logo in the specified HTML container\n */\n public async mountWatermark(container: HTMLElement | string, options = { includeAdditionalInfo: true }): Promise<void> {\n const component = await this.fastlaneSdk.FastlaneWatermarkComponent(options);\n component.render(container);\n }\n\n private requestClientToken(): Promise<FastlaneTokenData> {\n return requestFastlaneToken(this.checkoutShopperURL, this.clientKey);\n }\n\n private async fetchSdk(clientToken: string, clientId: string): Promise<void> {\n const url = `https://www.paypal.com/sdk/js?client-id=${clientId}&components=buttons,fastlane`;\n const script = new Script(url, 'body', {}, { sdkClientToken: clientToken });\n\n await script.load();\n }\n\n /**\n * Fetch the fastlane session ID used internally by PayPal for Network Token Usage event\n * This ID is not critical for the payment processing part\n *\n * @private\n */\n private async fetchSessionIdAsync(): Promise<void> {\n try {\n const { sessionId } = await this.fastlaneSdk.identity.getSession();\n this.fastlaneSessionId = sessionId;\n } catch (error) {\n console.warn('Fastlane SDK: Failed to fetch session ID', error);\n }\n }\n\n /**\n * Fetch object containing that details that will be used to display the sign-up UI\n * inside the card component\n * @private\n */\n private async fetchConsentDetails(): Promise<FastlaneConsentRenderState> {\n try {\n const consentComponent = await this.fastlaneSdk.ConsentComponent();\n return await consentComponent.getRenderState();\n } catch (error) {\n throw new AdyenCheckoutError('ERROR', 'fetchConsentDetails(): failed to fetch consent details', { cause: error });\n }\n }\n\n private async initializeFastlaneInstance(): Promise<void> {\n try {\n this.fastlaneSdk = await window.paypal.Fastlane({\n intendedExperience: 'externalProcessorCustomConsent',\n ...(this.forceConsentDetails && {\n metadata: {\n geoLocOverride: 'US'\n }\n })\n });\n this.fastlaneSdk.setLocale(this.locale);\n\n void this.fetchSessionIdAsync();\n } catch (error) {\n throw new AdyenCheckoutError('ERROR', 'Fastlane SDK: Failed to initialize fastlane using the window.paypal.Fastlane constructor', {\n cause: error\n });\n }\n }\n}\n\nexport default FastlaneSDK;\n"],"names":["FastlaneSDK","initialize","tokenData","this","requestClientToken","fetchSdk","value","clientId","initializeFastlaneInstance","authenticate","email","fastlaneSdk","AdyenCheckoutError","customerContextId","identity","lookupCustomerByEmail","latestShopperDetails","customerId","triggerAuthenticationFlow","authenticationState","profileData","undefined","getComponentConfiguration","authResult","card","paymentType","configuration","fastlaneSessionId","tokenId","id","lastFour","paymentSource","lastDigits","brand","toLowerCase","consentDetails","fetchConsentDetails","fastlaneConfiguration","showShippingAddressSelector","profile","mountWatermark","container","options","includeAdditionalInfo","FastlaneWatermarkComponent","render","requestFastlaneToken","checkoutShopperURL","clientKey","clientToken","script","Script","sdkClientToken","load","fetchSessionIdAsync","sessionId","getSession","error","console","warn","consentComponent","ConsentComponent","getRenderState","cause","window","paypal","Fastlane","intendedExperience","forceConsentDetails","metadata","geoLocOverride","setLocale","locale","constructor","_define_property","environment","includes","apiUrl","resolveEnvironments","convertAdyenLocaleToFastlaneLocale"],"mappings":"maAeA,MAAMA,EA4BF,gBAAaC,GACT,MAAMC,QAAkBC,KAAKC,qBAG7B,aAFMD,KAAKE,SAASH,EAAUI,MAAOJ,EAAUK,gBACzCJ,KAAKK,6BACJL,IACX,CAQA,kBAAaM,CAAaC,GACtB,IAAKP,KAAKQ,YACN,MAAM,IAAIC,EAAmB,uBAAwB,mDAGzD,MAAMC,kBAAEA,SAA4BV,KAAKQ,YAAYG,SAASC,sBAAsBL,GAEpF,OAAIG,GACAV,KAAKa,qBAAuB,CAAEN,QAAOO,WAAYJ,GAC1CV,KAAKQ,YAAYG,SAASI,0BAA0B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,EAAiBE,gBAClC,CAAE,MAAOL,GACL,MAAM,IAAI7C,EAAmB,QAAS,yDAA0D,CAAEmD,MAAON,GAC7G,CACJ,CAEA,gCAAcjD,GACV,IACIL,KAAKQ,kBAAoBqD,OAAOC,OAAOC,SAAS,CAC5CC,mBAAoB,oCAChBhE,KAAKiE,qBAAuB,CAC5BC,SAAU,CACNC,eAAgB,SAI5BnE,KAAKQ,YAAY4D,UAAUpE,KAAKqE,QAE3BrE,KAAKmD,qBACd,CAAE,MAAOG,GACL,MAAM,IAAI7C,EAAmB,QAAS,2FAA4F,CAC9HmD,MAAON,GAEf,CACJ,CA3KA,WAAAgB,CAAY/C,GACR,GAVJgD,EAAAvE,KAAiB6C,iBAAjB,GACA0B,EAAAvE,KAAiB4C,0BAAjB,GACA2B,EAAAvE,KAAiBqE,cAAjB,GACAE,EAAAvE,KAAiBiE,2BAAjB,GAEAM,EAAAvE,KAAQQ,mBAAR,GACA+D,EAAAvE,KAAQa,4BAAR,GACA0D,EAAAvE,KAAQwB,yBAAR,IAGSD,GAAeiD,YAAa,MAAM,IAAI/D,EAAmB,uBAAwB,mDACtF,IAAKc,GAAesB,UAAW,MAAM,IAAIpC,EAAmB,uBAAwB,iDAEhFc,EAAc0C,qBAAuB1C,EAAciD,YAAYC,SAAS,SACxElB,QAAQC,KAAK,gFAEjB,MAAMkB,OAAEA,GAAWC,EAAoBpD,EAAciD,aAErDxE,KAAK4C,mBAAqB8B,EAC1B1E,KAAK6C,UAAYtB,EAAcsB,UAC/B7C,KAAKiE,oBAAsB1C,EAAc0C,sBAAuB,EAChEjE,KAAKqE,OAASO,EAAmCrD,EAAc8C,QAAU,QAC7E"}
1
+ {"version":3,"file":"FastlaneSDK.js","sources":["../../../../src/components/PayPalFastlane/FastlaneSDK.ts"],"sourcesContent":["import { resolveEnvironments } from '../../core/Environment';\nimport requestFastlaneToken from './services/request-fastlane-token';\nimport { convertAdyenLocaleToFastlaneLocale } from './utils/convert-locale';\nimport Script from '../../utils/Script';\nimport AdyenCheckoutError from '../../core/Errors/AdyenCheckoutError';\nimport type {\n FastlanePaymentMethodConfiguration,\n FastlaneWindowInstance,\n FastlaneAuthenticatedCustomerResult,\n FastlaneShippingAddressSelectorResult,\n FastlaneSDKConfiguration,\n FastlaneConsentRenderState\n} from './types';\nimport type { FastlaneTokenData } from './services/request-fastlane-token';\n\nclass FastlaneSDK {\n private readonly clientKey: string;\n private readonly checkoutShopperURL: string;\n private readonly locale: string;\n private readonly forceConsentDetails: boolean;\n\n private fastlaneSdk?: FastlaneWindowInstance;\n private latestShopperDetails?: { email: string; customerId: string };\n private fastlaneSessionId?: string;\n\n constructor(configuration: FastlaneSDKConfiguration) {\n if (!configuration?.environment) throw new AdyenCheckoutError('IMPLEMENTATION_ERROR', \"FastlaneSDK: 'environment' property is required\");\n if (!configuration?.clientKey) throw new AdyenCheckoutError('IMPLEMENTATION_ERROR', \"FastlaneSDK: 'clientKey' property is required\");\n\n if (configuration.forceConsentDetails && configuration.environment.includes('live'))\n console.warn(\"Fastlane SDK: 'forceConsentDetails' should not be used on 'live' environment\");\n\n const { apiUrl } = resolveEnvironments(configuration.environment);\n\n this.checkoutShopperURL = apiUrl;\n this.clientKey = configuration.clientKey;\n this.forceConsentDetails = configuration.forceConsentDetails || false;\n this.locale = convertAdyenLocaleToFastlaneLocale(configuration.locale || 'en-US');\n }\n\n /**\n * Initializes the Fastlane SDK\n */\n public async initialize(): Promise<FastlaneSDK> {\n const tokenData = await this.requestClientToken();\n await this.fetchSdk(tokenData.value, tokenData.clientId);\n await this.initializeFastlaneInstance();\n return this;\n }\n\n /**\n * Triggers the authentication for Fastlane using shopper's email.\n * If shopper is recognized, the OTP flow is initialized.\n *\n * @param email\n */\n public async authenticate(email: string): Promise<FastlaneAuthenticatedCustomerResult> {\n if (!this.fastlaneSdk) {\n throw new AdyenCheckoutError('IMPLEMENTATION_ERROR', 'authenticate(): Fastlane SDK is not initialized');\n }\n\n const { customerContextId } = await this.fastlaneSdk.identity.lookupCustomerByEmail(email);\n\n if (customerContextId) {\n this.latestShopperDetails = { email, customerId: customerContextId };\n return this.fastlaneSdk.identity.triggerAuthenticationFlow(customerContextId);\n } else {\n return {\n authenticationState: 'not_found',\n profileData: undefined\n };\n }\n }\n\n /**\n * Creates the Adyen Component configuration based on the Fastlane authentication result.\n *\n * In case the shopper authenticated successfully, it returns config to be used in the Fastlane component\n * Otherwise, it returns the configuration to be used in the Card component\n *\n * @param authResult\n */\n public async getComponentConfiguration(authResult: FastlaneAuthenticatedCustomerResult): Promise<FastlanePaymentMethodConfiguration> {\n if (!authResult) {\n throw new AdyenCheckoutError(\n 'IMPLEMENTATION_ERROR',\n 'FastlaneSDK: you must pass the authentication result to get the component configuration'\n );\n }\n\n if (authResult.authenticationState === 'succeeded') {\n const hasCard = !!authResult.profileData?.card;\n\n if (!hasCard) {\n throw new AdyenCheckoutError('ERROR', 'getComponentConfiguration(): There is no card associated with the authenticated profile');\n }\n\n return {\n paymentType: 'fastlane',\n configuration: {\n fastlaneSessionId: this.fastlaneSessionId,\n email: this.latestShopperDetails.email,\n tokenId: authResult.profileData.card.id,\n lastFour: authResult.profileData.card.paymentSource.card.lastDigits,\n brand: authResult.profileData.card.paymentSource.card.brand.toLowerCase()\n }\n };\n } else {\n const consentDetails = await this.fetchConsentDetails();\n return {\n paymentType: 'card',\n configuration: {\n ...(consentDetails && {\n fastlaneConfiguration: {\n fastlaneSessionId: this.fastlaneSessionId,\n ...consentDetails\n }\n })\n }\n };\n }\n }\n\n /**\n * Displays the Fastlane Shipping Address selector UI\n */\n public showShippingAddressSelector(): Promise<FastlaneShippingAddressSelectorResult> {\n return this.fastlaneSdk.profile.showShippingAddressSelector();\n }\n\n /**\n * Render the \"Fastlane by PayPal\" logo in the specified HTML container\n */\n public async mountWatermark(container: HTMLElement | string, options = { includeAdditionalInfo: true }): Promise<void> {\n const component = await this.fastlaneSdk.FastlaneWatermarkComponent(options);\n component.render(container);\n }\n\n private requestClientToken(): Promise<FastlaneTokenData> {\n return requestFastlaneToken(this.checkoutShopperURL, this.clientKey);\n }\n\n private async fetchSdk(clientToken: string, clientId: string): Promise<void> {\n const url = `https://www.paypal.com/sdk/js?client-id=${clientId}&components=buttons,fastlane`;\n const script = new Script(url, 'body', {}, { sdkClientToken: clientToken });\n\n await script.load();\n }\n\n /**\n * Fetch the fastlane session ID used internally by PayPal for Network Token Usage event\n * This ID is not critical for the payment processing part\n *\n * @private\n */\n private async fetchSessionIdAsync(): Promise<void> {\n try {\n const { sessionId } = await this.fastlaneSdk.identity.getSession();\n this.fastlaneSessionId = sessionId;\n } catch (error) {\n console.warn('Fastlane SDK: Failed to fetch session ID', error);\n }\n }\n\n /**\n * Fetch object containing that details that will be used to display the sign-up UI\n * inside the card component\n * @private\n */\n private async fetchConsentDetails(): Promise<FastlaneConsentRenderState> {\n try {\n const consentComponent = await this.fastlaneSdk.ConsentComponent();\n return await consentComponent.getRenderState();\n } catch (error) {\n throw new AdyenCheckoutError('ERROR', 'fetchConsentDetails(): failed to fetch consent details', { cause: error });\n }\n }\n\n private async initializeFastlaneInstance(): Promise<void> {\n try {\n this.fastlaneSdk = await window.paypal.Fastlane({\n intendedExperience: 'externalProcessorCustomConsent',\n ...(this.forceConsentDetails && {\n metadata: {\n geoLocOverride: 'US'\n }\n })\n });\n this.fastlaneSdk.setLocale(this.locale);\n\n void this.fetchSessionIdAsync();\n } catch (error) {\n throw new AdyenCheckoutError('ERROR', 'Fastlane SDK: Failed to initialize fastlane using the window.paypal.Fastlane constructor', {\n cause: error\n });\n }\n }\n}\n\nexport default FastlaneSDK;\n"],"names":["FastlaneSDK","initialize","tokenData","this","requestClientToken","fetchSdk","value","clientId","initializeFastlaneInstance","authenticate","email","fastlaneSdk","AdyenCheckoutError","customerContextId","identity","lookupCustomerByEmail","latestShopperDetails","customerId","triggerAuthenticationFlow","authenticationState","profileData","undefined","getComponentConfiguration","authResult","card","paymentType","configuration","fastlaneSessionId","tokenId","id","lastFour","paymentSource","lastDigits","brand","toLowerCase","consentDetails","fetchConsentDetails","fastlaneConfiguration","showShippingAddressSelector","profile","mountWatermark","container","options","includeAdditionalInfo","FastlaneWatermarkComponent","render","requestFastlaneToken","checkoutShopperURL","clientKey","clientToken","script","Script","sdkClientToken","load","fetchSessionIdAsync","sessionId","getSession","error","console","warn","consentComponent","ConsentComponent","getRenderState","cause","window","paypal","Fastlane","intendedExperience","forceConsentDetails","metadata","geoLocOverride","setLocale","locale","constructor","_define_property","environment","includes","apiUrl","resolveEnvironments","convertAdyenLocaleToFastlaneLocale"],"mappings":"maAeA,MAAMA,EA4BF,gBAAaC,GACT,MAAMC,QAAkBC,KAAKC,qBAG7B,aAFMD,KAAKE,SAASH,EAAUI,MAAOJ,EAAUK,gBACzCJ,KAAKK,6BACJL,IACX,CAQA,kBAAaM,CAAaC,GACtB,IAAKP,KAAKQ,YACN,MAAM,IAAIC,EAAmB,uBAAwB,mDAGzD,MAAMC,kBAAEA,SAA4BV,KAAKQ,YAAYG,SAASC,sBAAsBL,GAEpF,OAAIG,GACAV,KAAKa,qBAAuB,CAAEN,QAAOO,WAAYJ,GAC1CV,KAAKQ,YAAYG,SAASI,0BAA0BL,IAEpD,CACHM,oBAAqB,YACrBC,iBAAaC,EAGzB,CAUA,+BAAaC,CAA0BC,GACnC,IAAKA,EACD,MAAM,IAAIX,EACN,uBACA,2FAIR,GAAuC,cAAnCW,EAAWJ,oBAAqC,CAGhD,MAFkBI,EAAWH,aAAaI,KAGtC,MAAM,IAAIZ,EAAmB,QAAS,2FAG1C,MAAO,CACHa,YAAa,WACbC,cAAe,CACXC,kBAAmBxB,KAAKwB,kBACxBjB,MAAOP,KAAKa,qBAAqBN,MACjCkB,QAASL,EAAWH,YAAYI,KAAKK,GACrCC,SAAUP,EAAWH,YAAYI,KAAKO,cAAcP,KAAKQ,WACzDC,MAAOV,EAAWH,YAAYI,KAAKO,cAAcP,KAAKS,MAAMC,eAGxE,CAAO,CACH,MAAMC,QAAuBhC,KAAKiC,sBAClC,MAAO,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jB,GACAE,EAAAvE,KAAiBiE,2BAAjB,GAEAM,EAAAvE,KAAQQ,mBAAR,GACA+D,EAAAvE,KAAQa,4BAAR,GACA0D,EAAAvE,KAAQwB,yBAAR,IAGSD,GAAeiD,YAAa,MAAM,IAAI/D,EAAmB,uBAAwB,mDACtF,IAAKc,GAAesB,UAAW,MAAM,IAAIpC,EAAmB,uBAAwB,iDAEhFc,EAAc0C,qBAAuB1C,EAAciD,YAAYC,SAAS,SACxElB,QAAQC,KAAK,gFAEjB,MAAMkB,OAAEA,GAAWC,EAAoBpD,EAAciD,aAErDxE,KAAK4C,mBAAqB8B,EAC1B1E,KAAK6C,UAAYtB,EAAcsB,UAC/B7C,KAAKiE,oBAAsB1C,EAAc0C,sBAAuB,EAChEjE,KAAKqE,OAASO,EAAmCrD,EAAc8C,QAAU,QAC7E"}
@@ -1 +1 @@
1
- {"version":3,"file":"PrepareChallenge3DS2.js","sources":["../../../../../../src/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.tsx"],"sourcesContent":["import { Component, h } from 'preact';\nimport DoChallenge3DS2 from './DoChallenge3DS2';\nimport { createChallengeResolveData, prepareChallengeData, createOldChallengeResolveData, isErrorObject } from '../utils';\nimport { PrepareChallenge3DS2Props, PrepareChallenge3DS2State, StatusErrorInfoObject } from './types';\nimport { ChallengeData, ResultObject, ThreeDS2FlowObject, ErrorCodeObject } from '../../types';\nimport '../../ThreeDS2.scss';\nimport Img from '../../../internal/Img';\nimport './challenge.scss';\nimport { hasOwnProperty } from '../../../../utils/hasOwnProperty';\nimport useImage from '../../../../core/Context/useImage';\nimport AdyenCheckoutError, { ERROR } from '../../../../core/Errors/AdyenCheckoutError';\nimport { THREEDS2_CHALLENGE, THREEDS2_CHALLENGE_ERROR, THREEDS2_FULL, THREEDS2_NUM, MISSING_TOKEN_IN_ACTION_MSG } from '../../constants';\nimport { isValidHttpUrl } from '../../../../utils/isValidURL';\nimport { ANALYTICS_ERROR_TYPE, Analytics3DS2Errors, Analytics3DS2Events } from '../../../../core/Analytics/constants';\nimport { ErrorObject } from '../../../../core/Errors/types';\nimport { AnalyticsLogEvent } from '../../../../core/Analytics/AnalyticsLogEvent';\nimport { AnalyticsErrorEvent } from '../../../../core/Analytics/AnalyticsErrorEvent';\nimport { AnalyticsEvent } from '../../../../core/Analytics/AnalyticsEvent';\n\nclass PrepareChallenge3DS2 extends Component<PrepareChallenge3DS2Props, PrepareChallenge3DS2State> {\n public static defaultProps = {\n onComplete: () => {},\n onError: () => {},\n isMDFlow: false\n };\n\n constructor(props) {\n super(props);\n\n if (this.props.token) {\n const challengeData: ChallengeData | ErrorObject = prepareChallengeData({\n token: this.props.token,\n size: this.props.challengeWindowSize || this.props.size // TODO confirm that this.props.size is legacy and can be removed\n });\n\n this.state = {\n status: 'init',\n challengeData: challengeData as ChallengeData\n };\n } else {\n // Will be picked up in componentDidMount\n this.state = { challengeData: { success: false, error: MISSING_TOKEN_IN_ACTION_MSG } };\n\n console.debug(`${THREEDS2_CHALLENGE_ERROR}: ${MISSING_TOKEN_IN_ACTION_MSG}`);\n }\n }\n\n public onFormSubmit = (msg: string) => {\n const event = new AnalyticsLogEvent({\n type: THREEDS2_FULL,\n message: msg,\n subType: Analytics3DS2Events.CHALLENGE_DATA_SENT\n });\n\n this.props.onSubmitAnalytics(event);\n };\n\n componentDidMount() {\n const hasChallengeData = !isErrorObject(this.state.challengeData);\n\n if (hasChallengeData) {\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 challengeData\n */\n const { acsURL } = this.state.challengeData as ChallengeData;\n const hasValidAcsURL = isValidHttpUrl(acsURL, shouldAllowHttpDomains);\n\n // Only render component if we have an acsURL.\n if (!hasValidAcsURL) {\n // Set UI error & call onError callback\n this.setError(\n {\n errorInfo: `${Analytics3DS2Errors.TOKEN_IS_MISSING_ACSURL}: ${this.props.i18n.get('err.gen.9102')}` //\n },\n true\n );\n\n // Send error to analytics endpoint // TODO - check logs to see if this *ever* happens\n const event = new AnalyticsErrorEvent({\n code: Analytics3DS2Errors.TOKEN_IS_MISSING_ACSURL,\n errorType: ANALYTICS_ERROR_TYPE.apiError,\n message: `${THREEDS2_CHALLENGE_ERROR}: Decoded token is missing a valid acsURL property`\n });\n this.props.onSubmitAnalytics(event);\n\n console.debug('### PrepareChallenge3DS2::exiting:: no valid acsURL');\n return;\n }\n\n const { acsTransID, messageVersion, threeDSServerTransID } = (this.state.challengeData as ChallengeData).cReqData;\n\n // Only render component if we have a acsTransID, messageVersion & threeDSServerTransID\n if (!acsTransID || !messageVersion || !threeDSServerTransID) {\n // Set UI error & call onError callback\n this.setError(\n {\n errorInfo: `${Analytics3DS2Errors.TOKEN_IS_MISSING_OTHER_PROPS}: ${this.props.i18n.get('err.gen.9102')}`\n // errorObj: this.state.challengeData // TODO Decide if we want to expose this data\n },\n true\n );\n\n // Send error to analytics endpoint // TODO - check logs to see if this *ever* happens\n const event = new AnalyticsErrorEvent({\n code: Analytics3DS2Errors.TOKEN_IS_MISSING_OTHER_PROPS,\n errorType: ANALYTICS_ERROR_TYPE.apiError,\n message: `${THREEDS2_CHALLENGE_ERROR}: Decoded token is missing one or more of the following properties (acsTransID | messageVersion | threeDSServerTransID)`\n });\n this.props.onSubmitAnalytics(event);\n\n console.debug(\n '### PrepareChallenge3DS2::exiting:: missing one or more of the following properties (acsTransID | messageVersion | threeDSServerTransID)'\n );\n return;\n }\n\n // Proceed to allow component to render\n this.setState({ status: 'performingChallenge' });\n //\n } else {\n const errorMsg: string = (this.state.challengeData 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 // Set UI error & call onError callback\n this.setError(\n {\n errorInfo:\n errorMsg.indexOf(MISSING_TOKEN_IN_ACTION_MSG) > -1\n ? `${Analytics3DS2Errors.ACTION_IS_MISSING_TOKEN}: ${this.props.i18n.get('err.gen.9102')}`\n : `${Analytics3DS2Errors.TOKEN_DECODE_OR_PARSING_FAILED}: ${this.props.i18n.get('err.gen.9102')}`\n // errorObj: this.state.challengeData // TODO Decide if we want to expose this data\n },\n true\n );\n\n // Send error to analytics endpoint // TODO - check logs to see if the base64 decoding errors *ever* happen\n const event = new AnalyticsErrorEvent({\n code: errorCode,\n errorType: ANALYTICS_ERROR_TYPE.apiError,\n message: `${THREEDS2_CHALLENGE_ERROR}: ${errorMsg}` // can be: 'Missing \"token\" property from threeDS2 action', 'not base64', 'malformed URI sequence' or 'Could not JSON parse token'\n });\n\n this.props.onSubmitAnalytics(event);\n\n console.debug('### PrepareChallenge3DS2::exiting:: no challengeData');\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 ? createOldChallengeResolveData : createChallengeResolveData;\n const data = resolveDataFunction(this.props.dataKey, resultObj.transStatus, this.props.paymentData);\n\n if (errorCodeObject) {\n console.debug('### PrepareChallenge3DS2::errorCodeObject::', errorCodeObject);\n }\n\n let event: AnalyticsEvent;\n\n /** Are we in an \"error\" i.e. timeout or no transStatus, 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 : Analytics3DS2Errors.NO_TRANSSTATUS,\n errorType: finalResObject.errorCode === 'timeout' ? ANALYTICS_ERROR_TYPE.network : ANALYTICS_ERROR_TYPE.apiError\n };\n\n // Challenge process has timed out,\n // or, It's an error reported by the backend 'cos no transStatus could be retrieved // TODO - check logs to see if this *ever* happens\n\n event = new AnalyticsErrorEvent({\n message: (finalResObject as ErrorCodeObject).message,\n ...errorTypeAndCode\n });\n\n // Send error to analytics endpoint\n this.props.onSubmitAnalytics(event);\n }\n\n /** Calculate \"result\" for analytics */\n let result: string;\n\n switch (resultObj?.transStatus) {\n case 'Y':\n result = 'success';\n break;\n case 'N':\n result = 'failed';\n break;\n case 'U':\n result = !errorCodeObject ? 'cancelled' : 'timeout';\n break;\n default:\n }\n if (resultObj?.errorCode) {\n result = 'noTransStatus';\n }\n\n /** Create log object - the process is completed, one way or another */\n\n event = new AnalyticsLogEvent({\n type: THREEDS2_FULL,\n message: `${THREEDS2_NUM} challenge has completed`,\n subType: Analytics3DS2Events.CHALLENGE_COMPLETED,\n result\n });\n\n // Send log to analytics endpoint\n this.props.onSubmitAnalytics(event);\n\n /**\n * Equals call to onAdditionalDetails (except for in 3DS2InMDFlow)\n */\n this.props.onComplete(data);\n });\n }\n\n /**\n * Display error in the UI,\n * and, optionally, decide whether to send any of these errors to the merchant defined onError callback\n *\n * @param errorInfoObj -\n * @param isFatal -\n */\n setError(errorInfoObj: StatusErrorInfoObject, isFatal: boolean) {\n this.setState({ status: 'error', errorInfo: errorInfoObj.errorInfo });\n\n // Decide whether to call this.props.onError\n if (isFatal) {\n this.props.onError(new AdyenCheckoutError(ERROR, errorInfoObj.errorInfo, { cause: errorInfoObj.errorObj }));\n }\n }\n\n render(_, { challengeData }) {\n const getImage = useImage();\n if (this.state.status === 'performingChallenge') {\n return (\n <DoChallenge3DS2\n onCompleteChallenge={(challenge: ThreeDS2FlowObject) => {\n let errorCodeObject: ErrorCodeObject = null;\n\n // Challenge has resulted in an error (no transStatus could be retrieved) - but we still treat this as a valid scenario\n if (hasOwnProperty(challenge.result, 'errorCode') && challenge.result.errorCode.length) {\n // Tell the merchant there's been an error\n errorCodeObject = {\n errorCode: challenge.result.errorCode,\n message: `${THREEDS2_CHALLENGE_ERROR}: ${\n challenge.result.errorDescription ? challenge.result.errorDescription : 'no transStatus could be retrieved'\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 this.props.onError(\n new AdyenCheckoutError(\n ERROR,\n `${THREEDS2_CHALLENGE_ERROR}: ${\n challenge.result.errorDescription\n ? challenge.result.errorDescription\n : 'no transStatus could be retrieved'\n }`,\n { cause: challenge.result.errorCode }\n )\n );\n }\n }\n\n /**\n * An object has been returned, parsed & accepted as legit (according to the rules in getProcessMessageHandler),\n * but the result prop on that object is missing\n */\n if (!challenge.result) {\n this.setError(\n {\n errorInfo: `${THREEDS2_CHALLENGE_ERROR}: ${this.props.i18n.get('3ds.chal.805', {\n values: { result: '\"result\"' }\n })}`,\n errorObj: challenge as unknown as ErrorObject\n },\n true\n );\n\n // Send error to analytics endpoint\n const event = new AnalyticsErrorEvent({\n code: Analytics3DS2Errors.CHALLENGE_RESOLVED_WITHOUT_RESULT_PROP,\n errorType: ANALYTICS_ERROR_TYPE.apiError,\n message: `${THREEDS2_CHALLENGE_ERROR}: challenge resolved without a \"result\" object`\n });\n\n this.props.onSubmitAnalytics(event);\n\n console.debug('### PrepareChallenge3DS2::exiting:: challenge resolved without a \"result\" object');\n\n return;\n }\n\n // Proceed with call to onAdditionalDetails (except for in 3DS2InMDFlow)\n this.setStatusComplete(challenge.result, errorCodeObject);\n }}\n onErrorChallenge={(challenge: ThreeDS2FlowObject) => {\n /**\n * Called when challenge times-out (which is still a valid scenario)...\n */\n if (hasOwnProperty(challenge, 'errorCode')) {\n const timeoutObject: ErrorCodeObject = {\n errorCode: challenge.errorCode,\n message: `${THREEDS2_CHALLENGE}: ${challenge.errorCode}`\n };\n\n // see comment in onCompleteChallenge code block\n if (this.props.isMDFlow) {\n this.props.onError(\n new AdyenCheckoutError(ERROR, `${THREEDS2_CHALLENGE_ERROR}: '3DS2 challenge timed out'`, {\n cause: challenge.errorCode\n })\n );\n }\n\n this.setStatusComplete(challenge.result, timeoutObject);\n return;\n }\n }}\n {...challengeData}\n onActionHandled={this.props.onActionHandled}\n onFormSubmit={this.onFormSubmit}\n />\n );\n }\n\n if (this.state.status === 'error') {\n return (\n <div className=\"adyen-checkout__threeds2-challenge-error\">\n <Img\n className=\"adyen-checkout__status__icon adyen-checkout__status__icon--error\"\n src={getImage({\n imageFolder: 'components/'\n })('error')}\n alt={''}\n />\n <div className=\"adyen-checkout__status__text\">\n {this.state.errorInfo ? this.state.errorInfo : this.props.i18n.get('error.message.unknown')}\n </div>\n </div>\n );\n }\n\n return null;\n }\n}\n\nexport default PrepareChallenge3DS2;\n"],"names":["PrepareChallenge3DS2","Component","componentDidMount","isErrorObject","this","state","challengeData","shouldAllowHttpDomains","props","environment","_environmentUrls","api","includes","acsURL","isValidHttpUrl","setError","errorInfo","Analytics3DS2Errors","TOKEN_IS_MISSING_ACSURL","i18n","get","event","AnalyticsErrorEvent","code","errorType","ANALYTICS_ERROR_TYPE","apiError","message","THREEDS2_CHALLENGE_ERROR","onSubmitAnalytics","console","debug","acsTransID","messageVersion","threeDSServerTransID","cReqData","TOKEN_IS_MISSING_OTHER_PROPS","setState","status","errorMsg","error","errorCode","indexOf","MISSING_TOKEN_IN_ACTION_MSG","ACTION_IS_MISSING_TOKEN","TOKEN_DECODE_OR_PARSING_FAILED","setStatusComplete","resultObj","errorCodeObject","data","isMDFlow","createOldChallengeResolveData","createChallengeResolveData","dataKey","transStatus","paymentData","finalResObject","errorTypeAndCode","THREEDS2_TIMEOUT","NO_TRANSSTATUS","network","result","AnalyticsLogEvent","type","THREEDS2_FULL","THREEDS2_NUM","subType","Analytics3DS2Events","CHALLENGE_COMPLETED","onComplete","errorInfoObj","isFatal","onError","AdyenCheckoutError","ERROR","cause","errorObj","render","_","getImage","useImage","h","DoChallenge3DS2","onCompleteChallenge","challenge","hasOwnProperty","length","errorDescription","values","CHALLENGE_RESOLVED_WITHOUT_RESULT_PROP","onErrorChallenge","timeoutObject","THREEDS2_CHALLENGE","onActionHandled","onFormSubmit","div","className","Img","src","imageFolder","alt","constructor","super","_define_property","msg","CHALLENGE_DATA_SENT","token","prepareChallengeData","size","challengeWindowSize","success","defaultProps"],"mappings":"unCAmBA,MAAMA,UAA6BC,EAsC/BC,iBAAAA,GAGI,IAF0BC,EAAcC,KAAKC,MAAMC,eAE7B,CAClB,MAAMC,EAO0B,SAA3BH,KAAKI,MAAMC,aAA0BL,KAAKI,MAAME,kBAAkBC,KAAKC,SAAS,0BAK/EC,OAAEA,GAAWT,KAAKC,MAAMC,cAI9B,IAHuBQ,EAAeD,EAAQN,GAGzB,CAEjBH,KAAKW,SACD,CACIC,UAAW,GAAGC,EAAoBC,4BAA4Bd,KAAKI,MAAMW,KAAKC,IAAI,oBAEtF,GAIJ,MAAMC,EAAQ,IAAIC,EAAoB,CAClCC,KAAMN,EAAoBC,wBAC1BM,UAAWC,EAAqBC,SAChCC,QAAS,GAAGC,wDAKhB,OAHAxB,KAAKI,MAAMqB,kBAAkBR,QAE7BS,QAAQC,MAAM,sDAElB,CAEA,MAAMC,WAAEA,EAAUC,eAAEA,EAAcC,qBAAEA,GAA0B9B,KAAKC,MAAMC,cAAgC6B,SAGzG,IAAKH,IAAeC,IAAmBC,EAAsB,CAEzD9B,KAAKW,SACD,CACIC,UAAW,GAAGC,EAAoBmB,iCAAiChC,KAAKI,MAAMW,KAAKC,IAAI,oBAG3F,GAIJ,MAAMC,EAAQ,IAAIC,EAAoB,CAClCC,KAAMN,EAAoBmB,6BAC1BZ,UAAWC,EAAqBC,SAChCC,QAAS,GAAGC,6HAOhB,OALAxB,KAAKI,MAAMqB,kBAAkBR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Q,CAAEC,cAAe,CAAEwG,SAAS,EAAOtE,MAAOG,IAEvDb,QAAQC,MAAM,GAAGH,MAA6Be,IAEtD,EAzBA4D,EADEvG,EACY+G,eAAe,CACzB1C,WAAY,OACZG,QAAS,OACTtB,UAAU"}
1
+ {"version":3,"file":"PrepareChallenge3DS2.js","sources":["../../../../../../src/components/ThreeDS2/components/Challenge/PrepareChallenge3DS2.tsx"],"sourcesContent":["import { Component, h } from 'preact';\nimport DoChallenge3DS2 from './DoChallenge3DS2';\nimport { createChallengeResolveData, prepareChallengeData, createOldChallengeResolveData, isErrorObject } from '../utils';\nimport { PrepareChallenge3DS2Props, PrepareChallenge3DS2State, StatusErrorInfoObject } from './types';\nimport { ChallengeData, ResultObject, ThreeDS2FlowObject, ErrorCodeObject } from '../../types';\nimport '../../ThreeDS2.scss';\nimport Img from '../../../internal/Img';\nimport './challenge.scss';\nimport { hasOwnProperty } from '../../../../utils/hasOwnProperty';\nimport useImage from '../../../../core/Context/useImage';\nimport AdyenCheckoutError, { ERROR } from '../../../../core/Errors/AdyenCheckoutError';\nimport { THREEDS2_CHALLENGE, THREEDS2_CHALLENGE_ERROR, THREEDS2_FULL, THREEDS2_NUM, MISSING_TOKEN_IN_ACTION_MSG } from '../../constants';\nimport { isValidHttpUrl } from '../../../../utils/isValidURL';\nimport { ANALYTICS_ERROR_TYPE, Analytics3DS2Errors, Analytics3DS2Events } from '../../../../core/Analytics/constants';\nimport { ErrorObject } from '../../../../core/Errors/types';\nimport { AnalyticsLogEvent } from '../../../../core/Analytics/AnalyticsLogEvent';\nimport { AnalyticsErrorEvent } from '../../../../core/Analytics/AnalyticsErrorEvent';\nimport { AnalyticsEvent } from '../../../../core/Analytics/AnalyticsEvent';\n\nclass PrepareChallenge3DS2 extends Component<PrepareChallenge3DS2Props, PrepareChallenge3DS2State> {\n public static defaultProps = {\n onComplete: () => {},\n onError: () => {},\n isMDFlow: false\n };\n\n constructor(props) {\n super(props);\n\n if (this.props.token) {\n const challengeData: ChallengeData | ErrorObject = prepareChallengeData({\n token: this.props.token,\n size: this.props.challengeWindowSize || this.props.size // TODO confirm that this.props.size is legacy and can be removed\n });\n\n this.state = {\n status: 'init',\n challengeData: challengeData as ChallengeData\n };\n } else {\n // Will be picked up in componentDidMount\n this.state = { challengeData: { success: false, error: MISSING_TOKEN_IN_ACTION_MSG } };\n\n console.debug(`${THREEDS2_CHALLENGE_ERROR}: ${MISSING_TOKEN_IN_ACTION_MSG}`);\n }\n }\n\n public onFormSubmit = (msg: string) => {\n const event = new AnalyticsLogEvent({\n type: THREEDS2_FULL,\n message: msg,\n subType: Analytics3DS2Events.CHALLENGE_DATA_SENT\n });\n\n this.props.onSubmitAnalytics(event);\n };\n\n componentDidMount() {\n const hasChallengeData = !isErrorObject(this.state.challengeData);\n\n if (hasChallengeData) {\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 challengeData\n */\n const { acsURL } = this.state.challengeData as ChallengeData;\n const hasValidAcsURL = isValidHttpUrl(acsURL, shouldAllowHttpDomains);\n\n // Only render component if we have an acsURL.\n if (!hasValidAcsURL) {\n // Set UI error & call onError callback\n this.setError(\n {\n errorInfo: `${Analytics3DS2Errors.TOKEN_IS_MISSING_ACSURL}: ${this.props.i18n.get('err.gen.9102')}` //\n },\n true\n );\n\n // Send error to analytics endpoint // TODO - check logs to see if this *ever* happens\n const event = new AnalyticsErrorEvent({\n code: Analytics3DS2Errors.TOKEN_IS_MISSING_ACSURL,\n errorType: ANALYTICS_ERROR_TYPE.apiError,\n message: `${THREEDS2_CHALLENGE_ERROR}: Decoded token is missing a valid acsURL property`\n });\n this.props.onSubmitAnalytics(event);\n\n console.debug('### PrepareChallenge3DS2::exiting:: no valid acsURL');\n return;\n }\n\n const { acsTransID, messageVersion, threeDSServerTransID } = (this.state.challengeData as ChallengeData).cReqData;\n\n // Only render component if we have a acsTransID, messageVersion & threeDSServerTransID\n if (!acsTransID || !messageVersion || !threeDSServerTransID) {\n // Set UI error & call onError callback\n this.setError(\n {\n errorInfo: `${Analytics3DS2Errors.TOKEN_IS_MISSING_OTHER_PROPS}: ${this.props.i18n.get('err.gen.9102')}`\n // errorObj: this.state.challengeData // TODO Decide if we want to expose this data\n },\n true\n );\n\n // Send error to analytics endpoint // TODO - check logs to see if this *ever* happens\n const event = new AnalyticsErrorEvent({\n code: Analytics3DS2Errors.TOKEN_IS_MISSING_OTHER_PROPS,\n errorType: ANALYTICS_ERROR_TYPE.apiError,\n message: `${THREEDS2_CHALLENGE_ERROR}: Decoded token is missing one or more of the following properties (acsTransID | messageVersion | threeDSServerTransID)`\n });\n this.props.onSubmitAnalytics(event);\n\n console.debug(\n '### PrepareChallenge3DS2::exiting:: missing one or more of the following properties (acsTransID | messageVersion | threeDSServerTransID)'\n );\n return;\n }\n\n // Proceed to allow component to render\n this.setState({ status: 'performingChallenge' });\n //\n } else {\n const errorMsg: string = (this.state.challengeData 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 // Set UI error & call onError callback\n this.setError(\n {\n errorInfo:\n errorMsg.indexOf(MISSING_TOKEN_IN_ACTION_MSG) > -1\n ? `${Analytics3DS2Errors.ACTION_IS_MISSING_TOKEN}: ${this.props.i18n.get('err.gen.9102')}`\n : `${Analytics3DS2Errors.TOKEN_DECODE_OR_PARSING_FAILED}: ${this.props.i18n.get('err.gen.9102')}`\n // errorObj: this.state.challengeData // TODO Decide if we want to expose this data\n },\n true\n );\n\n // Send error to analytics endpoint // TODO - check logs to see if the base64 decoding errors *ever* happen\n const event = new AnalyticsErrorEvent({\n code: errorCode,\n errorType: ANALYTICS_ERROR_TYPE.apiError,\n message: `${THREEDS2_CHALLENGE_ERROR}: ${errorMsg}` // can be: 'Missing \"token\" property from threeDS2 action', 'not base64', 'malformed URI sequence' or 'Could not JSON parse token'\n });\n\n this.props.onSubmitAnalytics(event);\n\n console.debug('### PrepareChallenge3DS2::exiting:: no challengeData');\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 ? createOldChallengeResolveData : createChallengeResolveData;\n const data = resolveDataFunction(this.props.dataKey, resultObj.transStatus, this.props.paymentData);\n\n if (errorCodeObject) {\n console.debug('### PrepareChallenge3DS2::errorCodeObject::', errorCodeObject);\n }\n\n let event: AnalyticsEvent;\n\n /** Are we in an \"error\" i.e. timeout or no transStatus, 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 : Analytics3DS2Errors.NO_TRANSSTATUS,\n errorType: finalResObject.errorCode === 'timeout' ? ANALYTICS_ERROR_TYPE.network : ANALYTICS_ERROR_TYPE.apiError\n };\n\n // Challenge process has timed out,\n // or, It's an error reported by the backend 'cos no transStatus could be retrieved // TODO - check logs to see if this *ever* happens\n\n event = new AnalyticsErrorEvent({\n message: (finalResObject as ErrorCodeObject).message,\n ...errorTypeAndCode\n });\n\n // Send error to analytics endpoint\n this.props.onSubmitAnalytics(event);\n }\n\n /** Calculate \"result\" for analytics */\n let result: string;\n\n switch (resultObj?.transStatus) {\n case 'Y':\n result = 'success';\n break;\n case 'N':\n result = 'failed';\n break;\n case 'U':\n result = !errorCodeObject ? 'cancelled' : 'timeout';\n break;\n default:\n }\n if (resultObj?.errorCode) {\n result = 'noTransStatus';\n }\n\n /** Create log object - the process is completed, one way or another */\n\n event = new AnalyticsLogEvent({\n type: THREEDS2_FULL,\n message: `${THREEDS2_NUM} challenge has completed`,\n subType: Analytics3DS2Events.CHALLENGE_COMPLETED,\n result\n });\n\n // Send log to analytics endpoint\n this.props.onSubmitAnalytics(event);\n\n /**\n * Equals call to onAdditionalDetails (except for in 3DS2InMDFlow)\n */\n this.props.onComplete(data);\n });\n }\n\n /**\n * Display error in the UI,\n * and, optionally, decide whether to send any of these errors to the merchant defined onError callback\n *\n * @param errorInfoObj -\n * @param isFatal -\n */\n setError(errorInfoObj: StatusErrorInfoObject, isFatal: boolean) {\n this.setState({ status: 'error', errorInfo: errorInfoObj.errorInfo });\n\n // Decide whether to call this.props.onError\n if (isFatal) {\n this.props.onError(new AdyenCheckoutError(ERROR, errorInfoObj.errorInfo, { cause: errorInfoObj.errorObj }));\n }\n }\n\n render(_, { challengeData }) {\n const getImage = useImage();\n if (this.state.status === 'performingChallenge') {\n return (\n <DoChallenge3DS2\n onCompleteChallenge={(challenge: ThreeDS2FlowObject) => {\n let errorCodeObject: ErrorCodeObject = null;\n\n // Challenge has resulted in an error (no transStatus could be retrieved) - but we still treat this as a valid scenario\n if (hasOwnProperty(challenge.result, 'errorCode') && challenge.result.errorCode.length) {\n // Tell the merchant there's been an error\n errorCodeObject = {\n errorCode: challenge.result.errorCode,\n message: `${THREEDS2_CHALLENGE_ERROR}: ${\n challenge.result.errorDescription ? challenge.result.errorDescription : 'no transStatus could be retrieved'\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 this.props.onError(\n new AdyenCheckoutError(\n ERROR,\n `${THREEDS2_CHALLENGE_ERROR}: ${\n challenge.result.errorDescription\n ? challenge.result.errorDescription\n : 'no transStatus could be retrieved'\n }`,\n { cause: challenge.result.errorCode }\n )\n );\n }\n }\n\n /**\n * An object has been returned, parsed & accepted as legit (according to the rules in getProcessMessageHandler),\n * but the result prop on that object is missing\n */\n if (!challenge.result) {\n this.setError(\n {\n errorInfo: `${THREEDS2_CHALLENGE_ERROR}: ${this.props.i18n.get('3ds.chal.805', {\n values: { result: '\"result\"' }\n })}`,\n errorObj: challenge as unknown as ErrorObject\n },\n true\n );\n\n // Send error to analytics endpoint\n const event = new AnalyticsErrorEvent({\n code: Analytics3DS2Errors.CHALLENGE_RESOLVED_WITHOUT_RESULT_PROP,\n errorType: ANALYTICS_ERROR_TYPE.apiError,\n message: `${THREEDS2_CHALLENGE_ERROR}: challenge resolved without a \"result\" object`\n });\n\n this.props.onSubmitAnalytics(event);\n\n console.debug('### PrepareChallenge3DS2::exiting:: challenge resolved without a \"result\" object');\n\n return;\n }\n\n // Proceed with call to onAdditionalDetails (except for in 3DS2InMDFlow)\n this.setStatusComplete(challenge.result, errorCodeObject);\n }}\n onErrorChallenge={(challenge: ThreeDS2FlowObject) => {\n /**\n * Called when challenge times-out (which is still a valid scenario)...\n */\n if (hasOwnProperty(challenge, 'errorCode')) {\n const timeoutObject: ErrorCodeObject = {\n errorCode: challenge.errorCode,\n message: `${THREEDS2_CHALLENGE}: ${challenge.errorCode}`\n };\n\n // see comment in onCompleteChallenge code block\n if (this.props.isMDFlow) {\n this.props.onError(\n new AdyenCheckoutError(ERROR, `${THREEDS2_CHALLENGE_ERROR}: '3DS2 challenge timed out'`, {\n cause: challenge.errorCode\n })\n );\n }\n\n this.setStatusComplete(challenge.result, timeoutObject);\n return;\n }\n }}\n {...challengeData}\n onActionHandled={this.props.onActionHandled}\n onFormSubmit={this.onFormSubmit}\n />\n );\n }\n\n if (this.state.status === 'error') {\n return (\n <div className=\"adyen-checkout__threeds2-challenge-error\">\n <Img\n className=\"adyen-checkout__status__icon adyen-checkout__status__icon--error\"\n src={getImage({\n imageFolder: 'components/'\n })('error')}\n alt={''}\n />\n <div className=\"adyen-checkout__status__text\">\n {this.state.errorInfo ? this.state.errorInfo : this.props.i18n.get('error.message.unknown')}\n </div>\n </div>\n );\n }\n\n return null;\n }\n}\n\nexport default PrepareChallenge3DS2;\n"],"names":["PrepareChallenge3DS2","Component","componentDidMount","isErrorObject","this","state","challengeData","shouldAllowHttpDomains","props","environment","_environmentUrls","api","includes","acsURL","isValidHttpUrl","setError","errorInfo","Analytics3DS2Errors","TOKEN_IS_MISSING_ACSURL","i18n","get","event","AnalyticsErrorEvent","code","errorType","ANALYTICS_ERROR_TYPE","apiError","message","THREEDS2_CHALLENGE_ERROR","onSubmitAnalytics","console","debug","acsTransID","messageVersion","threeDSServerTransID","cReqData","TOKEN_IS_MISSING_OTHER_PROPS","setState","status","errorMsg","error","errorCode","indexOf","MISSING_TOKEN_IN_ACTION_MSG","ACTION_IS_MISSING_TOKEN","TOKEN_DECODE_OR_PARSING_FAILED","setStatusComplete","resultObj","errorCodeObject","data","isMDFlow","createOldChallengeResolveData","createChallengeResolveData","dataKey","transStatus","paymentData","finalResObject","errorTypeAndCode","THREEDS2_TIMEOUT","NO_TRANSSTATUS","network","result","AnalyticsLogEvent","type","THREEDS2_FULL","THREEDS2_NUM","subType","Analytics3DS2Events","CHALLENGE_COMPLETED","onComplete","errorInfoObj","isFatal","onError","AdyenCheckoutError","ERROR","cause","errorObj","render","_","getImage","useImage","h","DoChallenge3DS2","onCompleteChallenge","challenge","hasOwnProperty","length","errorDescription","values","CHALLENGE_RESOLVED_WITHOUT_RESULT_PROP","onErrorChallenge","timeoutObject","THREEDS2_CHALLENGE","onActionHandled","onFormSubmit","div","className","Img","src","imageFolder","alt","constructor","super","_define_property","msg","CHALLENGE_DATA_SENT","token","prepareChallengeData","size","challengeWindowSize","success","defaultProps"],"mappings":"unCAmBA,MAAMA,UAA6BC,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