@blocklet/payment-react-headless 1.26.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 (250) hide show
  1. package/.eslintrc.js +18 -0
  2. package/build.config.ts +30 -0
  3. package/es/checkout/context/CheckoutProvider.d.ts +6 -0
  4. package/es/checkout/context/CheckoutProvider.js +209 -0
  5. package/es/checkout/context/CustomerFormContext.d.ts +4 -0
  6. package/es/checkout/context/CustomerFormContext.js +9 -0
  7. package/es/checkout/context/ExchangeRateContext.d.ts +11 -0
  8. package/es/checkout/context/ExchangeRateContext.js +9 -0
  9. package/es/checkout/context/PaymentMethodContext.d.ts +26 -0
  10. package/es/checkout/context/PaymentMethodContext.js +9 -0
  11. package/es/checkout/context/SessionContext.d.ts +45 -0
  12. package/es/checkout/context/SessionContext.js +9 -0
  13. package/es/checkout/context/SubmitContext.d.ts +4 -0
  14. package/es/checkout/context/SubmitContext.js +9 -0
  15. package/es/checkout/context/index.d.ts +6 -0
  16. package/es/checkout/context/index.js +6 -0
  17. package/es/checkout/core/billingInterval.d.ts +15 -0
  18. package/es/checkout/core/billingInterval.js +36 -0
  19. package/es/checkout/core/crossSell.d.ts +4 -0
  20. package/es/checkout/core/crossSell.js +30 -0
  21. package/es/checkout/core/customerForm.d.ts +5 -0
  22. package/es/checkout/core/customerForm.js +105 -0
  23. package/es/checkout/core/exchangeRate.d.ts +11 -0
  24. package/es/checkout/core/exchangeRate.js +25 -0
  25. package/es/checkout/core/index.d.ts +10 -0
  26. package/es/checkout/core/index.js +55 -0
  27. package/es/checkout/core/lineItems.d.ts +7 -0
  28. package/es/checkout/core/lineItems.js +59 -0
  29. package/es/checkout/core/paymentMethod.d.ts +23 -0
  30. package/es/checkout/core/paymentMethod.js +85 -0
  31. package/es/checkout/core/pricing.d.ts +32 -0
  32. package/es/checkout/core/pricing.js +221 -0
  33. package/es/checkout/core/promotion.d.ts +10 -0
  34. package/es/checkout/core/promotion.js +39 -0
  35. package/es/checkout/core/session.d.ts +26 -0
  36. package/es/checkout/core/session.js +50 -0
  37. package/es/checkout/core/submit.d.ts +40 -0
  38. package/es/checkout/core/submit.js +66 -0
  39. package/es/checkout/hooks/index.d.ts +34 -0
  40. package/es/checkout/hooks/index.js +19 -0
  41. package/es/checkout/hooks/useBillingInterval.d.ts +14 -0
  42. package/es/checkout/hooks/useBillingInterval.js +50 -0
  43. package/es/checkout/hooks/useCheckout.d.ts +2 -0
  44. package/es/checkout/hooks/useCheckout.js +212 -0
  45. package/es/checkout/hooks/useCheckoutSession.d.ts +58 -0
  46. package/es/checkout/hooks/useCheckoutSession.js +107 -0
  47. package/es/checkout/hooks/useCheckoutStatus.d.ts +10 -0
  48. package/es/checkout/hooks/useCheckoutStatus.js +16 -0
  49. package/es/checkout/hooks/useCrossSell.d.ts +8 -0
  50. package/es/checkout/hooks/useCrossSell.js +57 -0
  51. package/es/checkout/hooks/useCustomerForm.d.ts +14 -0
  52. package/es/checkout/hooks/useCustomerForm.js +116 -0
  53. package/es/checkout/hooks/useCustomerFormFeature.d.ts +2 -0
  54. package/es/checkout/hooks/useCustomerFormFeature.js +4 -0
  55. package/es/checkout/hooks/useExchangeRate.d.ts +11 -0
  56. package/es/checkout/hooks/useExchangeRate.js +15 -0
  57. package/es/checkout/hooks/useLineItems.d.ts +22 -0
  58. package/es/checkout/hooks/useLineItems.js +139 -0
  59. package/es/checkout/hooks/usePaymentMethod.d.ts +26 -0
  60. package/es/checkout/hooks/usePaymentMethod.js +101 -0
  61. package/es/checkout/hooks/usePaymentMethodFeature.d.ts +2 -0
  62. package/es/checkout/hooks/usePaymentMethodFeature.js +4 -0
  63. package/es/checkout/hooks/usePricing.d.ts +57 -0
  64. package/es/checkout/hooks/usePricing.js +174 -0
  65. package/es/checkout/hooks/usePricingFeature.d.ts +28 -0
  66. package/es/checkout/hooks/usePricingFeature.js +36 -0
  67. package/es/checkout/hooks/useProduct.d.ts +32 -0
  68. package/es/checkout/hooks/useProduct.js +5 -0
  69. package/es/checkout/hooks/usePromotion.d.ts +12 -0
  70. package/es/checkout/hooks/usePromotion.js +48 -0
  71. package/es/checkout/hooks/useSlippage.d.ts +8 -0
  72. package/es/checkout/hooks/useSlippage.js +29 -0
  73. package/es/checkout/hooks/useSubmit.d.ts +38 -0
  74. package/es/checkout/hooks/useSubmit.js +493 -0
  75. package/es/checkout/hooks/useSubmitFeature.d.ts +2 -0
  76. package/es/checkout/hooks/useSubmitFeature.js +4 -0
  77. package/es/checkout/hooks/useUpsell.d.ts +5 -0
  78. package/es/checkout/hooks/useUpsell.js +25 -0
  79. package/es/checkout/index.d.ts +37 -0
  80. package/es/checkout/index.js +28 -0
  81. package/es/checkout/types.d.ts +262 -0
  82. package/es/checkout/types.js +0 -0
  83. package/es/index.d.ts +1 -0
  84. package/es/index.js +28 -0
  85. package/es/shared/api.d.ts +41 -0
  86. package/es/shared/api.js +81 -0
  87. package/es/shared/format.d.ts +38 -0
  88. package/es/shared/format.js +229 -0
  89. package/es/shared/polling.d.ts +15 -0
  90. package/es/shared/polling.js +20 -0
  91. package/es/shared/types.d.ts +10 -0
  92. package/es/shared/types.js +0 -0
  93. package/es/shared/validation.d.ts +38 -0
  94. package/es/shared/validation.js +190 -0
  95. package/es/types/checkout-augmented.d.ts +42 -0
  96. package/es/types/checkout-augmented.js +17 -0
  97. package/es/types/external.d.ts +18 -0
  98. package/examples/01-basic-checkout.tsx +159 -0
  99. package/examples/01-credit-recharge.tsx +19 -0
  100. package/examples/02-subscription.tsx +40 -0
  101. package/examples/03-upsell.tsx +60 -0
  102. package/examples/04-cross-sell.tsx +54 -0
  103. package/examples/05-full-checkout.tsx +126 -0
  104. package/jest.config.js +15 -0
  105. package/lib/checkout/context/CheckoutProvider.d.ts +6 -0
  106. package/lib/checkout/context/CheckoutProvider.js +181 -0
  107. package/lib/checkout/context/CustomerFormContext.d.ts +4 -0
  108. package/lib/checkout/context/CustomerFormContext.js +16 -0
  109. package/lib/checkout/context/ExchangeRateContext.d.ts +11 -0
  110. package/lib/checkout/context/ExchangeRateContext.js +16 -0
  111. package/lib/checkout/context/PaymentMethodContext.d.ts +26 -0
  112. package/lib/checkout/context/PaymentMethodContext.js +16 -0
  113. package/lib/checkout/context/SessionContext.d.ts +45 -0
  114. package/lib/checkout/context/SessionContext.js +16 -0
  115. package/lib/checkout/context/SubmitContext.d.ts +4 -0
  116. package/lib/checkout/context/SubmitContext.js +16 -0
  117. package/lib/checkout/context/index.d.ts +6 -0
  118. package/lib/checkout/context/index.js +77 -0
  119. package/lib/checkout/core/billingInterval.d.ts +15 -0
  120. package/lib/checkout/core/billingInterval.js +42 -0
  121. package/lib/checkout/core/crossSell.d.ts +4 -0
  122. package/lib/checkout/core/crossSell.js +43 -0
  123. package/lib/checkout/core/customerForm.d.ts +5 -0
  124. package/lib/checkout/core/customerForm.js +106 -0
  125. package/lib/checkout/core/exchangeRate.d.ts +11 -0
  126. package/lib/checkout/core/exchangeRate.js +45 -0
  127. package/lib/checkout/core/index.d.ts +10 -0
  128. package/lib/checkout/core/index.js +297 -0
  129. package/lib/checkout/core/lineItems.d.ts +7 -0
  130. package/lib/checkout/core/lineItems.js +76 -0
  131. package/lib/checkout/core/paymentMethod.d.ts +23 -0
  132. package/lib/checkout/core/paymentMethod.js +114 -0
  133. package/lib/checkout/core/pricing.d.ts +32 -0
  134. package/lib/checkout/core/pricing.js +216 -0
  135. package/lib/checkout/core/promotion.d.ts +10 -0
  136. package/lib/checkout/core/promotion.js +62 -0
  137. package/lib/checkout/core/session.d.ts +26 -0
  138. package/lib/checkout/core/session.js +58 -0
  139. package/lib/checkout/core/submit.d.ts +40 -0
  140. package/lib/checkout/core/submit.js +84 -0
  141. package/lib/checkout/hooks/index.d.ts +34 -0
  142. package/lib/checkout/hooks/index.js +138 -0
  143. package/lib/checkout/hooks/useBillingInterval.d.ts +14 -0
  144. package/lib/checkout/hooks/useBillingInterval.js +63 -0
  145. package/lib/checkout/hooks/useCheckout.d.ts +2 -0
  146. package/lib/checkout/hooks/useCheckout.js +190 -0
  147. package/lib/checkout/hooks/useCheckoutSession.d.ts +58 -0
  148. package/lib/checkout/hooks/useCheckoutSession.js +119 -0
  149. package/lib/checkout/hooks/useCheckoutStatus.d.ts +10 -0
  150. package/lib/checkout/hooks/useCheckoutStatus.js +28 -0
  151. package/lib/checkout/hooks/useCrossSell.d.ts +8 -0
  152. package/lib/checkout/hooks/useCrossSell.js +75 -0
  153. package/lib/checkout/hooks/useCustomerForm.d.ts +14 -0
  154. package/lib/checkout/hooks/useCustomerForm.js +135 -0
  155. package/lib/checkout/hooks/useCustomerFormFeature.d.ts +2 -0
  156. package/lib/checkout/hooks/useCustomerFormFeature.js +10 -0
  157. package/lib/checkout/hooks/useExchangeRate.d.ts +11 -0
  158. package/lib/checkout/hooks/useExchangeRate.js +29 -0
  159. package/lib/checkout/hooks/useLineItems.d.ts +22 -0
  160. package/lib/checkout/hooks/useLineItems.js +142 -0
  161. package/lib/checkout/hooks/usePaymentMethod.d.ts +26 -0
  162. package/lib/checkout/hooks/usePaymentMethod.js +101 -0
  163. package/lib/checkout/hooks/usePaymentMethodFeature.d.ts +2 -0
  164. package/lib/checkout/hooks/usePaymentMethodFeature.js +10 -0
  165. package/lib/checkout/hooks/usePricing.d.ts +57 -0
  166. package/lib/checkout/hooks/usePricing.js +168 -0
  167. package/lib/checkout/hooks/usePricingFeature.d.ts +28 -0
  168. package/lib/checkout/hooks/usePricingFeature.js +48 -0
  169. package/lib/checkout/hooks/useProduct.d.ts +32 -0
  170. package/lib/checkout/hooks/useProduct.js +21 -0
  171. package/lib/checkout/hooks/usePromotion.d.ts +12 -0
  172. package/lib/checkout/hooks/usePromotion.js +57 -0
  173. package/lib/checkout/hooks/useSlippage.d.ts +8 -0
  174. package/lib/checkout/hooks/useSlippage.js +39 -0
  175. package/lib/checkout/hooks/useSubmit.d.ts +38 -0
  176. package/lib/checkout/hooks/useSubmit.js +504 -0
  177. package/lib/checkout/hooks/useSubmitFeature.d.ts +2 -0
  178. package/lib/checkout/hooks/useSubmitFeature.js +10 -0
  179. package/lib/checkout/hooks/useUpsell.d.ts +5 -0
  180. package/lib/checkout/hooks/useUpsell.js +40 -0
  181. package/lib/checkout/index.d.ts +37 -0
  182. package/lib/checkout/index.js +182 -0
  183. package/lib/checkout/types.d.ts +262 -0
  184. package/lib/checkout/types.js +1 -0
  185. package/lib/index.d.ts +1 -0
  186. package/lib/index.js +162 -0
  187. package/lib/shared/api.d.ts +41 -0
  188. package/lib/shared/api.js +88 -0
  189. package/lib/shared/format.d.ts +38 -0
  190. package/lib/shared/format.js +262 -0
  191. package/lib/shared/polling.d.ts +15 -0
  192. package/lib/shared/polling.js +32 -0
  193. package/lib/shared/types.d.ts +10 -0
  194. package/lib/shared/types.js +1 -0
  195. package/lib/shared/validation.d.ts +38 -0
  196. package/lib/shared/validation.js +212 -0
  197. package/lib/types/checkout-augmented.d.ts +42 -0
  198. package/lib/types/checkout-augmented.js +24 -0
  199. package/lib/types/external.d.ts +18 -0
  200. package/package.json +64 -0
  201. package/src/checkout/context/CheckoutProvider.tsx +269 -0
  202. package/src/checkout/context/CustomerFormContext.ts +14 -0
  203. package/src/checkout/context/ExchangeRateContext.ts +21 -0
  204. package/src/checkout/context/PaymentMethodContext.ts +36 -0
  205. package/src/checkout/context/SessionContext.ts +49 -0
  206. package/src/checkout/context/SubmitContext.ts +14 -0
  207. package/src/checkout/context/index.ts +6 -0
  208. package/src/checkout/core/billingInterval.ts +62 -0
  209. package/src/checkout/core/crossSell.ts +52 -0
  210. package/src/checkout/core/customerForm.ts +122 -0
  211. package/src/checkout/core/exchangeRate.ts +38 -0
  212. package/src/checkout/core/index.ts +60 -0
  213. package/src/checkout/core/lineItems.ts +106 -0
  214. package/src/checkout/core/paymentMethod.ts +113 -0
  215. package/src/checkout/core/pricing.ts +347 -0
  216. package/src/checkout/core/promotion.ts +59 -0
  217. package/src/checkout/core/session.ts +62 -0
  218. package/src/checkout/core/submit.ts +109 -0
  219. package/src/checkout/hooks/index.ts +41 -0
  220. package/src/checkout/hooks/useBillingInterval.ts +71 -0
  221. package/src/checkout/hooks/useCheckout.ts +267 -0
  222. package/src/checkout/hooks/useCheckoutSession.ts +217 -0
  223. package/src/checkout/hooks/useCheckoutStatus.ts +31 -0
  224. package/src/checkout/hooks/useCrossSell.ts +80 -0
  225. package/src/checkout/hooks/useCustomerForm.ts +156 -0
  226. package/src/checkout/hooks/useCustomerFormFeature.ts +7 -0
  227. package/src/checkout/hooks/useExchangeRate.ts +28 -0
  228. package/src/checkout/hooks/useLineItems.ts +191 -0
  229. package/src/checkout/hooks/usePaymentMethod.ts +165 -0
  230. package/src/checkout/hooks/usePaymentMethodFeature.ts +8 -0
  231. package/src/checkout/hooks/usePricing.ts +274 -0
  232. package/src/checkout/hooks/usePricingFeature.ts +73 -0
  233. package/src/checkout/hooks/useProduct.ts +32 -0
  234. package/src/checkout/hooks/usePromotion.ts +67 -0
  235. package/src/checkout/hooks/useSlippage.ts +39 -0
  236. package/src/checkout/hooks/useSubmit.ts +684 -0
  237. package/src/checkout/hooks/useSubmitFeature.ts +7 -0
  238. package/src/checkout/hooks/useUpsell.ts +35 -0
  239. package/src/checkout/index.ts +65 -0
  240. package/src/checkout/types.ts +292 -0
  241. package/src/index.ts +64 -0
  242. package/src/shared/api.ts +118 -0
  243. package/src/shared/format.ts +318 -0
  244. package/src/shared/polling.ts +49 -0
  245. package/src/shared/types.ts +13 -0
  246. package/src/shared/validation.ts +254 -0
  247. package/src/types/checkout-augmented.ts +77 -0
  248. package/src/types/external.d.ts +18 -0
  249. package/tools/jest.js +1 -0
  250. package/tsconfig.json +18 -0
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ module.exports = exports.API = void 0;
7
+ exports.getLocale = getLocale;
8
+ exports.getPrefix = getPrefix;
9
+ var _jsSdk = require("@blocklet/js-sdk");
10
+ var _isNull = _interopRequireDefault(require("lodash/isNull"));
11
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
12
+ const PAYMENT_KIT_DID = "z2qaCNvKMv5GjouKdcDWexv6WqtHbpNPQDnAk";
13
+ function getPrefix() {
14
+ const prefix = window.blocklet?.prefix || "/";
15
+ const baseUrl = window.location?.origin;
16
+ if (window.__PAYMENT_KIT_BASE_URL) {
17
+ try {
18
+ const tmp = new URL(window.__PAYMENT_KIT_BASE_URL);
19
+ if (tmp.origin !== window.location.origin) {
20
+ return window.__PAYMENT_KIT_BASE_URL;
21
+ }
22
+ } catch {}
23
+ }
24
+ const componentId = (window.blocklet?.componentId || "").split("/").pop();
25
+ if (componentId === PAYMENT_KIT_DID) {
26
+ return `${baseUrl}${prefix}`;
27
+ }
28
+ const component = (window.blocklet?.componentMountPoints || []).find(x => x?.did === PAYMENT_KIT_DID);
29
+ if (component) {
30
+ return `${baseUrl}${component.mountPoint}`;
31
+ }
32
+ return `${baseUrl}${prefix}`;
33
+ }
34
+ function getLocale(languages) {
35
+ if (typeof window === "undefined") return "en";
36
+ try {
37
+ const stored = localStorage.getItem("locale");
38
+ if (stored) return stored;
39
+ } catch {}
40
+ if (languages && languages.length > 0) return languages[0];
41
+ return navigator.language?.split("-")[0] || "en";
42
+ }
43
+ function createApi() {
44
+ const api2 = (0, _jsSdk.createAxios)();
45
+ api2.interceptors.request.use(config => {
46
+ const prefix = getPrefix();
47
+ config.baseURL = prefix || "";
48
+ const locale = getLocale(window.blocklet?.languages);
49
+ const query = new URLSearchParams(config.url?.split("?").pop());
50
+ config.params = {
51
+ ...(config.params || {}),
52
+ locale
53
+ };
54
+ const authToken = window.__PAYMENT_KIT_AUTH_TOKEN;
55
+ if (authToken && typeof config.params.authToken === "undefined" && !query.has("authToken")) {
56
+ config.params.authToken = authToken;
57
+ }
58
+ if (typeof config.params.livemode === "undefined" && query.has("livemode") === false) {
59
+ const livemode = localStorage.getItem("livemode");
60
+ config.params.livemode = (0, _isNull.default)(livemode) ? true : JSON.parse(livemode);
61
+ }
62
+ return config;
63
+ }, err => Promise.reject(err));
64
+ return api2;
65
+ }
66
+ const api = createApi();
67
+ module.exports = api;
68
+ const API = exports.API = {
69
+ START_PAYMENT_LINK: id => `/api/checkout-sessions/start/${id}`,
70
+ RETRIEVE_SESSION: id => `/api/checkout-sessions/retrieve/${id}`,
71
+ SWITCH_CURRENCY: id => `/api/checkout-sessions/${id}/switch-currency`,
72
+ SUBMIT: id => `/api/checkout-sessions/${id}/submit`,
73
+ DONATE_SUBMIT: id => `/api/checkout-sessions/${id}/donate-submit`,
74
+ FAST_CHECKOUT_CONFIRM: id => `/api/checkout-sessions/${id}/fast-checkout-confirm`,
75
+ EXCHANGE_RATE: id => `/api/checkout-sessions/${id}/exchange-rate`,
76
+ ADJUST_QUANTITY: id => `/api/checkout-sessions/${id}/adjust-quantity`,
77
+ UPSELL: id => `/api/checkout-sessions/${id}/upsell`,
78
+ DOWNSELL: id => `/api/checkout-sessions/${id}/downsell`,
79
+ CROSS_SELL: id => `/api/checkout-sessions/${id}/cross-sell`,
80
+ CHANGE_AMOUNT: id => `/api/checkout-sessions/${id}/amount`,
81
+ SLIPPAGE: id => `/api/checkout-sessions/${id}/slippage`,
82
+ ABORT_STRIPE: id => `/api/checkout-sessions/${id}/abort-stripe`,
83
+ RECALCULATE_PROMOTION_SESSION: id => `/api/checkout-sessions/${id}/recalculate-promotion`,
84
+ APPLY_PROMOTION: id => `/api/checkout-sessions/${id}/apply-promotion`,
85
+ REMOVE_PROMOTION: id => `/api/checkout-sessions/${id}/remove-promotion`,
86
+ CUSTOMER_ME: "/api/customers/me",
87
+ VENDOR_ORDER_STATUS: id => `/api/vendors/order/${id}/status`
88
+ };
@@ -0,0 +1,38 @@
1
+ import { BN } from '@ocap/util';
2
+ import type { TPaymentCurrency, TPrice, TLineItemExpanded } from '@blocklet/payment-types';
3
+ export declare function formatNumber(n: number | string, precision?: number, trim?: boolean, thousandSeparated?: boolean): string;
4
+ export declare function formatBNStr(str?: string, decimals?: number, precision?: number, trim?: boolean, thousandSeparated?: boolean): string;
5
+ export declare function formatDynamicPrice(n: number | string, isDynamic: boolean, precision?: number, trim?: boolean, thousandSeparated?: boolean): string;
6
+ export declare function getUsdAmountFromTokenUnits(tokenAmount: BN | string, tokenDecimals: number, exchangeRate?: string | null): string | null;
7
+ export declare function formatUsdAmount(amount: string | null, locale?: string): string | null;
8
+ export declare function formatExchangeRate(amount: string | null): string | null;
9
+ export declare function formatExchangeRateDisplay(rate: string | number | null | undefined, currency?: string, decimals?: number): string | null;
10
+ export declare function formatAmount(amount: string, decimals: number, precision?: number): string;
11
+ export declare function getPriceCurrencyOptions(price: TPrice): Array<{
12
+ currency_id: string;
13
+ unit_amount: string;
14
+ custom_unit_amount: {
15
+ preset?: string;
16
+ presets: string[];
17
+ } | null;
18
+ tiers: unknown;
19
+ }>;
20
+ export declare function getPriceUnitAmountByCurrency(price: TPrice, currency: TPaymentCurrency): string;
21
+ export declare function getLineItemAmounts(item: TLineItemExpanded, currency: TPaymentCurrency, { useUpsell, exchangeRate }?: {
22
+ useUpsell?: boolean;
23
+ exchangeRate?: string | null;
24
+ }): {
25
+ unitAmount: BN;
26
+ totalAmount: BN;
27
+ isDynamicQuote: boolean;
28
+ };
29
+ export declare function getCheckoutAmount(items: TLineItemExpanded[], currency: TPaymentCurrency, trialing?: boolean, upsell?: boolean, { exchangeRate }?: {
30
+ exchangeRate?: string | null;
31
+ }): {
32
+ subtotal: string;
33
+ total: string;
34
+ renew: string;
35
+ discount: string;
36
+ shipping: string;
37
+ tax: string;
38
+ };
@@ -0,0 +1,262 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.formatAmount = formatAmount;
7
+ exports.formatBNStr = formatBNStr;
8
+ exports.formatDynamicPrice = formatDynamicPrice;
9
+ exports.formatExchangeRate = formatExchangeRate;
10
+ exports.formatExchangeRateDisplay = formatExchangeRateDisplay;
11
+ exports.formatNumber = formatNumber;
12
+ exports.formatUsdAmount = formatUsdAmount;
13
+ exports.getCheckoutAmount = getCheckoutAmount;
14
+ exports.getLineItemAmounts = getLineItemAmounts;
15
+ exports.getPriceCurrencyOptions = getPriceCurrencyOptions;
16
+ exports.getPriceUnitAmountByCurrency = getPriceUnitAmountByCurrency;
17
+ exports.getUsdAmountFromTokenUnits = getUsdAmountFromTokenUnits;
18
+ var _util = require("@ocap/util");
19
+ function formatNumber(n, precision = 6, trim = true, thousandSeparated = true) {
20
+ if (!n || n === "0") {
21
+ return "0";
22
+ }
23
+ const num = Number(n);
24
+ if (!Number.isFinite(num)) {
25
+ return "0";
26
+ }
27
+ let result;
28
+ if (thousandSeparated) {
29
+ result = num.toLocaleString("en-US", {
30
+ minimumFractionDigits: precision,
31
+ maximumFractionDigits: precision
32
+ });
33
+ } else {
34
+ result = num.toFixed(precision);
35
+ }
36
+ if (!trim) {
37
+ return result;
38
+ }
39
+ const [left, right] = result.split(".");
40
+ if (!right) return left;
41
+ const trimmed = right.replace(/0+$/, "");
42
+ return trimmed ? `${left}.${trimmed}` : left;
43
+ }
44
+ function formatBNStr(str = "", decimals = 18, precision = 6, trim = true, thousandSeparated = true) {
45
+ if (!str) {
46
+ return "0";
47
+ }
48
+ return formatNumber((0, _util.fromUnitToToken)(str, decimals), precision, trim, thousandSeparated);
49
+ }
50
+ function formatDynamicPrice(n, isDynamic, precision = 6, trim = true, thousandSeparated = true) {
51
+ if (!isDynamic) {
52
+ return formatNumber(n, precision, trim, thousandSeparated);
53
+ }
54
+ const num = Number(n);
55
+ if (!Number.isFinite(num)) {
56
+ return formatNumber(n, precision, trim, thousandSeparated);
57
+ }
58
+ const abs = Math.abs(num);
59
+ const targetPrecision = abs > 0 && abs < 0.01 ? precision : 2;
60
+ return formatNumber(n, targetPrecision, trim, thousandSeparated);
61
+ }
62
+ const USD_DECIMALS = 8;
63
+ function getUsdAmountFromTokenUnits(tokenAmount, tokenDecimals, exchangeRate) {
64
+ if (!exchangeRate && exchangeRate !== "0") {
65
+ return null;
66
+ }
67
+ if (tokenDecimals === void 0 || tokenDecimals === null) {
68
+ return null;
69
+ }
70
+ try {
71
+ const amountBN = tokenAmount instanceof _util.BN ? tokenAmount : new _util.BN(tokenAmount || "0");
72
+ const tokenScale = new _util.BN(10).pow(new _util.BN(tokenDecimals));
73
+ if (tokenScale.isZero()) {
74
+ return null;
75
+ }
76
+ const rateBN = new _util.BN(exchangeRate.replace(".", ""));
77
+ const rateDecimalPlaces = exchangeRate.includes(".") ? exchangeRate.split(".")[1]?.length || 0 : 0;
78
+ const rateScale = new _util.BN(10).pow(new _util.BN(rateDecimalPlaces));
79
+ const usdPrecisionScale = new _util.BN(10).pow(new _util.BN(USD_DECIMALS));
80
+ const usdUnit = amountBN.mul(rateBN).mul(usdPrecisionScale).div(tokenScale.mul(rateScale));
81
+ return (0, _util.fromUnitToToken)(usdUnit.toString(), USD_DECIMALS);
82
+ } catch {
83
+ return null;
84
+ }
85
+ }
86
+ function formatUsdAmount(amount, locale = "en") {
87
+ if (!amount && amount !== "0") {
88
+ return null;
89
+ }
90
+ const num = Number(amount);
91
+ if (!Number.isFinite(num)) {
92
+ return null;
93
+ }
94
+ return new Intl.NumberFormat(locale, {
95
+ minimumFractionDigits: 2,
96
+ maximumFractionDigits: 2
97
+ }).format(num);
98
+ }
99
+ function formatExchangeRate(amount) {
100
+ if (!amount && amount !== "0") {
101
+ return null;
102
+ }
103
+ const value = String(amount);
104
+ const num = Number(value);
105
+ if (!Number.isFinite(num)) {
106
+ return null;
107
+ }
108
+ return value;
109
+ }
110
+ function formatExchangeRateDisplay(rate, currency = "USD", decimals = 2) {
111
+ if (rate === null || rate === void 0) {
112
+ return null;
113
+ }
114
+ const num = Number(rate);
115
+ if (!Number.isFinite(num)) {
116
+ return null;
117
+ }
118
+ const formattedValue = num.toFixed(decimals);
119
+ if (currency === "USD") {
120
+ return `$${formattedValue}`;
121
+ }
122
+ return `${formattedValue} ${currency}`;
123
+ }
124
+ function formatAmount(amount, decimals, precision = 2) {
125
+ const tokenAmount = (0, _util.fromUnitToToken)(amount, decimals);
126
+ const numericValue = Number(tokenAmount);
127
+ if (!Number.isFinite(numericValue)) {
128
+ return formatBNStr(amount, decimals, precision, true, false);
129
+ }
130
+ const abs = Math.abs(numericValue);
131
+ const targetPrecision = abs > 0 && abs < 0.01 ? decimals : 2;
132
+ return formatNumber(tokenAmount, targetPrecision, true, false);
133
+ }
134
+ function getPriceCurrencyOptions(price) {
135
+ if (Array.isArray(price.currency_options)) {
136
+ return price.currency_options;
137
+ }
138
+ return [{
139
+ currency_id: price.currency_id,
140
+ unit_amount: price.unit_amount,
141
+ custom_unit_amount: price.custom_unit_amount || null,
142
+ tiers: null
143
+ }];
144
+ }
145
+ function getPriceUnitAmountByCurrency(price, currency) {
146
+ const options = getPriceCurrencyOptions(price);
147
+ const option = options.find(x => x.currency_id === currency?.id);
148
+ if (option) {
149
+ if (option.custom_unit_amount) {
150
+ return option.custom_unit_amount.preset || option.custom_unit_amount.presets[0];
151
+ }
152
+ return option.unit_amount;
153
+ }
154
+ if (price.currency_id === currency?.id) {
155
+ if (price.custom_unit_amount) {
156
+ return price.custom_unit_amount.preset || price.custom_unit_amount.presets[0];
157
+ }
158
+ return price.unit_amount;
159
+ }
160
+ return "0";
161
+ }
162
+ function getLineItemAmounts(item, currency, {
163
+ useUpsell = true,
164
+ exchangeRate = null
165
+ } = {}) {
166
+ if (!currency) {
167
+ return {
168
+ unitAmount: new _util.BN(0),
169
+ totalAmount: new _util.BN(0),
170
+ isDynamicQuote: false
171
+ };
172
+ }
173
+ const price = useUpsell ? item.upsell_price || item.price : item.price;
174
+ const quantity = new _util.BN(item.quantity || 0);
175
+ const quoteAmount = item.quoted_amount;
176
+ const quoteCurrencyId = item.quote_currency_id;
177
+ const isDynamicPrice = price?.pricing_type === "dynamic";
178
+ const isQuoteValidForCurrency = isDynamicPrice && quoteAmount && quoteCurrencyId === currency.id;
179
+ if (isQuoteValidForCurrency) {
180
+ const totalAmount = new _util.BN(quoteAmount || "0");
181
+ const unitAmount2 = quantity.gt(new _util.BN(0)) ? totalAmount.add(quantity).sub(new _util.BN(1)).div(quantity) : new _util.BN(0);
182
+ return {
183
+ unitAmount: unitAmount2,
184
+ totalAmount,
185
+ isDynamicQuote: true
186
+ };
187
+ }
188
+ if (isDynamicPrice && exchangeRate && price?.base_amount) {
189
+ const rate = Number(exchangeRate);
190
+ if (rate > 0 && Number.isFinite(rate)) {
191
+ const baseAmountUsd = Number(price.base_amount);
192
+ if (baseAmountUsd > 0 && Number.isFinite(baseAmountUsd)) {
193
+ const tokenAmount = baseAmountUsd / rate;
194
+ const unitAmount2 = (0, _util.fromTokenToUnit)(tokenAmount.toFixed(currency.decimal || 8), currency.decimal || 8);
195
+ return {
196
+ unitAmount: unitAmount2,
197
+ totalAmount: unitAmount2.mul(quantity),
198
+ isDynamicQuote: false
199
+ };
200
+ }
201
+ }
202
+ }
203
+ if (!exchangeRate && price?.base_amount != null) {
204
+ const baseAmountUsd = Number(price.base_amount);
205
+ if (baseAmountUsd >= 0 && Number.isFinite(baseAmountUsd)) {
206
+ const dec = currency.decimal || 2;
207
+ const unitAmountBN = (0, _util.fromTokenToUnit)(baseAmountUsd.toFixed(dec), dec);
208
+ return {
209
+ unitAmount: unitAmountBN,
210
+ totalAmount: unitAmountBN.mul(quantity),
211
+ isDynamicQuote: false
212
+ };
213
+ }
214
+ }
215
+ const unitAmount = new _util.BN(getPriceUnitAmountByCurrency(price, currency));
216
+ return {
217
+ unitAmount,
218
+ totalAmount: unitAmount.mul(quantity),
219
+ isDynamicQuote: false
220
+ };
221
+ }
222
+ function getCheckoutAmount(items, currency, trialing = false, upsell = true, {
223
+ exchangeRate = null
224
+ } = {}) {
225
+ let renew = new _util.BN(0);
226
+ const total = items.filter(x => {
227
+ const price = upsell ? x.upsell_price || x.price : x.price;
228
+ return price != null;
229
+ }).reduce((acc, x) => {
230
+ const quoteCurrencyId = x.quote_currency_id;
231
+ let totalAmount;
232
+ if (x.custom_amount && quoteCurrencyId && quoteCurrencyId === currency.id) {
233
+ totalAmount = new _util.BN(x.custom_amount);
234
+ } else {
235
+ ({
236
+ totalAmount
237
+ } = getLineItemAmounts(x, currency, {
238
+ useUpsell: upsell,
239
+ exchangeRate
240
+ }));
241
+ }
242
+ const price = upsell ? x.upsell_price || x.price : x.price;
243
+ if (price?.type === "recurring") {
244
+ renew = renew.add(totalAmount);
245
+ if (trialing) {
246
+ return acc;
247
+ }
248
+ if (price.recurring?.usage_type === "metered") {
249
+ return acc;
250
+ }
251
+ }
252
+ return acc.add(totalAmount);
253
+ }, new _util.BN(0)).toString();
254
+ return {
255
+ subtotal: total,
256
+ total,
257
+ renew: formatDynamicPrice(renew.toString(), !!exchangeRate),
258
+ discount: "0",
259
+ shipping: "0",
260
+ tax: "0"
261
+ };
262
+ }
@@ -0,0 +1,15 @@
1
+ import type { CheckoutResult } from '../checkout/types';
2
+ /**
3
+ * Poll for checkout session completion.
4
+ * Extracted from react/src/payment/form/index.tsx:72-99
5
+ *
6
+ * Uses p-wait-for with 2s interval and 3 minute timeout.
7
+ * Completion condition: session.status === 'complete' && payment_status in ['paid', 'no_payment_required']
8
+ * Throws if paymentIntent has last_payment_error.
9
+ */
10
+ export declare function waitForCheckoutComplete(sessionId: string): Promise<CheckoutResult>;
11
+ /**
12
+ * Generate unique idempotency key for submit (Final Freeze Architecture).
13
+ * Format: ${sessionId}-${currencyId}-${timestamp}-${random}
14
+ */
15
+ export declare function generateIdempotencyKey(sessionId: string, currencyId: string): string;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.generateIdempotencyKey = generateIdempotencyKey;
7
+ exports.waitForCheckoutComplete = waitForCheckoutComplete;
8
+ var _pWaitFor = _interopRequireDefault(require("p-wait-for"));
9
+ var _api = _interopRequireWildcard(require("./api"));
10
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
11
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
12
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
13
+ async function waitForCheckoutComplete(sessionId) {
14
+ let result;
15
+ await (0, _pWaitFor.default)(async () => {
16
+ const {
17
+ data
18
+ } = await _api.default.get(_api.API.RETRIEVE_SESSION(sessionId));
19
+ if (data.paymentIntent && data.paymentIntent.status === "requires_action" && data.paymentIntent.last_payment_error) {
20
+ throw new Error(data.paymentIntent.last_payment_error.message);
21
+ }
22
+ result = data;
23
+ return data.checkoutSession?.status === "complete" && ["paid", "no_payment_required"].includes(data.checkoutSession?.payment_status);
24
+ }, {
25
+ interval: 2e3,
26
+ timeout: 3 * 60 * 1e3
27
+ });
28
+ return result;
29
+ }
30
+ function generateIdempotencyKey(sessionId, currencyId) {
31
+ return `${sessionId}-${currencyId}-${Date.now()}-${Math.random().toString(36).substring(2, 10)}`;
32
+ }
@@ -0,0 +1,10 @@
1
+ export interface ApiConfig {
2
+ baseUrl?: string;
3
+ authToken?: string;
4
+ locale?: string;
5
+ livemode?: boolean;
6
+ }
7
+ export interface LoadingState {
8
+ isLoading: boolean;
9
+ error: string | null;
10
+ }
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1,38 @@
1
+ import type { CheckoutFormData } from '../checkout/types';
2
+ export declare const postalCodePatterns: Record<string, RegExp>;
3
+ export declare function validatePostalCode(postalCode: string, country?: string): boolean;
4
+ export declare function getFieldValidation(fieldName: string, validations?: Record<string, {
5
+ pattern?: string;
6
+ pattern_message?: Record<string, string>;
7
+ }>, locale?: string): {
8
+ pattern?: {
9
+ value: RegExp;
10
+ message: string;
11
+ };
12
+ };
13
+ export declare function validatePhone(phone: string): Promise<boolean>;
14
+ export declare function validateEmail(email: string): boolean;
15
+ export interface ValidateFormOptions {
16
+ phoneEnabled: boolean;
17
+ addressMode: 'auto' | 'required' | null;
18
+ fieldValidation?: Record<string, {
19
+ pattern?: string;
20
+ pattern_message?: Record<string, string>;
21
+ }>;
22
+ locale?: string;
23
+ }
24
+ export interface FormErrors {
25
+ customer_name?: string;
26
+ customer_email?: string;
27
+ customer_phone?: string;
28
+ 'billing_address.country'?: string;
29
+ 'billing_address.state'?: string;
30
+ 'billing_address.line1'?: string;
31
+ 'billing_address.city'?: string;
32
+ 'billing_address.postal_code'?: string;
33
+ [key: string]: string | undefined;
34
+ }
35
+ export declare function validateForm(values: CheckoutFormData | null, options: ValidateFormOptions): Promise<{
36
+ valid: boolean;
37
+ errors: FormErrors;
38
+ }>;