@shipengine/elements 2.28.0 → 2.29.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 (130) hide show
  1. package/dist/cjs/components/forms/edit-billing-form/edit-billing-form.cjs +87 -12
  2. package/dist/cjs/components/forms/edit-billing-form/edit-billing-form.styles.cjs +15 -0
  3. package/dist/cjs/components/forms/wallet-form/index.cjs +0 -2
  4. package/dist/cjs/components/forms/wallet-form/wallet-form.cjs +153 -23
  5. package/dist/cjs/components/forms/wallet-form/wallet-form.styles.cjs +15 -0
  6. package/dist/cjs/components/forms/wallet-form/wallet-schema.cjs +8 -43
  7. package/dist/cjs/components/payment/payment-method-selector/index.cjs +7 -0
  8. package/dist/cjs/components/payment/payment-method-selector/payment-method-selector.cjs +55 -0
  9. package/dist/cjs/components/payment/payment-method-selector/payment-method-selector.styles.cjs +58 -0
  10. package/dist/cjs/contexts/auctane-pay-session-context.cjs +158 -0
  11. package/dist/cjs/contexts/index.cjs +8 -0
  12. package/dist/cjs/features/payment-method-settings/payment-method-settings.cjs +4 -3
  13. package/dist/cjs/hooks/financial-services/financial-service.cjs +464 -0
  14. package/dist/cjs/hooks/financial-services/index.cjs +9 -0
  15. package/dist/cjs/hooks/financial-services/use-financial-service.cjs +188 -0
  16. package/dist/cjs/locales/en/register-wallet.json.cjs +5 -0
  17. package/dist/cjs/package.json.cjs +1 -1
  18. package/dist/cjs/workflows/onboarding/components/confirmation-and-submission-step/confirmation-and-submission-step.cjs +16 -5
  19. package/dist/cjs/workflows/onboarding/components/confirmation-and-submission-step/use-confirmation-and-submission-step.cjs +6 -6
  20. package/dist/cjs/workflows/onboarding/components/funding-step/funding-step.cjs +7 -3
  21. package/dist/cjs/workflows/onboarding/onboarding.cjs +8 -5
  22. package/dist/esm/components/forms/edit-billing-form/edit-billing-form.js +88 -13
  23. package/dist/esm/components/forms/edit-billing-form/edit-billing-form.styles.js +15 -0
  24. package/dist/esm/components/forms/wallet-form/index.js +0 -1
  25. package/dist/esm/components/forms/wallet-form/wallet-form.js +155 -25
  26. package/dist/esm/components/forms/wallet-form/wallet-form.styles.js +15 -0
  27. package/dist/esm/components/forms/wallet-form/wallet-schema.js +1 -36
  28. package/dist/esm/components/payment/payment-method-selector/index.js +1 -0
  29. package/dist/esm/components/payment/payment-method-selector/payment-method-selector.js +53 -0
  30. package/dist/esm/components/payment/payment-method-selector/payment-method-selector.styles.js +56 -0
  31. package/dist/esm/contexts/auctane-pay-session-context.js +155 -0
  32. package/dist/esm/contexts/index.js +1 -0
  33. package/dist/esm/features/payment-method-settings/payment-method-settings.js +5 -4
  34. package/dist/esm/hooks/financial-services/financial-service.js +462 -0
  35. package/dist/esm/hooks/financial-services/index.js +2 -0
  36. package/dist/esm/hooks/financial-services/use-financial-service.js +186 -0
  37. package/dist/esm/locales/en/register-wallet.json.js +5 -0
  38. package/dist/esm/package.json.js +1 -1
  39. package/dist/esm/workflows/onboarding/components/confirmation-and-submission-step/confirmation-and-submission-step.js +16 -5
  40. package/dist/esm/workflows/onboarding/components/confirmation-and-submission-step/use-confirmation-and-submission-step.js +6 -6
  41. package/dist/esm/workflows/onboarding/components/funding-step/funding-step.js +7 -3
  42. package/dist/esm/workflows/onboarding/onboarding.js +8 -5
  43. package/dist/types/components/address-preference-context/address-preference-context.d.ts +0 -1
  44. package/dist/types/components/address-preference-context/address-preference-context.d.ts.map +1 -1
  45. package/dist/types/components/forms/edit-billing-form/edit-billing-form.d.ts +2 -2
  46. package/dist/types/components/forms/edit-billing-form/edit-billing-form.d.ts.map +1 -1
  47. package/dist/types/components/forms/edit-billing-form/edit-billing-form.styles.d.ts +14 -0
  48. package/dist/types/components/forms/edit-billing-form/edit-billing-form.styles.d.ts.map +1 -1
  49. package/dist/types/components/forms/wallet-form/index.d.ts +0 -1
  50. package/dist/types/components/forms/wallet-form/index.d.ts.map +1 -1
  51. package/dist/types/components/forms/wallet-form/wallet-form.d.ts +4 -1
  52. package/dist/types/components/forms/wallet-form/wallet-form.d.ts.map +1 -1
  53. package/dist/types/components/forms/wallet-form/wallet-form.styles.d.ts +14 -0
  54. package/dist/types/components/forms/wallet-form/wallet-form.styles.d.ts.map +1 -1
  55. package/dist/types/components/forms/wallet-form/wallet-schema.d.ts +3 -43
  56. package/dist/types/components/forms/wallet-form/wallet-schema.d.ts.map +1 -1
  57. package/dist/types/components/payment/payment-method-selector/index.d.ts +2 -0
  58. package/dist/types/components/payment/payment-method-selector/index.d.ts.map +1 -0
  59. package/dist/types/components/payment/payment-method-selector/payment-method-selector.d.ts +11 -0
  60. package/dist/types/components/payment/payment-method-selector/payment-method-selector.d.ts.map +1 -0
  61. package/dist/types/components/payment/payment-method-selector/payment-method-selector.styles.d.ts +52 -0
  62. package/dist/types/components/payment/payment-method-selector/payment-method-selector.styles.d.ts.map +1 -0
  63. package/dist/types/contexts/auctane-pay-session-context.d.ts +54 -0
  64. package/dist/types/contexts/auctane-pay-session-context.d.ts.map +1 -0
  65. package/dist/types/contexts/index.d.ts +3 -0
  66. package/dist/types/contexts/index.d.ts.map +1 -0
  67. package/dist/types/elements/customs-form/customs-form-element.d.ts +5 -0
  68. package/dist/types/elements/customs-form/customs-form-element.d.ts.map +1 -1
  69. package/dist/types/elements/labels-grid/labels-grid.d.ts +5 -0
  70. package/dist/types/elements/labels-grid/labels-grid.d.ts.map +1 -1
  71. package/dist/types/elements/manage-carriers/manage-carriers.d.ts +5 -0
  72. package/dist/types/elements/manage-carriers/manage-carriers.d.ts.map +1 -1
  73. package/dist/types/elements/manage-external-carriers/manage-external-carriers.d.ts +5 -0
  74. package/dist/types/elements/manage-external-carriers/manage-external-carriers.d.ts.map +1 -1
  75. package/dist/types/elements/manage-funding/manage-funding-element.d.ts +5 -0
  76. package/dist/types/elements/manage-funding/manage-funding-element.d.ts.map +1 -1
  77. package/dist/types/elements/manage-warehouses/manage-warehouses.d.ts +5 -0
  78. package/dist/types/elements/manage-warehouses/manage-warehouses.d.ts.map +1 -1
  79. package/dist/types/elements/payment-method-settings/payment-method-settings-element.d.ts +5 -0
  80. package/dist/types/elements/payment-method-settings/payment-method-settings-element.d.ts.map +1 -1
  81. package/dist/types/elements/purchase-label/purchase-label.d.ts +5 -0
  82. package/dist/types/elements/purchase-label/purchase-label.d.ts.map +1 -1
  83. package/dist/types/elements/select-label-layout/select-label-layout-element.d.ts +5 -0
  84. package/dist/types/elements/select-label-layout/select-label-layout-element.d.ts.map +1 -1
  85. package/dist/types/elements/shipment-summary/shipment-summary.d.ts +5 -0
  86. package/dist/types/elements/shipment-summary/shipment-summary.d.ts.map +1 -1
  87. package/dist/types/elements/shipments-grid/shipments-grid.d.ts +5 -0
  88. package/dist/types/elements/shipments-grid/shipments-grid.d.ts.map +1 -1
  89. package/dist/types/elements/theme-creator/theme-creator.d.ts +5 -0
  90. package/dist/types/elements/theme-creator/theme-creator.d.ts.map +1 -1
  91. package/dist/types/elements/transaction-history/transaction-history-element.d.ts +5 -0
  92. package/dist/types/elements/transaction-history/transaction-history-element.d.ts.map +1 -1
  93. package/dist/types/elements/unit-settings/unit-settings-element.d.ts +5 -0
  94. package/dist/types/elements/unit-settings/unit-settings-element.d.ts.map +1 -1
  95. package/dist/types/elements/vat-settings/vat-settings-element.d.ts +5 -0
  96. package/dist/types/elements/vat-settings/vat-settings-element.d.ts.map +1 -1
  97. package/dist/types/elements/void-label/void-label.d.ts +5 -0
  98. package/dist/types/elements/void-label/void-label.d.ts.map +1 -1
  99. package/dist/types/elements-provider/elements-provider.d.ts.map +1 -1
  100. package/dist/types/features/payment-method-settings/payment-method-settings.d.ts.map +1 -1
  101. package/dist/types/hooks/financial-services/financial-service.d.ts +279 -0
  102. package/dist/types/hooks/financial-services/financial-service.d.ts.map +1 -0
  103. package/dist/types/hooks/financial-services/index.d.ts +5 -0
  104. package/dist/types/hooks/financial-services/index.d.ts.map +1 -0
  105. package/dist/types/hooks/financial-services/use-financial-service.d.ts +40 -0
  106. package/dist/types/hooks/financial-services/use-financial-service.d.ts.map +1 -0
  107. package/dist/types/locales/en/index.d.ts +5 -0
  108. package/dist/types/locales/en/index.d.ts.map +1 -1
  109. package/dist/types/types/financial-services.d.ts +34 -0
  110. package/dist/types/types/financial-services.d.ts.map +1 -0
  111. package/dist/types/types/index.d.ts +1 -1
  112. package/dist/types/types/index.d.ts.map +1 -1
  113. package/dist/types/workflows/account-settings/account-settings.d.ts +5 -0
  114. package/dist/types/workflows/account-settings/account-settings.d.ts.map +1 -1
  115. package/dist/types/workflows/carrier-services/carrier-services.d.ts +5 -0
  116. package/dist/types/workflows/carrier-services/carrier-services.d.ts.map +1 -1
  117. package/dist/types/workflows/connect-external-carrier/connect-external-carrier.d.ts +5 -0
  118. package/dist/types/workflows/connect-external-carrier/connect-external-carrier.d.ts.map +1 -1
  119. package/dist/types/workflows/label-workflow/label-workflow.d.ts +5 -0
  120. package/dist/types/workflows/label-workflow/label-workflow.d.ts.map +1 -1
  121. package/dist/types/workflows/onboarding/components/confirmation-and-submission-step/confirmation-and-submission-step.d.ts.map +1 -1
  122. package/dist/types/workflows/onboarding/components/confirmation-and-submission-step/use-confirmation-and-submission-step.d.ts.map +1 -1
  123. package/dist/types/workflows/onboarding/components/funding-step/funding-step.d.ts.map +1 -1
  124. package/dist/types/workflows/onboarding/onboarding.d.ts +5 -0
  125. package/dist/types/workflows/onboarding/onboarding.d.ts.map +1 -1
  126. package/package.json +5 -5
  127. package/dist/cjs/components/forms/wallet-form/billing-fields.cjs +0 -71
  128. package/dist/esm/components/forms/wallet-form/billing-fields.js +0 -69
  129. package/dist/types/components/forms/wallet-form/billing-fields.d.ts +0 -7
  130. package/dist/types/components/forms/wallet-form/billing-fields.d.ts.map +0 -1
@@ -0,0 +1,158 @@
1
+ 'use strict';
2
+
3
+ var _tslib = require('../_virtual/_tslib.cjs');
4
+ var jsxRuntime = require('@emotion/react/jsx-runtime');
5
+ var reactApi = require('@shipengine/react-api');
6
+ var React = require('react');
7
+
8
+ const SESSION_STORAGE_KEY = "auctane_pay_session";
9
+ const storeSession = (session, expiresAt) => {
10
+ try {
11
+ const data = {
12
+ session,
13
+ expiresAt
14
+ };
15
+ sessionStorage.setItem(SESSION_STORAGE_KEY, JSON.stringify(data));
16
+ } catch (error) {
17
+ console.warn("Failed to store session in sessionStorage:", error);
18
+ }
19
+ };
20
+ const retrieveStoredSession = () => {
21
+ try {
22
+ const stored = sessionStorage.getItem(SESSION_STORAGE_KEY);
23
+ if (!stored) return null;
24
+ const data = JSON.parse(stored);
25
+ return data;
26
+ } catch (error) {
27
+ console.warn("Failed to retrieve session from sessionStorage:", error);
28
+ return null;
29
+ }
30
+ };
31
+ const clearStoredSession = () => {
32
+ try {
33
+ sessionStorage.removeItem(SESSION_STORAGE_KEY);
34
+ } catch (error) {
35
+ console.warn("Failed to clear session from sessionStorage:", error);
36
+ }
37
+ };
38
+ const AuctanePaySessionContext = /*#__PURE__*/React.createContext(undefined);
39
+ /**
40
+ * Provider that manages Adyen payment session creation and redirect handling.
41
+ * Each call to getSessionData() creates a fresh session - sessions are not cached
42
+ * to avoid reusing sessions after authorization.
43
+ *
44
+ * @example
45
+ * ```tsx
46
+ * <AuctanePaySessionProvider paymentPreferences={["add_funds", "subscription"]}>
47
+ * <OnboardingWizard>
48
+ * <FundingStep />
49
+ * </OnboardingWizard>
50
+ * </AuctanePaySessionProvider>
51
+ * ```
52
+ */
53
+ const AuctanePaySessionProvider = ({
54
+ children,
55
+ paymentPreferences = ["add_funds", "subscription"],
56
+ returnUrl
57
+ }) => {
58
+ const [sessionError, setSessionError] = React.useState(null);
59
+ // Track the last created session for saveSessionForRedirect
60
+ const lastSessionRef = React.useRef(null);
61
+ const {
62
+ mutateAsync: createAdyenSession,
63
+ isLoading: isCreating
64
+ } = reactApi.useCreateAuctanePaySession();
65
+ const createSession = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
66
+ try {
67
+ setSessionError(null);
68
+ const cleanUrl = returnUrl || `${window.location.origin}${window.location.pathname}`;
69
+ const session = yield createAdyenSession({
70
+ paymentPreferences,
71
+ returnUrl: cleanUrl
72
+ });
73
+ if (session) {
74
+ const expiresAt = new Date(session.metadata.adyenExpiration).getTime();
75
+ lastSessionRef.current = {
76
+ session,
77
+ expiresAt
78
+ };
79
+ }
80
+ return session;
81
+ } catch (err) {
82
+ const error = err instanceof Error ? err : new Error("Failed to create Adyen session");
83
+ setSessionError(error);
84
+ throw error;
85
+ }
86
+ }), [createAdyenSession, paymentPreferences, returnUrl]);
87
+ const getSessionData = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
88
+ // Always create a fresh session to avoid reusing sessions after authorization
89
+ return createSession();
90
+ }), [createSession]);
91
+ const clearSession = React.useCallback(() => {
92
+ lastSessionRef.current = null;
93
+ setSessionError(null);
94
+ clearStoredSession();
95
+ }, []);
96
+ const saveSessionForRedirect = React.useCallback(() => {
97
+ if (lastSessionRef.current) {
98
+ storeSession(lastSessionRef.current.session, lastSessionRef.current.expiresAt);
99
+ }
100
+ }, []);
101
+ const restoreSessionAfterRedirect = React.useCallback(() => {
102
+ const storedData = retrieveStoredSession();
103
+ if (!storedData) {
104
+ return null;
105
+ }
106
+ // Check if session is still valid
107
+ if (Date.now() >= storedData.expiresAt) {
108
+ clearStoredSession();
109
+ return null;
110
+ }
111
+ // Update lastSessionRef so saveSessionForRedirect can work if needed
112
+ lastSessionRef.current = storedData;
113
+ // Clear from storage after restoring (single-use)
114
+ clearStoredSession();
115
+ return storedData.session;
116
+ }, []);
117
+ const value = React.useMemo(() => ({
118
+ isCreating,
119
+ sessionError,
120
+ getSessionData,
121
+ clearSession,
122
+ saveSessionForRedirect,
123
+ restoreSessionAfterRedirect
124
+ }), [isCreating, sessionError, getSessionData, clearSession, saveSessionForRedirect, restoreSessionAfterRedirect]);
125
+ return jsxRuntime.jsx(AuctanePaySessionContext.Provider, {
126
+ value: value,
127
+ children: children
128
+ });
129
+ };
130
+ /**
131
+ * Hook to access the Adyen payment session context
132
+ *
133
+ * @throws Error if used outside of AuctanePaySessionProvider
134
+ *
135
+ * @example
136
+ * ```tsx
137
+ * const WalletForm = () => {
138
+ * const { getSessionData, sessionData } = useAuctanePaySession();
139
+ *
140
+ * const { adyenRef, submit } = useFinancialService({
141
+ * getAdyenSessionData: getSessionData, // Uses cached session!
142
+ * paymentMethod: "credit_card",
143
+ * });
144
+ *
145
+ * return <div ref={adyenRef} />;
146
+ * };
147
+ * ```
148
+ */
149
+ const useAuctanePaySession = () => {
150
+ const context = React.useContext(AuctanePaySessionContext);
151
+ if (!context) {
152
+ throw new Error("useAuctanePaySession must be used within AuctanePaySessionProvider");
153
+ }
154
+ return context;
155
+ };
156
+
157
+ exports.AuctanePaySessionProvider = AuctanePaySessionProvider;
158
+ exports.useAuctanePaySession = useAuctanePaySession;
@@ -0,0 +1,8 @@
1
+ 'use strict';
2
+
3
+ var auctanePaySessionContext = require('./auctane-pay-session-context.cjs');
4
+
5
+
6
+
7
+ exports.AuctanePaySessionProvider = auctanePaySessionContext.AuctanePaySessionProvider;
8
+ exports.useAuctanePaySession = auctanePaySessionContext.useAuctanePaySession;
@@ -2,6 +2,7 @@
2
2
 
3
3
  var _tslib = require('../../_virtual/_tslib.cjs');
4
4
  var jsxRuntime = require('@emotion/react/jsx-runtime');
5
+ var auctanePaySessionContext = require('../../contexts/auctane-pay-session-context.cjs');
5
6
  var useToggle = require('../../hooks/use-toggle.cjs');
6
7
  var giger = require('@shipengine/giger');
7
8
  var reactApi = require('@shipengine/react-api');
@@ -43,13 +44,13 @@ const PaymentMethodSettings = ({
43
44
  fundingSourceId,
44
45
  billingInfo
45
46
  } = (_a = fundingSources === null || fundingSources === void 0 ? void 0 : fundingSources[0]) !== null && _a !== void 0 ? _a : {};
46
- const handleUpdateBilling = (billingInfo, creditCardInfo) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
47
+ const handleUpdateBilling = (billingInfo, auctanePayInfo) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
47
48
  if (fundingSourceId) {
48
49
  try {
49
50
  setIsUpdatingBilling(true);
50
51
  yield updateBilling({
51
52
  billingInfo,
52
- creditCardInfo,
53
+ auctanePayInfo,
53
54
  fundingSourceId
54
55
  });
55
56
  yield refetchFundingSources();
@@ -62,7 +63,7 @@ const PaymentMethodSettings = ({
62
63
  }
63
64
  }
64
65
  });
65
- if (showEditBilling) return jsxRuntime.jsxs(jsxRuntime.Fragment, {
66
+ if (showEditBilling) return jsxRuntime.jsxs(auctanePaySessionContext.AuctanePaySessionProvider, {
66
67
  children: [jsxRuntime.jsx(editBillingForm.EditBillingForm, {
67
68
  billingInfo: billingInfo,
68
69
  isLoading: isUpdatingBilling,
@@ -0,0 +1,464 @@
1
+ 'use strict';
2
+
3
+ var _tslib = require('../../_virtual/_tslib.cjs');
4
+ var adyenWeb = require('@adyen/adyen-web');
5
+
6
+ /**
7
+ * ShipstationFinancialService - This class provides a simple, unified interface for initializing and managing Adyen payment flows,
8
+ * including credit card payments, bank transfers, and handling 3D Secure redirects.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * // 1. Create service instance with session data callback
13
+ * const financialService = new ShipstationFinancialService({
14
+ * getAdyenSessionData: async () => {
15
+ * // Fetch Adyen session data from Auctane Pay
16
+ * const response = await fetch('/api/adyen/session', {
17
+ * method: 'POST',
18
+ * headers: { 'Authorization': `Bearer ${token}` },
19
+ * body: JSON.stringify({ amount: 1000, currency: 'USD' })
20
+ * });
21
+ * return response.json();
22
+ * }
23
+ * });
24
+ *
25
+ * // 2. Initialize the service
26
+ * await financialService.init();
27
+ *
28
+ * // 3. Create a credit card checkout component
29
+ * await financialService.createCheckout('credit_card', {
30
+ * locale: 'en-US',
31
+ * onPaymentCompleted: (result) => {
32
+ * if (result.resultCode === 'Authorised') {
33
+ * console.log('Payment successful!');
34
+ * }
35
+ * },
36
+ * onError: (error) => {
37
+ * console.error('Payment error:', error);
38
+ * },
39
+ * creditCardOptions: {
40
+ * hasHolderName: true,
41
+ * placeholders: {
42
+ * cardNumber: '1234 5678 9012 3456',
43
+ * expiryDate: 'MM/YY',
44
+ * securityCodeThreeDigits: '123'
45
+ * }
46
+ * }
47
+ * });
48
+ *
49
+ * // 4. Mount the component to a DOM element
50
+ * financialService.mount('#payment-container');
51
+ *
52
+ * // 5. Submit payment when user clicks pay button
53
+ * document.getElementById('pay-button').addEventListener('click', () => {
54
+ * financialService.submit();
55
+ * });
56
+ * ```
57
+ */
58
+ class FinancialService {
59
+ /**
60
+ * A flag that indicates whether the current instance of the financial services class has been initialized.
61
+ *
62
+ * @example
63
+ * if (financialService.isReady()) {
64
+ * financialService.mount("#service-container");
65
+ * }
66
+ */
67
+ isReady() {
68
+ return !!this.getCurrentSessionData();
69
+ }
70
+ constructor(config) {
71
+ this.paymentConfig = config;
72
+ }
73
+ /**
74
+ * Initializes the service by fetching Adyen session data.
75
+ * Must be called before creating any payment components.
76
+ *
77
+ * @throws Error If session data cannot be retrieved
78
+ *
79
+ * @example
80
+ * ```typescript
81
+ * try {
82
+ * await new ShipstationFinancialService({ getAdyenSessionData }).init()
83
+ * console.log('Service initialized successfully');
84
+ * } catch (error) {
85
+ * console.error('Failed to initialize:', error);
86
+ * }
87
+ * ```
88
+ */
89
+ init() {
90
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
91
+ const {
92
+ getAdyenSessionData
93
+ } = this.paymentConfig;
94
+ try {
95
+ this.adyenCheckoutData = yield getAdyenSessionData();
96
+ if (!this.adyenCheckoutData) {
97
+ throw new Error("Failed to retrieve Adyen session data");
98
+ }
99
+ } catch (error) {
100
+ throw new Error(`Failed to initialize: ${error instanceof Error ? error.message : "Unknown error"}`);
101
+ }
102
+ });
103
+ }
104
+ /**
105
+ * Creates a payment checkout component for the specified payment method.
106
+ *
107
+ * @returns The created Adyen component (Card or PayByBankUS)
108
+ * @throws {Error} If init() hasn't been called or if payment method is unsupported
109
+ *
110
+ * @example Credit card with custom styling
111
+ * ```typescript
112
+ * const cardComponent = await financialService.createCheckout('credit_card', {
113
+ * locale: 'en-US',
114
+ * creditCardOptions: {
115
+ * hasHolderName: true,
116
+ * holderNameRequired: true,
117
+ * showBrandIcon: true,
118
+ * placeholders: {
119
+ * cardNumber: 'Card number',
120
+ * expiryDate: 'MM/YY',
121
+ * securityCodeThreeDigits: 'CVV'
122
+ * }
123
+ * },
124
+ * onChange: (state) => {
125
+ * // Update UI based on validation state
126
+ * submitButton.disabled = !state.isValid;
127
+ * }
128
+ * });
129
+ * ```
130
+ */
131
+ createCheckout(type_1) {
132
+ return _tslib.__awaiter(this, arguments, void 0, function* (type, options = {}) {
133
+ if (!this.isReady()) {
134
+ throw new Error("No session data. Please call init() first.");
135
+ }
136
+ const coreConfig = this.getCoreConfig(options);
137
+ try {
138
+ this.checkout = yield adyenWeb.AdyenCheckout(coreConfig);
139
+ // Create the specific component based on payment method type
140
+ if (type === "credit_card") {
141
+ this.activeComponent = this.createCreditCardComponent(options.creditCardOptions);
142
+ } else if (type === "pay_by_bank_us") {
143
+ this.activeComponent = this.createPayByBankComponent();
144
+ } else {
145
+ throw new Error(`Unsupported payment method type: ${type}`);
146
+ }
147
+ if (!this.activeComponent) {
148
+ throw new Error("Failed to create payment component");
149
+ }
150
+ return this.activeComponent;
151
+ } catch (error) {
152
+ throw new Error(`Failed to create checkout: ${error instanceof Error ? error.message : "Unknown error"}`);
153
+ }
154
+ });
155
+ }
156
+ /**
157
+ * Mounts the active payment component to a DOM element.
158
+ *
159
+ * @param element - DOM element or CSS selector where the component should be mounted
160
+ * @throws Error If no active component exists (createCheckout must be called first)
161
+ *
162
+ * @example
163
+ * ```typescript
164
+ * // Mount to element by ID
165
+ * financialService.mount('#payment-form');
166
+ *
167
+ * // Mount to DOM element
168
+ * const container = document.getElementById('payment-container');
169
+ * financialService.mount(container);
170
+ * ```
171
+ */
172
+ mount(element) {
173
+ if (!this.activeComponent) {
174
+ throw new Error("No active component. Please call createCheckout() first.");
175
+ }
176
+ this.activeComponent.mount(element);
177
+ }
178
+ /**
179
+ * Submits the payment using the active component.
180
+ * Triggers validation and payment processing.
181
+ *
182
+ * @throws Error If no active component exists
183
+ *
184
+ * @example
185
+ * ```typescript
186
+ * // In a form submit handler
187
+ * form.addEventListener('submit', (e) => {
188
+ * e.preventDefault();
189
+ * financialService.submit();
190
+ * });
191
+ * ```
192
+ */
193
+ submit() {
194
+ if (!this.activeComponent) {
195
+ throw new Error("No active component. Please call createCheckout() first.");
196
+ }
197
+ this.activeComponent.submit();
198
+ }
199
+ /**
200
+ * Submits the payment and returns a Promise that resolves with the payment result.
201
+ * This method should be used when you need to wait for payment completion.
202
+ *
203
+ * @returns Promise that resolves with PaymentResult
204
+ * @throws Error If no active component exists
205
+ *
206
+ * @example
207
+ * ```typescript
208
+ * try {
209
+ * const result = await financialService.submitPayment();
210
+ * if (result.success) {
211
+ * console.log('Payment successful!', result.resultCode);
212
+ * } else {
213
+ * console.error('Payment failed:', result.error);
214
+ * }
215
+ * } catch (error) {
216
+ * console.error('Payment error:', error);
217
+ * }
218
+ * ```
219
+ */
220
+ submitPromise() {
221
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
222
+ if (!this.activeComponent) {
223
+ throw new Error("No active component. Please call createCheckout() first.");
224
+ }
225
+ return new Promise((resolve, reject) => {
226
+ this.paymentPromise = {
227
+ resolve,
228
+ reject
229
+ };
230
+ this.activeComponent.submit();
231
+ });
232
+ });
233
+ }
234
+ /**
235
+ * Unmounts and cleans up the active payment component.
236
+ * Should be called when the component is no longer needed.
237
+ *
238
+ * @example
239
+ * ```typescript
240
+ * // Clean up on component unmount (React example)
241
+ * useEffect(() => {
242
+ * return () => {
243
+ * financialService.unmount();
244
+ * };
245
+ * }, []);
246
+ * ```
247
+ */
248
+ unmount() {
249
+ if (this.activeComponent && "unmount" in this.activeComponent) {
250
+ this.activeComponent.unmount();
251
+ }
252
+ this.activeComponent = undefined;
253
+ }
254
+ /**
255
+ * Resets the payment component to ready state, allowing user to edit fields and retry.
256
+ * This is useful after a failed payment to unlock the form fields.
257
+ *
258
+ * @example
259
+ * ```typescript
260
+ * // After a failed payment
261
+ * const result = await financialService.submitPromise();
262
+ * if (!result.success) {
263
+ * // Reset the component to allow retry
264
+ * financialService.resetComponent();
265
+ * // Show error message to user
266
+ * }
267
+ * ```
268
+ */
269
+ resetComponent() {
270
+ if (this.activeComponent && "setStatus" in this.activeComponent) {
271
+ this.activeComponent.setStatus("ready");
272
+ }
273
+ }
274
+ /**
275
+ * Returns the current Adyen session data if available.
276
+ * Useful for accessing session metadata or debugging.
277
+ *
278
+ * @returns The current session data or undefined if not initialized
279
+ *
280
+ * @example
281
+ * ```typescript
282
+ * const sessionData = financialService.getCurrentSessionData();
283
+ * if (sessionData) {
284
+ * console.log('Session ID:', sessionData.metadata.adyenSessionId);
285
+ * console.log('Expires:', sessionData.metadata.adyenExpiration);
286
+ * }
287
+ * ```
288
+ */
289
+ getCurrentSessionData() {
290
+ return this.adyenCheckoutData;
291
+ }
292
+ /**
293
+ * Handles the return flow from payment redirects (3D Secure, bank authentication, etc.).
294
+ * Should be called on your return URL page with the redirect parameters.
295
+ *
296
+ * @example
297
+ * ```typescript
298
+ * // On your return URL page
299
+ * const urlParams = new URLSearchParams(window.location.search);
300
+ *
301
+ * await financialService.handleRedirect({
302
+ * sessionId: urlParams.get('sessionId'),
303
+ * redirectResult: urlParams.get('redirectResult'),
304
+ * onPaymentCompleted: (result) => {
305
+ * switch (result.resultCode) {
306
+ * case 'Authorised':
307
+ * ...
308
+ * break;
309
+ * case 'Pending':
310
+ * ...
311
+ * break;
312
+ * default:
313
+ * ...
314
+ * }
315
+ * },
316
+ * onError: (error) => {
317
+ * console.error('Redirect handling failed:', error);
318
+ * showErrorMessage('Payment verification failed');
319
+ * }
320
+ * });
321
+ * ```
322
+ */
323
+ handleRedirect(options) {
324
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
325
+ const {
326
+ sessionId,
327
+ redirectResult,
328
+ clientKey,
329
+ locale = "en-US",
330
+ countryCode = "US"
331
+ } = options,
332
+ rest = _tslib.__rest(options, ["sessionId", "redirectResult", "clientKey", "locale", "countryCode"]);
333
+ if (!sessionId || !redirectResult) {
334
+ throw new Error("Missing sessionId or redirectResult, unable to complete checkout");
335
+ }
336
+ // Determine client key - use provided one or try to get from existing session data
337
+ let finalClientKey = clientKey;
338
+ if (!finalClientKey && this.adyenCheckoutData) {
339
+ finalClientKey = this.adyenCheckoutData.metadata.adyenClientKey;
340
+ }
341
+ if (!finalClientKey) {
342
+ throw new Error("Client key not found, unable to complete checkout");
343
+ }
344
+ const environment = this.parseEnvironment(finalClientKey);
345
+ try {
346
+ // Create a new checkout instance specifically for handling the redirect
347
+ const redirectCheckout = yield adyenWeb.AdyenCheckout(Object.assign({
348
+ environment,
349
+ clientKey: finalClientKey,
350
+ session: {
351
+ id: sessionId
352
+ },
353
+ locale,
354
+ countryCode
355
+ }, rest));
356
+ // Submit the redirect details to complete the payment
357
+ redirectCheckout.submitDetails({
358
+ details: {
359
+ redirectResult
360
+ }
361
+ });
362
+ } catch (error) {
363
+ throw new Error(`Failed to handle redirect: ${error instanceof Error ? error.message : "Unknown error"}`);
364
+ }
365
+ });
366
+ }
367
+ getCoreConfig(options) {
368
+ if (!this.adyenCheckoutData) {
369
+ throw new Error("No session data available");
370
+ }
371
+ const {
372
+ metadata: {
373
+ adyenClientKey,
374
+ adyenSessionId,
375
+ adyenSessionData
376
+ }
377
+ } = this.adyenCheckoutData;
378
+ // Determine environment from client key
379
+ const environment = options.environment || this.parseEnvironment(adyenClientKey);
380
+ // Exclude creditCardOptions from the core config as it's component-specific
381
+ const coreOptions = _tslib.__rest(options, ["creditCardOptions"]);
382
+ const config = Object.assign(Object.assign({
383
+ environment,
384
+ clientKey: adyenClientKey,
385
+ session: {
386
+ id: adyenSessionId,
387
+ sessionData: adyenSessionData
388
+ },
389
+ locale: options.locale || "en-US",
390
+ countryCode: options.countryCode || "US"
391
+ }, coreOptions), {
392
+ // Override callbacks to handle Promise resolution while preserving original callbacks
393
+ onPaymentCompleted: result => {
394
+ // Call original callback if provided
395
+ var _a;
396
+ (_a = options.onPaymentCompleted) === null || _a === void 0 ? void 0 : _a.call(options, result);
397
+ // Resolve Promise if waiting
398
+ if (this.paymentPromise) {
399
+ const paymentResult = {
400
+ success: result.resultCode === "Authorised" || result.resultCode === "Received",
401
+ resultCode: result.resultCode,
402
+ data: result
403
+ };
404
+ this.paymentPromise.resolve(paymentResult);
405
+ this.paymentPromise = undefined;
406
+ }
407
+ },
408
+ onPaymentFailed: result => {
409
+ // Call original callback if provided
410
+ var _a;
411
+ (_a = options.onPaymentFailed) === null || _a === void 0 ? void 0 : _a.call(options, result);
412
+ // Reset component to unlock form fields for retry
413
+ this.resetComponent();
414
+ // Resolve Promise with failure if waiting
415
+ if (this.paymentPromise) {
416
+ const paymentResult = {
417
+ success: false,
418
+ resultCode: result === null || result === void 0 ? void 0 : result.resultCode,
419
+ error: (result === null || result === void 0 ? void 0 : result.resultCode) ? `Payment failed: ${result.resultCode}` : "Payment failed",
420
+ data: result
421
+ };
422
+ this.paymentPromise.resolve(paymentResult);
423
+ this.paymentPromise = undefined;
424
+ }
425
+ },
426
+ onError: error => {
427
+ // Call original callback if provided
428
+ var _a;
429
+ (_a = options.onError) === null || _a === void 0 ? void 0 : _a.call(options, error);
430
+ // Reset component to unlock form fields for retry
431
+ this.resetComponent();
432
+ // Reject Promise if waiting
433
+ if (this.paymentPromise) {
434
+ this.paymentPromise.reject(new Error(error.message || "Payment processing error"));
435
+ this.paymentPromise = undefined;
436
+ }
437
+ }
438
+ });
439
+ if (options.beforeSubmit) {
440
+ config.beforeSubmit = options.beforeSubmit;
441
+ }
442
+ if (options.onChange) {
443
+ config.onChange = options.onChange;
444
+ }
445
+ return config;
446
+ }
447
+ createCreditCardComponent(creditCardOptions) {
448
+ if (!this.checkout) {
449
+ throw new Error("Checkout not initialized");
450
+ }
451
+ return new adyenWeb.Card(this.checkout, creditCardOptions);
452
+ }
453
+ createPayByBankComponent() {
454
+ if (!this.checkout) {
455
+ throw new Error("Checkout not initialized");
456
+ }
457
+ return new adyenWeb.PayByBankUS(this.checkout);
458
+ }
459
+ parseEnvironment(clientKey) {
460
+ return clientKey.startsWith("test_") ? "test" : "live";
461
+ }
462
+ }
463
+
464
+ exports.FinancialService = FinancialService;
@@ -0,0 +1,9 @@
1
+ 'use strict';
2
+
3
+ var financialService = require('./financial-service.cjs');
4
+ var useFinancialService = require('./use-financial-service.cjs');
5
+
6
+
7
+
8
+ exports.FinancialService = financialService.FinancialService;
9
+ exports.useFinancialService = useFinancialService.useFinancialService;