@cedros/pay-react 1.0.4 → 1.1.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 (389) hide show
  1. package/README.md +297 -39
  2. package/dist/CedrosContext-DUT3cLZg.mjs +2474 -0
  3. package/dist/CedrosContext-efFL4kQz.js +11 -0
  4. package/dist/admin/index.d.ts +9 -0
  5. package/dist/admin/index.d.ts.map +1 -0
  6. package/dist/admin/plugin.d.ts +9 -0
  7. package/dist/admin/plugin.d.ts.map +1 -0
  8. package/dist/admin/types.d.ts +115 -0
  9. package/dist/admin/types.d.ts.map +1 -0
  10. package/dist/components/CedrosPay.d.ts.map +1 -1
  11. package/dist/components/CreditsButton.d.ts +42 -0
  12. package/dist/components/CreditsButton.d.ts.map +1 -0
  13. package/dist/components/CreditsSubscribeButton.d.ts +55 -0
  14. package/dist/components/CreditsSubscribeButton.d.ts.map +1 -0
  15. package/dist/components/CryptoButton.d.ts.map +1 -1
  16. package/dist/components/CryptoSubscribeButton.d.ts +50 -0
  17. package/dist/components/CryptoSubscribeButton.d.ts.map +1 -0
  18. package/dist/components/PaymentModal.d.ts +8 -2
  19. package/dist/components/PaymentModal.d.ts.map +1 -1
  20. package/dist/components/PurchaseButton.d.ts +14 -3
  21. package/dist/components/PurchaseButton.d.ts.map +1 -1
  22. package/dist/components/SubscribeButton.d.ts +55 -0
  23. package/dist/components/SubscribeButton.d.ts.map +1 -0
  24. package/dist/components/SubscriptionManagementPanel.d.ts +67 -0
  25. package/dist/components/SubscriptionManagementPanel.d.ts.map +1 -0
  26. package/dist/components/admin/AISettingsSection.d.ts +3 -0
  27. package/dist/components/admin/AISettingsSection.d.ts.map +1 -0
  28. package/dist/components/admin/AdminAuthManager.d.ts +95 -0
  29. package/dist/components/admin/AdminAuthManager.d.ts.map +1 -0
  30. package/dist/components/admin/CedrosPayAdminDashboard.d.ts +40 -0
  31. package/dist/components/admin/CedrosPayAdminDashboard.d.ts.map +1 -0
  32. package/dist/components/admin/ConfigEditor.d.ts +13 -0
  33. package/dist/components/admin/ConfigEditor.d.ts.map +1 -0
  34. package/dist/components/admin/CouponsSection.d.ts +3 -0
  35. package/dist/components/admin/CouponsSection.d.ts.map +1 -0
  36. package/dist/components/admin/Dropdown.d.ts +29 -0
  37. package/dist/components/admin/Dropdown.d.ts.map +1 -0
  38. package/dist/components/admin/FAQSection.d.ts +3 -0
  39. package/dist/components/admin/FAQSection.d.ts.map +1 -0
  40. package/dist/components/admin/MessagingSection.d.ts +10 -0
  41. package/dist/components/admin/MessagingSection.d.ts.map +1 -0
  42. package/dist/components/admin/OverviewSection.d.ts +3 -0
  43. package/dist/components/admin/OverviewSection.d.ts.map +1 -0
  44. package/dist/components/admin/PaymentSettingsSection.d.ts +3 -0
  45. package/dist/components/admin/PaymentSettingsSection.d.ts.map +1 -0
  46. package/dist/components/admin/ProductVariationsEditor.d.ts +14 -0
  47. package/dist/components/admin/ProductVariationsEditor.d.ts.map +1 -0
  48. package/dist/components/admin/ProductsSection.d.ts +3 -0
  49. package/dist/components/admin/ProductsSection.d.ts.map +1 -0
  50. package/dist/components/admin/RefundsSection.d.ts +3 -0
  51. package/dist/components/admin/RefundsSection.d.ts.map +1 -0
  52. package/dist/components/admin/SettingsSection.d.ts +10 -0
  53. package/dist/components/admin/SettingsSection.d.ts.map +1 -0
  54. package/dist/components/admin/SingleCategorySettings.d.ts +21 -0
  55. package/dist/components/admin/SingleCategorySettings.d.ts.map +1 -0
  56. package/dist/components/admin/StatsBar.d.ts +19 -0
  57. package/dist/components/admin/StatsBar.d.ts.map +1 -0
  58. package/dist/components/admin/StorefrontSection.d.ts +3 -0
  59. package/dist/components/admin/StorefrontSection.d.ts.map +1 -0
  60. package/dist/components/admin/SubscriptionsSection.d.ts +3 -0
  61. package/dist/components/admin/SubscriptionsSection.d.ts.map +1 -0
  62. package/dist/components/admin/TransactionsSection.d.ts +3 -0
  63. package/dist/components/admin/TransactionsSection.d.ts.map +1 -0
  64. package/dist/components/admin/VariantInventoryGrid.d.ts +19 -0
  65. package/dist/components/admin/VariantInventoryGrid.d.ts.map +1 -0
  66. package/dist/components/admin/VariationTypeEditor.d.ts +15 -0
  67. package/dist/components/admin/VariationTypeEditor.d.ts.map +1 -0
  68. package/dist/components/admin/configApi.d.ts +104 -0
  69. package/dist/components/admin/configApi.d.ts.map +1 -0
  70. package/dist/components/admin/icons.d.ts +50 -0
  71. package/dist/components/admin/icons.d.ts.map +1 -0
  72. package/dist/components/admin/index.d.ts +16 -0
  73. package/dist/components/admin/index.d.ts.map +1 -0
  74. package/dist/components/admin/sections-more.d.ts +12 -0
  75. package/dist/components/admin/sections-more.d.ts.map +1 -0
  76. package/dist/components/admin/sections.d.ts +12 -0
  77. package/dist/components/admin/sections.d.ts.map +1 -0
  78. package/dist/components/admin/types.d.ts +324 -0
  79. package/dist/components/admin/types.d.ts.map +1 -0
  80. package/dist/components/admin/useAdminAuth.d.ts +50 -0
  81. package/dist/components/admin/useAdminAuth.d.ts.map +1 -0
  82. package/dist/components/admin/useAutosave.d.ts +56 -0
  83. package/dist/components/admin/useAutosave.d.ts.map +1 -0
  84. package/dist/components/admin/useProductVariations.d.ts +56 -0
  85. package/dist/components/admin/useProductVariations.d.ts.map +1 -0
  86. package/dist/components/subscriptionPanelStyles.d.ts +12 -0
  87. package/dist/components/subscriptionPanelStyles.d.ts.map +1 -0
  88. package/dist/context/CedrosContext.d.ts +6 -0
  89. package/dist/context/CedrosContext.d.ts.map +1 -1
  90. package/dist/context/ThemeContext.d.ts +6 -0
  91. package/dist/context/ThemeContext.d.ts.map +1 -1
  92. package/dist/crypto-only.d.ts +1 -1
  93. package/dist/crypto-only.d.ts.map +1 -1
  94. package/dist/crypto-only.js +1 -1
  95. package/dist/crypto-only.mjs +16 -17
  96. package/dist/ecommerce/__tests__/cartCheckoutRequirements.test.d.ts +2 -0
  97. package/dist/ecommerce/__tests__/cartCheckoutRequirements.test.d.ts.map +1 -0
  98. package/dist/ecommerce/__tests__/cartProviderPersistence.test.d.ts +2 -0
  99. package/dist/ecommerce/__tests__/cartProviderPersistence.test.d.ts.map +1 -0
  100. package/dist/ecommerce/__tests__/cartReducer.test.d.ts +2 -0
  101. package/dist/ecommerce/__tests__/cartReducer.test.d.ts.map +1 -0
  102. package/dist/ecommerce/__tests__/cartServerMerge.test.d.ts +2 -0
  103. package/dist/ecommerce/__tests__/cartServerMerge.test.d.ts.map +1 -0
  104. package/dist/ecommerce/__tests__/checkoutPaymentMethods.test.d.ts +2 -0
  105. package/dist/ecommerce/__tests__/checkoutPaymentMethods.test.d.ts.map +1 -0
  106. package/dist/ecommerce/__tests__/checkoutReturn.test.d.ts +2 -0
  107. package/dist/ecommerce/__tests__/checkoutReturn.test.d.ts.map +1 -0
  108. package/dist/ecommerce/__tests__/checkoutSchema.test.d.ts +2 -0
  109. package/dist/ecommerce/__tests__/checkoutSchema.test.d.ts.map +1 -0
  110. package/dist/ecommerce/__tests__/mockAdapter.test.d.ts +2 -0
  111. package/dist/ecommerce/__tests__/mockAdapter.test.d.ts.map +1 -0
  112. package/dist/ecommerce/adapters/CommerceAdapter.d.ts +235 -0
  113. package/dist/ecommerce/adapters/CommerceAdapter.d.ts.map +1 -0
  114. package/dist/ecommerce/adapters/mock/mockAdapter.d.ts +3 -0
  115. package/dist/ecommerce/adapters/mock/mockAdapter.d.ts.map +1 -0
  116. package/dist/ecommerce/adapters/paywall/paywallAdapter.d.ts +6 -0
  117. package/dist/ecommerce/adapters/paywall/paywallAdapter.d.ts.map +1 -0
  118. package/dist/ecommerce/components/cart/CartLineItem.d.ts +12 -0
  119. package/dist/ecommerce/components/cart/CartLineItem.d.ts.map +1 -0
  120. package/dist/ecommerce/components/cart/CartPageContent.d.ts +6 -0
  121. package/dist/ecommerce/components/cart/CartPageContent.d.ts.map +1 -0
  122. package/dist/ecommerce/components/cart/CartPanel.d.ts +5 -0
  123. package/dist/ecommerce/components/cart/CartPanel.d.ts.map +1 -0
  124. package/dist/ecommerce/components/cart/CartSidebar.d.ts +11 -0
  125. package/dist/ecommerce/components/cart/CartSidebar.d.ts.map +1 -0
  126. package/dist/ecommerce/components/cart/CartSummary.d.ts +13 -0
  127. package/dist/ecommerce/components/cart/CartSummary.d.ts.map +1 -0
  128. package/dist/ecommerce/components/cart/PromoCodeInput.d.ts +6 -0
  129. package/dist/ecommerce/components/cart/PromoCodeInput.d.ts.map +1 -0
  130. package/dist/ecommerce/components/catalog/Breadcrumbs.d.ts +9 -0
  131. package/dist/ecommerce/components/catalog/Breadcrumbs.d.ts.map +1 -0
  132. package/dist/ecommerce/components/catalog/CategoryNav.d.ts +8 -0
  133. package/dist/ecommerce/components/catalog/CategoryNav.d.ts.map +1 -0
  134. package/dist/ecommerce/components/catalog/FilterPanel.d.ts +29 -0
  135. package/dist/ecommerce/components/catalog/FilterPanel.d.ts.map +1 -0
  136. package/dist/ecommerce/components/catalog/Price.d.ts +9 -0
  137. package/dist/ecommerce/components/catalog/Price.d.ts.map +1 -0
  138. package/dist/ecommerce/components/catalog/ProductCard.d.ts +14 -0
  139. package/dist/ecommerce/components/catalog/ProductCard.d.ts.map +1 -0
  140. package/dist/ecommerce/components/catalog/ProductGallery.d.ts +6 -0
  141. package/dist/ecommerce/components/catalog/ProductGallery.d.ts.map +1 -0
  142. package/dist/ecommerce/components/catalog/ProductGrid.d.ts +20 -0
  143. package/dist/ecommerce/components/catalog/ProductGrid.d.ts.map +1 -0
  144. package/dist/ecommerce/components/catalog/QuantitySelector.d.ts +8 -0
  145. package/dist/ecommerce/components/catalog/QuantitySelector.d.ts.map +1 -0
  146. package/dist/ecommerce/components/catalog/QuickViewDialog.d.ts +10 -0
  147. package/dist/ecommerce/components/catalog/QuickViewDialog.d.ts.map +1 -0
  148. package/dist/ecommerce/components/catalog/SearchInput.d.ts +7 -0
  149. package/dist/ecommerce/components/catalog/SearchInput.d.ts.map +1 -0
  150. package/dist/ecommerce/components/catalog/VariantSelector.d.ts +19 -0
  151. package/dist/ecommerce/components/catalog/VariantSelector.d.ts.map +1 -0
  152. package/dist/ecommerce/components/chat/ShopChatPanel.d.ts +4 -0
  153. package/dist/ecommerce/components/chat/ShopChatPanel.d.ts.map +1 -0
  154. package/dist/ecommerce/components/checkout/AddressForm.d.ts +9 -0
  155. package/dist/ecommerce/components/checkout/AddressForm.d.ts.map +1 -0
  156. package/dist/ecommerce/components/checkout/CheckoutCancelPage.d.ts +24 -0
  157. package/dist/ecommerce/components/checkout/CheckoutCancelPage.d.ts.map +1 -0
  158. package/dist/ecommerce/components/checkout/CheckoutForm.d.ts +4 -0
  159. package/dist/ecommerce/components/checkout/CheckoutForm.d.ts.map +1 -0
  160. package/dist/ecommerce/components/checkout/CheckoutLayout.d.ts +6 -0
  161. package/dist/ecommerce/components/checkout/CheckoutLayout.d.ts.map +1 -0
  162. package/dist/ecommerce/components/checkout/CheckoutReceipt.d.ts +8 -0
  163. package/dist/ecommerce/components/checkout/CheckoutReceipt.d.ts.map +1 -0
  164. package/dist/ecommerce/components/checkout/CheckoutSuccessPage.d.ts +29 -0
  165. package/dist/ecommerce/components/checkout/CheckoutSuccessPage.d.ts.map +1 -0
  166. package/dist/ecommerce/components/checkout/InventoryVerificationDialog.d.ts +19 -0
  167. package/dist/ecommerce/components/checkout/InventoryVerificationDialog.d.ts.map +1 -0
  168. package/dist/ecommerce/components/checkout/OrderReview.d.ts +4 -0
  169. package/dist/ecommerce/components/checkout/OrderReview.d.ts.map +1 -0
  170. package/dist/ecommerce/components/checkout/PaymentStep.d.ts +15 -0
  171. package/dist/ecommerce/components/checkout/PaymentStep.d.ts.map +1 -0
  172. package/dist/ecommerce/components/checkout/ShippingMethodSelector.d.ts +9 -0
  173. package/dist/ecommerce/components/checkout/ShippingMethodSelector.d.ts.map +1 -0
  174. package/dist/ecommerce/components/faq/FAQItem.d.ts +29 -0
  175. package/dist/ecommerce/components/faq/FAQItem.d.ts.map +1 -0
  176. package/dist/ecommerce/components/faq/FAQItem.test.d.ts +7 -0
  177. package/dist/ecommerce/components/faq/FAQItem.test.d.ts.map +1 -0
  178. package/dist/ecommerce/components/faq/FAQList.d.ts +15 -0
  179. package/dist/ecommerce/components/faq/FAQList.d.ts.map +1 -0
  180. package/dist/ecommerce/components/faq/index.d.ts +3 -0
  181. package/dist/ecommerce/components/faq/index.d.ts.map +1 -0
  182. package/dist/ecommerce/components/general/EmptyState.d.ts +8 -0
  183. package/dist/ecommerce/components/general/EmptyState.d.ts.map +1 -0
  184. package/dist/ecommerce/components/general/ErrorBoundary.d.ts +16 -0
  185. package/dist/ecommerce/components/general/ErrorBoundary.d.ts.map +1 -0
  186. package/dist/ecommerce/components/general/ErrorState.d.ts +7 -0
  187. package/dist/ecommerce/components/general/ErrorState.d.ts.map +1 -0
  188. package/dist/ecommerce/components/general/toast.d.ts +19 -0
  189. package/dist/ecommerce/components/general/toast.d.ts.map +1 -0
  190. package/dist/ecommerce/components/orders/OrderCard.d.ts +7 -0
  191. package/dist/ecommerce/components/orders/OrderCard.d.ts.map +1 -0
  192. package/dist/ecommerce/components/orders/OrderDetails.d.ts +7 -0
  193. package/dist/ecommerce/components/orders/OrderDetails.d.ts.map +1 -0
  194. package/dist/ecommerce/components/orders/OrderList.d.ts +7 -0
  195. package/dist/ecommerce/components/orders/OrderList.d.ts.map +1 -0
  196. package/dist/ecommerce/components/ui/accordion.d.ts +7 -0
  197. package/dist/ecommerce/components/ui/accordion.d.ts.map +1 -0
  198. package/dist/ecommerce/components/ui/badge.d.ts +10 -0
  199. package/dist/ecommerce/components/ui/badge.d.ts.map +1 -0
  200. package/dist/ecommerce/components/ui/button.d.ts +12 -0
  201. package/dist/ecommerce/components/ui/button.d.ts.map +1 -0
  202. package/dist/ecommerce/components/ui/card.d.ts +8 -0
  203. package/dist/ecommerce/components/ui/card.d.ts.map +1 -0
  204. package/dist/ecommerce/components/ui/dialog.d.ts +13 -0
  205. package/dist/ecommerce/components/ui/dialog.d.ts.map +1 -0
  206. package/dist/ecommerce/components/ui/input.d.ts +5 -0
  207. package/dist/ecommerce/components/ui/input.d.ts.map +1 -0
  208. package/dist/ecommerce/components/ui/label.d.ts +3 -0
  209. package/dist/ecommerce/components/ui/label.d.ts.map +1 -0
  210. package/dist/ecommerce/components/ui/select.d.ts +9 -0
  211. package/dist/ecommerce/components/ui/select.d.ts.map +1 -0
  212. package/dist/ecommerce/components/ui/separator.d.ts +4 -0
  213. package/dist/ecommerce/components/ui/separator.d.ts.map +1 -0
  214. package/dist/ecommerce/components/ui/sheet.d.ts +21 -0
  215. package/dist/ecommerce/components/ui/sheet.d.ts.map +1 -0
  216. package/dist/ecommerce/components/ui/skeleton.d.ts +3 -0
  217. package/dist/ecommerce/components/ui/skeleton.d.ts.map +1 -0
  218. package/dist/ecommerce/components/ui/tabs.d.ts +7 -0
  219. package/dist/ecommerce/components/ui/tabs.d.ts.map +1 -0
  220. package/dist/ecommerce/components/ui/textarea.d.ts +5 -0
  221. package/dist/ecommerce/components/ui/textarea.d.ts.map +1 -0
  222. package/dist/ecommerce/config/context.d.ts +13 -0
  223. package/dist/ecommerce/config/context.d.ts.map +1 -0
  224. package/dist/ecommerce/config/types.d.ts +48 -0
  225. package/dist/ecommerce/config/types.d.ts.map +1 -0
  226. package/dist/ecommerce/hooks/checkoutReturn.d.ts +3 -0
  227. package/dist/ecommerce/hooks/checkoutReturn.d.ts.map +1 -0
  228. package/dist/ecommerce/hooks/useAIRelatedProducts.d.ts +33 -0
  229. package/dist/ecommerce/hooks/useAIRelatedProducts.d.ts.map +1 -0
  230. package/dist/ecommerce/hooks/useCartInventory.d.ts +42 -0
  231. package/dist/ecommerce/hooks/useCartInventory.d.ts.map +1 -0
  232. package/dist/ecommerce/hooks/useCatalogUrlState.d.ts +15 -0
  233. package/dist/ecommerce/hooks/useCatalogUrlState.d.ts.map +1 -0
  234. package/dist/ecommerce/hooks/useCategories.d.ts +7 -0
  235. package/dist/ecommerce/hooks/useCategories.d.ts.map +1 -0
  236. package/dist/ecommerce/hooks/useCheckoutResultFromUrl.d.ts +4 -0
  237. package/dist/ecommerce/hooks/useCheckoutResultFromUrl.d.ts.map +1 -0
  238. package/dist/ecommerce/hooks/useHoldExpiry.d.ts +34 -0
  239. package/dist/ecommerce/hooks/useHoldExpiry.d.ts.map +1 -0
  240. package/dist/ecommerce/hooks/useInventoryVerification.d.ts +41 -0
  241. package/dist/ecommerce/hooks/useInventoryVerification.d.ts.map +1 -0
  242. package/dist/ecommerce/hooks/useOrders.d.ts +7 -0
  243. package/dist/ecommerce/hooks/useOrders.d.ts.map +1 -0
  244. package/dist/ecommerce/hooks/usePaymentMethodsConfig.d.ts +6 -0
  245. package/dist/ecommerce/hooks/usePaymentMethodsConfig.d.ts.map +1 -0
  246. package/dist/ecommerce/hooks/useProduct.d.ts +7 -0
  247. package/dist/ecommerce/hooks/useProduct.d.ts.map +1 -0
  248. package/dist/ecommerce/hooks/useProducts.d.ts +8 -0
  249. package/dist/ecommerce/hooks/useProducts.d.ts.map +1 -0
  250. package/dist/ecommerce/hooks/useShippingMethods.d.ts +10 -0
  251. package/dist/ecommerce/hooks/useShippingMethods.d.ts.map +1 -0
  252. package/dist/ecommerce/hooks/useStorefrontSettings.d.ts +32 -0
  253. package/dist/ecommerce/hooks/useStorefrontSettings.d.ts.map +1 -0
  254. package/dist/ecommerce/hooks/useSubscriptionData.d.ts +8 -0
  255. package/dist/ecommerce/hooks/useSubscriptionData.d.ts.map +1 -0
  256. package/dist/ecommerce/index.d.ts +98 -0
  257. package/dist/ecommerce/index.d.ts.map +1 -0
  258. package/dist/ecommerce/integrations/cedros-pay/useCedrosPayCheckoutAdapter.d.ts +10 -0
  259. package/dist/ecommerce/integrations/cedros-pay/useCedrosPayCheckoutAdapter.d.ts.map +1 -0
  260. package/dist/ecommerce/state/cart/CartProvider.d.ts +27 -0
  261. package/dist/ecommerce/state/cart/CartProvider.d.ts.map +1 -0
  262. package/dist/ecommerce/state/cart/cartReducer.d.ts +35 -0
  263. package/dist/ecommerce/state/cart/cartReducer.d.ts.map +1 -0
  264. package/dist/ecommerce/state/checkout/checkoutSchema.d.ts +21 -0
  265. package/dist/ecommerce/state/checkout/checkoutSchema.d.ts.map +1 -0
  266. package/dist/ecommerce/state/checkout/useCheckout.d.ts +34 -0
  267. package/dist/ecommerce/state/checkout/useCheckout.d.ts.map +1 -0
  268. package/dist/ecommerce/templates/CartTemplate.d.ts +5 -0
  269. package/dist/ecommerce/templates/CartTemplate.d.ts.map +1 -0
  270. package/dist/ecommerce/templates/CategoryTemplate.d.ts +11 -0
  271. package/dist/ecommerce/templates/CategoryTemplate.d.ts.map +1 -0
  272. package/dist/ecommerce/templates/CheckoutTemplate.d.ts +9 -0
  273. package/dist/ecommerce/templates/CheckoutTemplate.d.ts.map +1 -0
  274. package/dist/ecommerce/templates/ProductTemplate.d.ts +11 -0
  275. package/dist/ecommerce/templates/ProductTemplate.d.ts.map +1 -0
  276. package/dist/ecommerce/templates/PurchaseHistoryTemplate.d.ts +6 -0
  277. package/dist/ecommerce/templates/PurchaseHistoryTemplate.d.ts.map +1 -0
  278. package/dist/ecommerce/templates/ReceiptTemplate.d.ts +19 -0
  279. package/dist/ecommerce/templates/ReceiptTemplate.d.ts.map +1 -0
  280. package/dist/ecommerce/templates/ShopTemplate.d.ts +15 -0
  281. package/dist/ecommerce/templates/ShopTemplate.d.ts.map +1 -0
  282. package/dist/ecommerce/templates/SubscriptionTemplate.d.ts +15 -0
  283. package/dist/ecommerce/templates/SubscriptionTemplate.d.ts.map +1 -0
  284. package/dist/ecommerce/testing/adapterContract.d.ts +11 -0
  285. package/dist/ecommerce/testing/adapterContract.d.ts.map +1 -0
  286. package/dist/ecommerce/types.d.ts +164 -0
  287. package/dist/ecommerce/types.d.ts.map +1 -0
  288. package/dist/ecommerce/utils/cartCheckoutRequirements.d.ts +18 -0
  289. package/dist/ecommerce/utils/cartCheckoutRequirements.d.ts.map +1 -0
  290. package/dist/ecommerce/utils/cartItemMetadata.d.ts +3 -0
  291. package/dist/ecommerce/utils/cartItemMetadata.d.ts.map +1 -0
  292. package/dist/ecommerce/utils/cn.d.ts +3 -0
  293. package/dist/ecommerce/utils/cn.d.ts.map +1 -0
  294. package/dist/ecommerce/utils/money.d.ts +6 -0
  295. package/dist/ecommerce/utils/money.d.ts.map +1 -0
  296. package/dist/ecommerce/utils/storage.d.ts +5 -0
  297. package/dist/ecommerce/utils/storage.d.ts.map +1 -0
  298. package/dist/en-BXheDBal.mjs +19 -0
  299. package/dist/en-Yikrt96u.js +1 -0
  300. package/dist/hooks/useCreditsPayment.d.ts +64 -0
  301. package/dist/hooks/useCreditsPayment.d.ts.map +1 -0
  302. package/dist/hooks/useCreditsSubscription.d.ts +42 -0
  303. package/dist/hooks/useCreditsSubscription.d.ts.map +1 -0
  304. package/dist/hooks/useCryptoSubscription.d.ts +42 -0
  305. package/dist/hooks/useCryptoSubscription.d.ts.map +1 -0
  306. package/dist/hooks/usePaymentMode.d.ts.map +1 -1
  307. package/dist/hooks/useStripeCheckout.d.ts +1 -0
  308. package/dist/hooks/useStripeCheckout.d.ts.map +1 -1
  309. package/dist/hooks/useSubscription.d.ts +42 -0
  310. package/dist/hooks/useSubscription.d.ts.map +1 -0
  311. package/dist/hooks/useSubscriptionManagement.d.ts +92 -0
  312. package/dist/hooks/useSubscriptionManagement.d.ts.map +1 -0
  313. package/dist/hooks/useX402Payment.d.ts +1 -0
  314. package/dist/hooks/useX402Payment.d.ts.map +1 -1
  315. package/dist/i18n/index.d.ts +7 -0
  316. package/dist/i18n/index.d.ts.map +1 -1
  317. package/dist/index-D2d_ukkR.mjs +26838 -0
  318. package/dist/index-DGkSHjb1.js +136 -0
  319. package/dist/index.d.ts +20 -2
  320. package/dist/index.d.ts.map +1 -1
  321. package/dist/index.js +1 -1
  322. package/dist/index.mjs +79 -625
  323. package/dist/magic-string.es-B81Zo59j.js +10 -0
  324. package/dist/magic-string.es-uPKorP4O.mjs +663 -0
  325. package/dist/managers/CreditsManager.d.ts +151 -0
  326. package/dist/managers/CreditsManager.d.ts.map +1 -0
  327. package/dist/managers/ManagerCache.d.ts +6 -0
  328. package/dist/managers/ManagerCache.d.ts.map +1 -1
  329. package/dist/managers/RouteDiscoveryManager.d.ts.map +1 -1
  330. package/dist/managers/StripeManager.d.ts.map +1 -1
  331. package/dist/managers/SubscriptionChangeManager.d.ts +42 -0
  332. package/dist/managers/SubscriptionChangeManager.d.ts.map +1 -0
  333. package/dist/managers/SubscriptionManager.d.ts +113 -0
  334. package/dist/managers/SubscriptionManager.d.ts.map +1 -0
  335. package/dist/managers/X402Manager.d.ts.map +1 -1
  336. package/dist/pay-react.css +1 -1
  337. package/dist/sections-6IcZ6JeN.js +1 -0
  338. package/dist/sections-a0Dz-MMz.mjs +10 -0
  339. package/dist/stripe-only.d.ts +1 -1
  340. package/dist/stripe-only.d.ts.map +1 -1
  341. package/dist/stripe-only.js +1 -1
  342. package/dist/stripe-only.mjs +12 -13
  343. package/dist/styles-C4-_hbgr.js +1 -0
  344. package/dist/styles-QcAsIVWl.mjs +1909 -0
  345. package/dist/telemetry.js +1 -1
  346. package/dist/telemetry.mjs +1 -1
  347. package/dist/testing/index.js +147 -1
  348. package/dist/testing/index.mjs +10555 -103
  349. package/dist/types/componentOptions.d.ts +14 -4
  350. package/dist/types/componentOptions.d.ts.map +1 -1
  351. package/dist/types/errors.d.ts +26 -4
  352. package/dist/types/errors.d.ts.map +1 -1
  353. package/dist/types/index.d.ts +116 -0
  354. package/dist/types/index.d.ts.map +1 -1
  355. package/dist/types/subscription.d.ts +300 -0
  356. package/dist/types/subscription.d.ts.map +1 -0
  357. package/dist/utils/cartHelpers.d.ts +3 -0
  358. package/dist/utils/cartHelpers.d.ts.map +1 -1
  359. package/dist/utils/cspHelper.d.ts +7 -1
  360. package/dist/utils/cspHelper.d.ts.map +1 -1
  361. package/dist/utils/csvHelpers.d.ts +62 -0
  362. package/dist/utils/csvHelpers.d.ts.map +1 -0
  363. package/dist/utils/csvHelpers.test.d.ts +2 -0
  364. package/dist/utils/csvHelpers.test.d.ts.map +1 -0
  365. package/dist/utils/dateHelpers.d.ts +24 -0
  366. package/dist/utils/dateHelpers.d.ts.map +1 -0
  367. package/dist/utils/eventEmitter.d.ts +1 -1
  368. package/dist/utils/eventEmitter.d.ts.map +1 -1
  369. package/dist/utils/fetchWithTimeout.d.ts +3 -3
  370. package/dist/utils/index.d.ts +2 -1
  371. package/dist/utils/index.d.ts.map +1 -1
  372. package/dist/utils/tokenMintValidator.d.ts +10 -6
  373. package/dist/utils/tokenMintValidator.d.ts.map +1 -1
  374. package/dist/utils/uuid.d.ts.map +1 -1
  375. package/dist/uuid-C5B8o31X.js +1 -0
  376. package/dist/uuid-_z3jSatJ.mjs +17 -0
  377. package/package.json +25 -9
  378. package/dist/CedrosContext-B3iCqN6e.js +0 -11
  379. package/dist/CedrosContext-vX9uqZKp.mjs +0 -1796
  380. package/dist/en-CSsJl3nf.mjs +0 -19
  381. package/dist/en-D-uY3ltT.js +0 -1
  382. package/dist/styles-61pRysGe.js +0 -1
  383. package/dist/styles-DI2LPVdQ.mjs +0 -1625
  384. package/dist/utils/uuid-shim.d.ts +0 -9
  385. package/dist/utils/uuid-shim.d.ts.map +0 -1
  386. package/dist/uuid-C0iMjdcc.js +0 -1
  387. package/dist/uuid-UlzrVY8Y.mjs +0 -17
  388. package/dist/walletDetection-JZR3UCOa.mjs +0 -27
  389. package/dist/walletDetection-bNmV5ItZ.js +0 -1
@@ -0,0 +1,2474 @@
1
+ import { jsx as X } from "react/jsx-runtime";
2
+ import { createContext as ye, useContext as re, useState as Z, useRef as we, useEffect as L, useMemo as $ } from "react";
3
+ import { g as T } from "./uuid-_z3jSatJ.mjs";
4
+ import { clusterApiUrl as je, Connection as ze, Transaction as oe, PublicKey as N, LAMPORTS_PER_SOL as qe } from "@solana/web3.js";
5
+ import { getAssociatedTokenAddress as Qe, createTransferInstruction as We } from "@solana/spl-token";
6
+ import { PhantomWalletAdapter as He, SolflareWalletAdapter as Ve } from "@solana/wallet-adapter-wallets";
7
+ var me = "https://js.stripe.com/v3", Ge = /^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/;
8
+ var Ke = function() {
9
+ for (var e = document.querySelectorAll('script[src^="'.concat(me, '"]')), t = 0; t < e.length; t++) {
10
+ var n = e[t];
11
+ if (Ge.test(n.src))
12
+ return n;
13
+ }
14
+ return null;
15
+ }, se = function(e) {
16
+ var t = "", n = document.createElement("script");
17
+ n.src = "".concat(me).concat(t);
18
+ var a = document.head || document.body;
19
+ if (!a)
20
+ throw new Error("Expected document.body not to be null. Stripe.js requires a <body> element.");
21
+ return a.appendChild(n), n;
22
+ }, Je = function(e, t) {
23
+ !e || !e._registerWrapper || e._registerWrapper({
24
+ name: "stripe-js",
25
+ version: "4.6.0",
26
+ startTime: t
27
+ });
28
+ }, I = null, Q = null, W = null, Ye = function(e) {
29
+ return function() {
30
+ e(new Error("Failed to load Stripe.js"));
31
+ };
32
+ }, Xe = function(e, t) {
33
+ return function() {
34
+ window.Stripe ? e(window.Stripe) : t(new Error("Stripe.js not available"));
35
+ };
36
+ }, Ze = function(e) {
37
+ return I !== null ? I : (I = new Promise(function(t, n) {
38
+ if (typeof window > "u" || typeof document > "u") {
39
+ t(null);
40
+ return;
41
+ }
42
+ if (window.Stripe) {
43
+ t(window.Stripe);
44
+ return;
45
+ }
46
+ try {
47
+ var a = Ke();
48
+ if (!(a && e)) {
49
+ if (!a)
50
+ a = se(e);
51
+ else if (a && W !== null && Q !== null) {
52
+ var i;
53
+ a.removeEventListener("load", W), a.removeEventListener("error", Q), (i = a.parentNode) === null || i === void 0 || i.removeChild(a), a = se(e);
54
+ }
55
+ }
56
+ W = Xe(t, n), Q = Ye(n), a.addEventListener("load", W), a.addEventListener("error", Q);
57
+ } catch (o) {
58
+ n(o);
59
+ return;
60
+ }
61
+ }), I.catch(function(t) {
62
+ return I = null, Promise.reject(t);
63
+ }));
64
+ }, $e = function(e, t, n) {
65
+ if (e === null)
66
+ return null;
67
+ var a = e.apply(void 0, t);
68
+ return Je(a, n), a;
69
+ }, F, ge = !1, be = function() {
70
+ return F || (F = Ze(null).catch(function(e) {
71
+ return F = null, Promise.reject(e);
72
+ }), F);
73
+ };
74
+ Promise.resolve().then(function() {
75
+ return be();
76
+ }).catch(function(r) {
77
+ ge || console.warn(r);
78
+ });
79
+ var ve = function() {
80
+ for (var e = arguments.length, t = new Array(e), n = 0; n < e; n++)
81
+ t[n] = arguments[n];
82
+ ge = !0;
83
+ var a = Date.now();
84
+ return be().then(function(i) {
85
+ return $e(i, t, a);
86
+ });
87
+ }, _e = /* @__PURE__ */ ((r) => (r[r.DEBUG = 0] = "DEBUG", r[r.INFO = 1] = "INFO", r[r.WARN = 2] = "WARN", r[r.ERROR = 3] = "ERROR", r[r.SILENT = 4] = "SILENT", r))(_e || {});
88
+ class Ee {
89
+ config;
90
+ constructor(e) {
91
+ this.config = e;
92
+ }
93
+ /**
94
+ * Update the log level dynamically
95
+ */
96
+ setLevel(e) {
97
+ this.config.level = e;
98
+ }
99
+ /**
100
+ * Get the current log level
101
+ */
102
+ getLevel() {
103
+ return this.config.level;
104
+ }
105
+ /**
106
+ * Debug-level logging (most verbose)
107
+ * Use for detailed debugging information
108
+ */
109
+ debug(...e) {
110
+ this.config.level <= 0 && this.log("DEBUG", console.log, e);
111
+ }
112
+ /**
113
+ * Info-level logging
114
+ * Use for general informational messages
115
+ */
116
+ info(...e) {
117
+ this.config.level <= 1 && this.log("INFO", console.info, e);
118
+ }
119
+ /**
120
+ * Warning-level logging
121
+ * Use for potentially problematic situations
122
+ */
123
+ warn(...e) {
124
+ this.config.level <= 2 && this.log("WARN", console.warn, e);
125
+ }
126
+ /**
127
+ * Error-level logging
128
+ * Use for error conditions
129
+ */
130
+ error(...e) {
131
+ this.config.level <= 3 && this.log("ERROR", console.error, e);
132
+ }
133
+ /**
134
+ * Internal log method with formatting
135
+ */
136
+ log(e, t, n) {
137
+ const a = this.config.prefix ? `${this.config.prefix} ` : "", i = (/* @__PURE__ */ new Date()).toISOString();
138
+ t(`[${i}] ${a}[${e}]`, ...n);
139
+ }
140
+ }
141
+ const et = () => typeof process < "u" && process.env.NODE_ENV === "development" ? 0 : 2;
142
+ let V = null;
143
+ function c() {
144
+ return V || (V = new Ee({
145
+ level: et(),
146
+ prefix: "[CedrosPay]"
147
+ })), V;
148
+ }
149
+ function tt(r) {
150
+ V = r;
151
+ }
152
+ function rt(r) {
153
+ return new Ee(r);
154
+ }
155
+ function k(r, e) {
156
+ return r instanceof Error ? r.message : typeof r == "string" ? r : e;
157
+ }
158
+ const nt = {
159
+ service_unavailable: "Service temporarily unavailable. Please try again later or contact support.",
160
+ server_insufficient_funds: "Service temporarily unavailable. Please try again later or contact support.",
161
+ insufficient_funds_token: "Insufficient token balance in your wallet. Please add more tokens and try again.",
162
+ insufficient_funds_sol: "Insufficient SOL for transaction fees. Please add some SOL to your wallet and try again.",
163
+ insufficient_amount: "Payment amount is insufficient. Please check the required amount.",
164
+ invalid_signature: "Transaction signature is invalid. Please try again.",
165
+ send_failed: "Failed to send transaction. Please try again or contact support.",
166
+ timeout: "Transaction timed out. Please check the blockchain explorer or try again."
167
+ };
168
+ async function v(r, e, t = !1) {
169
+ try {
170
+ const n = await r.json();
171
+ if (t && n.verificationError) {
172
+ c().debug(`Payment verification failed: ${n.verificationError.code}`);
173
+ const a = n.verificationError.code;
174
+ return nt[a] || n.verificationError.message || e;
175
+ }
176
+ return typeof n.error == "string" ? n.error : n.error && typeof n.error == "object" && "message" in n.error ? n.error.message : e;
177
+ } catch {
178
+ return await r.text() || e;
179
+ }
180
+ }
181
+ const at = 15e3;
182
+ async function y(r, e = {}, t = at) {
183
+ const n = new AbortController(), a = e.signal;
184
+ if (a?.aborted)
185
+ throw n.abort(), new DOMException("The operation was aborted", "AbortError");
186
+ const i = setTimeout(() => n.abort(), t);
187
+ let o = null;
188
+ a && (o = () => n.abort(), a.addEventListener("abort", o));
189
+ try {
190
+ return await fetch(r, {
191
+ ...e,
192
+ signal: n.signal
193
+ });
194
+ } catch (s) {
195
+ throw s instanceof Error && s.name === "AbortError" ? a?.aborted ? s : new Error(`Request timeout after ${t}ms`) : s;
196
+ } finally {
197
+ clearTimeout(i), a && o && a.removeEventListener("abort", o);
198
+ }
199
+ }
200
+ function R(r) {
201
+ const { maxRequests: e, windowMs: t } = r;
202
+ let n = e, a = Date.now();
203
+ const i = e / t;
204
+ function o() {
205
+ const f = Date.now(), h = f - a;
206
+ if (h > 0) {
207
+ const A = h * i;
208
+ n = Math.min(e, n + A), a = f;
209
+ }
210
+ }
211
+ function s() {
212
+ return o(), n >= 1 ? (n -= 1, !0) : !1;
213
+ }
214
+ function u() {
215
+ return o(), Math.floor(n);
216
+ }
217
+ function l() {
218
+ if (o(), n >= 1)
219
+ return 0;
220
+ const h = (1 - n) / i;
221
+ return Math.ceil(h);
222
+ }
223
+ function d() {
224
+ n = e, a = Date.now();
225
+ }
226
+ return {
227
+ tryConsume: s,
228
+ getAvailableTokens: u,
229
+ getTimeUntilRefill: l,
230
+ reset: d
231
+ };
232
+ }
233
+ const M = {
234
+ /** 10 requests per minute - recommended for payment requests */
235
+ PAYMENT: { maxRequests: 10, windowMs: 6e4 },
236
+ /** 30 requests per minute - for quote fetching */
237
+ QUOTE: { maxRequests: 30, windowMs: 6e4 },
238
+ /** 5 requests per minute - strict limit for sensitive operations */
239
+ STRICT: { maxRequests: 5, windowMs: 6e4 },
240
+ /** 100 requests per minute - permissive for UI interactions */
241
+ PERMISSIVE: { maxRequests: 100, windowMs: 6e4 }
242
+ };
243
+ var it = /* @__PURE__ */ ((r) => (r.CLOSED = "CLOSED", r.OPEN = "OPEN", r.HALF_OPEN = "HALF_OPEN", r))(it || {});
244
+ class m extends Error {
245
+ constructor(e) {
246
+ super(e), this.name = "CircuitBreakerOpenError";
247
+ }
248
+ }
249
+ function U(r) {
250
+ const { failureThreshold: e, timeout: t, name: n = "circuit-breaker" } = r;
251
+ let a = "CLOSED", i = 0, o = 0, s = 0, u = null, l = null, d = null;
252
+ function f() {
253
+ a === "OPEN" && d !== null && Date.now() >= d && (c().debug(`[CircuitBreaker:${n}] Transitioning OPEN → HALF_OPEN (timeout expired)`), a = "HALF_OPEN", d = null);
254
+ }
255
+ function h() {
256
+ l = Date.now(), o++, a === "HALF_OPEN" ? (c().debug(`[CircuitBreaker:${n}] Success in HALF_OPEN → CLOSED`), a = "CLOSED", i = 0) : a === "CLOSED" && (i = 0);
257
+ }
258
+ function A(S) {
259
+ u = Date.now(), i++, c().warn(`[CircuitBreaker:${n}] Failure recorded (${i}/${e}):`, S.message), a === "HALF_OPEN" ? (c().warn(`[CircuitBreaker:${n}] Failed in HALF_OPEN → OPEN`), a = "OPEN", d = Date.now() + t) : a === "CLOSED" && i >= e && (c().error(`[CircuitBreaker:${n}] Failure threshold reached (${i}) → OPEN`), a = "OPEN", d = Date.now() + t);
260
+ }
261
+ async function p(S) {
262
+ if (f(), a === "OPEN") {
263
+ s++;
264
+ const E = d ? Math.ceil((d - Date.now()) / 1e3) : 0;
265
+ throw new m(
266
+ `Circuit breaker is OPEN. Service is unavailable. Retry in ${E}s.`
267
+ );
268
+ }
269
+ try {
270
+ const E = await S();
271
+ return h(), E;
272
+ } catch (E) {
273
+ throw A(E instanceof Error ? E : new Error(String(E))), E;
274
+ }
275
+ }
276
+ function w() {
277
+ return f(), a;
278
+ }
279
+ function P() {
280
+ return f(), {
281
+ state: a,
282
+ failures: i,
283
+ successes: o,
284
+ rejections: s,
285
+ lastFailureTime: u,
286
+ lastSuccessTime: l
287
+ };
288
+ }
289
+ function D() {
290
+ c().debug(`[CircuitBreaker:${n}] Manual reset → CLOSED`), a = "CLOSED", i = 0, o = 0, s = 0, u = null, l = null, d = null;
291
+ }
292
+ function x() {
293
+ c().warn(`[CircuitBreaker:${n}] Manual trip → OPEN`), a = "OPEN", d = Date.now() + t;
294
+ }
295
+ return {
296
+ execute: p,
297
+ getState: w,
298
+ getStats: P,
299
+ reset: D,
300
+ trip: x
301
+ };
302
+ }
303
+ const rr = {
304
+ /** Strict: Opens quickly (3 failures), long timeout (60s) */
305
+ STRICT: { failureThreshold: 3, timeout: 6e4 },
306
+ /** Standard: Balanced settings (5 failures, 30s timeout) */
307
+ STANDARD: { failureThreshold: 5, timeout: 3e4 },
308
+ /** Lenient: Tolerates more failures (10 failures, 15s timeout) */
309
+ LENIENT: { failureThreshold: 10, timeout: 15e3 }
310
+ };
311
+ function ot(r, e) {
312
+ if (e >= 3)
313
+ return !1;
314
+ const t = r.message.toLowerCase();
315
+ return t.includes("network") || t.includes("timeout") || t.includes("fetch failed") || t.includes("econnrefused") || t.includes("503") || t.includes("502") || t.includes("500") || t.includes("429") ? !0 : (t.includes("400") || t.includes("401") || t.includes("403") || t.includes("404"), !1);
316
+ }
317
+ function st(r, e, t, n, a) {
318
+ const i = e * Math.pow(t, r), o = Math.min(i, n);
319
+ if (a) {
320
+ const s = Math.random() * o;
321
+ return Math.floor(s);
322
+ }
323
+ return Math.floor(o);
324
+ }
325
+ function ct(r) {
326
+ return new Promise((e) => setTimeout(e, r));
327
+ }
328
+ async function g(r, e = {}) {
329
+ const {
330
+ maxRetries: t = 3,
331
+ initialDelayMs: n = 1e3,
332
+ backoffFactor: a = 2,
333
+ maxDelayMs: i = 3e4,
334
+ jitter: o = !0,
335
+ shouldRetry: s = ot,
336
+ name: u = "retry"
337
+ } = e;
338
+ let l = null, d = 0;
339
+ for (let f = 0; f <= t; f++)
340
+ try {
341
+ const h = await r();
342
+ return f > 0 && c().debug(
343
+ `[Retry:${u}] Succeeded on attempt ${f + 1}/${t + 1} after ${d}ms`
344
+ ), h;
345
+ } catch (h) {
346
+ l = h instanceof Error ? h : new Error(String(h));
347
+ const A = f === t, p = s(l, f);
348
+ if (A || !p)
349
+ throw c().warn(
350
+ `[Retry:${u}] Failed on attempt ${f + 1}/${t + 1}. ${A ? "No more retries." : "Error not retryable."}`
351
+ ), l;
352
+ const w = st(f, n, a, i, o);
353
+ d += w, c().warn(
354
+ `[Retry:${u}] Attempt ${f + 1}/${t + 1} failed: ${l.message}. Retrying in ${w}ms...`
355
+ ), await ct(w);
356
+ }
357
+ throw l || new Error("Retry failed with no error");
358
+ }
359
+ const b = {
360
+ /** Quick retries for transient errors (3 retries, 1s initial, 2x backoff) */
361
+ QUICK: {
362
+ maxRetries: 3,
363
+ initialDelayMs: 1e3,
364
+ backoffFactor: 2,
365
+ maxDelayMs: 1e4
366
+ },
367
+ /** Standard retries (3 retries, 2s initial, 2x backoff) */
368
+ STANDARD: {
369
+ maxRetries: 3,
370
+ initialDelayMs: 2e3,
371
+ backoffFactor: 2,
372
+ maxDelayMs: 3e4
373
+ },
374
+ /** Aggressive retries for critical operations (5 retries, 500ms initial) */
375
+ AGGRESSIVE: {
376
+ maxRetries: 5,
377
+ initialDelayMs: 500,
378
+ backoffFactor: 1.5,
379
+ maxDelayMs: 15e3
380
+ },
381
+ /** Patient retries for slow backends (5 retries, 5s initial) */
382
+ PATIENT: {
383
+ maxRetries: 5,
384
+ initialDelayMs: 5e3,
385
+ backoffFactor: 2,
386
+ maxDelayMs: 6e4
387
+ }
388
+ };
389
+ class lt {
390
+ stripe = null;
391
+ publicKey;
392
+ routeDiscovery;
393
+ rateLimiter = R(M.PAYMENT);
394
+ circuitBreaker = U({
395
+ failureThreshold: 5,
396
+ timeout: 1e4,
397
+ // 10 seconds for faster recovery in payment flows
398
+ name: "stripe-manager"
399
+ });
400
+ constructor(e, t) {
401
+ this.publicKey = e, this.routeDiscovery = t;
402
+ }
403
+ /**
404
+ * Initialize Stripe.js library
405
+ */
406
+ async initialize() {
407
+ if (!this.stripe && (this.stripe = await ve(this.publicKey), !this.stripe))
408
+ throw new Error("Failed to initialize Stripe");
409
+ }
410
+ /**
411
+ * Create a Stripe checkout session
412
+ */
413
+ async createSession(e) {
414
+ if (!this.rateLimiter.tryConsume())
415
+ throw new Error("Rate limit exceeded for Stripe session creation. Please try again later.");
416
+ try {
417
+ return await this.circuitBreaker.execute(async () => await g(
418
+ async () => {
419
+ const t = await this.routeDiscovery.buildUrl("/paywall/v1/stripe-session");
420
+ c().debug("[StripeManager] Creating session with request:", e), e.couponCode ? c().debug("[StripeManager] Coupon code included:", e.couponCode) : c().debug("[StripeManager] No coupon code in request");
421
+ const n = await y(t, {
422
+ method: "POST",
423
+ headers: {
424
+ "Content-Type": "application/json",
425
+ "Idempotency-Key": T()
426
+ },
427
+ body: JSON.stringify(e)
428
+ });
429
+ if (!n.ok) {
430
+ const a = await v(n, "Failed to create Stripe session");
431
+ throw new Error(a);
432
+ }
433
+ return await n.json();
434
+ },
435
+ { ...b.STANDARD, name: "stripe-create-session" }
436
+ ));
437
+ } catch (t) {
438
+ throw t instanceof m ? (c().error("[StripeManager] Circuit breaker is OPEN - Stripe service unavailable"), new Error("Stripe payment service is temporarily unavailable. Please try again in a few moments.")) : t;
439
+ }
440
+ }
441
+ /**
442
+ * Redirect to Stripe checkout
443
+ */
444
+ async redirectToCheckout(e) {
445
+ if (this.stripe || await this.initialize(), !this.stripe)
446
+ return {
447
+ success: !1,
448
+ error: "Stripe not initialized"
449
+ };
450
+ const t = await this.stripe.redirectToCheckout({ sessionId: e });
451
+ return t.error ? {
452
+ success: !1,
453
+ error: t.error.message
454
+ } : { success: !0 };
455
+ }
456
+ /**
457
+ * Handle complete payment flow: create session and redirect
458
+ */
459
+ async processPayment(e) {
460
+ try {
461
+ const t = await this.createSession(e);
462
+ return await this.redirectToCheckout(t.sessionId);
463
+ } catch (t) {
464
+ return {
465
+ success: !1,
466
+ error: k(t, "Unknown error")
467
+ };
468
+ }
469
+ }
470
+ /**
471
+ * Create a Stripe cart checkout session for multiple items
472
+ */
473
+ async processCartCheckout(e) {
474
+ const { items: t, successUrl: n, cancelUrl: a, metadata: i, customerEmail: o, couponCode: s } = e;
475
+ if (!this.rateLimiter.tryConsume())
476
+ return {
477
+ success: !1,
478
+ error: "Rate limit exceeded for cart checkout. Please try again later."
479
+ };
480
+ try {
481
+ const u = await this.circuitBreaker.execute(async () => await g(
482
+ async () => {
483
+ const l = await this.routeDiscovery.buildUrl("/paywall/v1/cart/checkout"), d = {
484
+ items: t,
485
+ successUrl: n,
486
+ cancelUrl: a,
487
+ metadata: i,
488
+ customerEmail: o,
489
+ coupon: s,
490
+ // New Rust server field
491
+ couponCode: s
492
+ // Legacy Go server field (backwards compat)
493
+ }, f = await y(l, {
494
+ method: "POST",
495
+ headers: {
496
+ "Content-Type": "application/json",
497
+ "Idempotency-Key": T()
498
+ },
499
+ body: JSON.stringify(d)
500
+ });
501
+ if (!f.ok) {
502
+ const h = await v(f, "Failed to create cart checkout session");
503
+ throw new Error(h);
504
+ }
505
+ return await f.json();
506
+ },
507
+ { ...b.STANDARD, name: "stripe-cart-checkout" }
508
+ ));
509
+ return await this.redirectToCheckout(u.sessionId);
510
+ } catch (u) {
511
+ return u instanceof m ? {
512
+ success: !1,
513
+ error: "Stripe payment service is temporarily unavailable. Please try again in a few moments."
514
+ } : {
515
+ success: !1,
516
+ error: k(u, "Cart checkout failed")
517
+ };
518
+ }
519
+ }
520
+ }
521
+ const Ce = "3.7.8", ut = Ce, O = typeof Buffer == "function", ce = typeof TextDecoder == "function" ? new TextDecoder() : void 0, le = typeof TextEncoder == "function" ? new TextEncoder() : void 0, dt = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", j = Array.prototype.slice.call(dt), H = ((r) => {
522
+ let e = {};
523
+ return r.forEach((t, n) => e[t] = n), e;
524
+ })(j), ft = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/, C = String.fromCharCode.bind(String), ue = typeof Uint8Array.from == "function" ? Uint8Array.from.bind(Uint8Array) : (r) => new Uint8Array(Array.prototype.slice.call(r, 0)), Se = (r) => r.replace(/=/g, "").replace(/[+\/]/g, (e) => e == "+" ? "-" : "_"), Pe = (r) => r.replace(/[^A-Za-z0-9\+\/]/g, ""), xe = (r) => {
525
+ let e, t, n, a, i = "";
526
+ const o = r.length % 3;
527
+ for (let s = 0; s < r.length; ) {
528
+ if ((t = r.charCodeAt(s++)) > 255 || (n = r.charCodeAt(s++)) > 255 || (a = r.charCodeAt(s++)) > 255)
529
+ throw new TypeError("invalid character found");
530
+ e = t << 16 | n << 8 | a, i += j[e >> 18 & 63] + j[e >> 12 & 63] + j[e >> 6 & 63] + j[e & 63];
531
+ }
532
+ return o ? i.slice(0, o - 3) + "===".substring(o) : i;
533
+ }, ne = typeof btoa == "function" ? (r) => btoa(r) : O ? (r) => Buffer.from(r, "binary").toString("base64") : xe, _ = O ? (r) => Buffer.from(r).toString("base64") : (r) => {
534
+ let t = [];
535
+ for (let n = 0, a = r.length; n < a; n += 4096)
536
+ t.push(C.apply(null, r.subarray(n, n + 4096)));
537
+ return ne(t.join(""));
538
+ }, G = (r, e = !1) => e ? Se(_(r)) : _(r), ht = (r) => {
539
+ if (r.length < 2) {
540
+ var e = r.charCodeAt(0);
541
+ return e < 128 ? r : e < 2048 ? C(192 | e >>> 6) + C(128 | e & 63) : C(224 | e >>> 12 & 15) + C(128 | e >>> 6 & 63) + C(128 | e & 63);
542
+ } else {
543
+ var e = 65536 + (r.charCodeAt(0) - 55296) * 1024 + (r.charCodeAt(1) - 56320);
544
+ return C(240 | e >>> 18 & 7) + C(128 | e >>> 12 & 63) + C(128 | e >>> 6 & 63) + C(128 | e & 63);
545
+ }
546
+ }, At = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g, Te = (r) => r.replace(At, ht), de = O ? (r) => Buffer.from(r, "utf8").toString("base64") : le ? (r) => _(le.encode(r)) : (r) => ne(Te(r)), B = (r, e = !1) => e ? Se(de(r)) : de(r), fe = (r) => B(r, !0), pt = /[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g, yt = (r) => {
547
+ switch (r.length) {
548
+ case 4:
549
+ var e = (7 & r.charCodeAt(0)) << 18 | (63 & r.charCodeAt(1)) << 12 | (63 & r.charCodeAt(2)) << 6 | 63 & r.charCodeAt(3), t = e - 65536;
550
+ return C((t >>> 10) + 55296) + C((t & 1023) + 56320);
551
+ case 3:
552
+ return C((15 & r.charCodeAt(0)) << 12 | (63 & r.charCodeAt(1)) << 6 | 63 & r.charCodeAt(2));
553
+ default:
554
+ return C((31 & r.charCodeAt(0)) << 6 | 63 & r.charCodeAt(1));
555
+ }
556
+ }, ke = (r) => r.replace(pt, yt), Re = (r) => {
557
+ if (r = r.replace(/\s+/g, ""), !ft.test(r))
558
+ throw new TypeError("malformed base64.");
559
+ r += "==".slice(2 - (r.length & 3));
560
+ let e, t, n, a = [];
561
+ for (let i = 0; i < r.length; )
562
+ e = H[r.charAt(i++)] << 18 | H[r.charAt(i++)] << 12 | (t = H[r.charAt(i++)]) << 6 | (n = H[r.charAt(i++)]), t === 64 ? a.push(C(e >> 16 & 255)) : n === 64 ? a.push(C(e >> 16 & 255, e >> 8 & 255)) : a.push(C(e >> 16 & 255, e >> 8 & 255, e & 255));
563
+ return a.join("");
564
+ }, ae = typeof atob == "function" ? (r) => atob(Pe(r)) : O ? (r) => Buffer.from(r, "base64").toString("binary") : Re, Me = O ? (r) => ue(Buffer.from(r, "base64")) : (r) => ue(ae(r).split("").map((e) => e.charCodeAt(0))), De = (r) => Me(Be(r)), wt = O ? (r) => Buffer.from(r, "base64").toString("utf8") : ce ? (r) => ce.decode(Me(r)) : (r) => ke(ae(r)), Be = (r) => Pe(r.replace(/[-_]/g, (e) => e == "-" ? "+" : "/")), ee = (r) => wt(Be(r)), mt = (r) => {
565
+ if (typeof r != "string")
566
+ return !1;
567
+ const e = r.replace(/\s+/g, "").replace(/={0,2}$/, "");
568
+ return !/[^\s0-9a-zA-Z\+/]/.test(e) || !/[^\s0-9a-zA-Z\-_]/.test(e);
569
+ }, Ue = (r) => ({
570
+ value: r,
571
+ enumerable: !1,
572
+ writable: !0,
573
+ configurable: !0
574
+ }), Oe = function() {
575
+ const r = (e, t) => Object.defineProperty(String.prototype, e, Ue(t));
576
+ r("fromBase64", function() {
577
+ return ee(this);
578
+ }), r("toBase64", function(e) {
579
+ return B(this, e);
580
+ }), r("toBase64URI", function() {
581
+ return B(this, !0);
582
+ }), r("toBase64URL", function() {
583
+ return B(this, !0);
584
+ }), r("toUint8Array", function() {
585
+ return De(this);
586
+ });
587
+ }, Ne = function() {
588
+ const r = (e, t) => Object.defineProperty(Uint8Array.prototype, e, Ue(t));
589
+ r("toBase64", function(e) {
590
+ return G(this, e);
591
+ }), r("toBase64URI", function() {
592
+ return G(this, !0);
593
+ }), r("toBase64URL", function() {
594
+ return G(this, !0);
595
+ });
596
+ }, gt = () => {
597
+ Oe(), Ne();
598
+ }, z = {
599
+ version: Ce,
600
+ VERSION: ut,
601
+ atob: ae,
602
+ atobPolyfill: Re,
603
+ btoa: ne,
604
+ btoaPolyfill: xe,
605
+ fromBase64: ee,
606
+ toBase64: B,
607
+ encode: B,
608
+ encodeURI: fe,
609
+ encodeURL: fe,
610
+ utob: Te,
611
+ btou: ke,
612
+ decode: ee,
613
+ isValid: mt,
614
+ fromUint8Array: G,
615
+ toUint8Array: De,
616
+ extendString: Oe,
617
+ extendUint8Array: Ne,
618
+ extendBuiltins: gt
619
+ };
620
+ class bt {
621
+ routeDiscovery;
622
+ quoteRateLimiter = R(M.QUOTE);
623
+ verifyRateLimiter = R(M.PAYMENT);
624
+ circuitBreaker = U({
625
+ failureThreshold: 5,
626
+ timeout: 1e4,
627
+ // 10 seconds for faster recovery in payment flows
628
+ name: "x402-manager"
629
+ });
630
+ constructor(e) {
631
+ this.routeDiscovery = e;
632
+ }
633
+ /**
634
+ * Request a protected resource and get x402 requirement
635
+ * SECURITY: Resource ID and coupon codes sent in request body to prevent leakage
636
+ * Prevents exposure of product IDs, SKUs, and business-sensitive identifiers in logs
637
+ */
638
+ async requestQuote(e) {
639
+ const { resource: t, couponCode: n } = e;
640
+ if (!this.quoteRateLimiter.tryConsume())
641
+ throw new Error("Rate limit exceeded for quote requests. Please try again later.");
642
+ try {
643
+ return await this.circuitBreaker.execute(async () => await g(
644
+ async () => {
645
+ const a = "/paywall/v1/quote";
646
+ c().debug(
647
+ "[X402Manager] Requesting quote",
648
+ n ? "with coupon" : "without coupon"
649
+ );
650
+ const i = await this.routeDiscovery.buildUrl(a), o = await y(i, {
651
+ method: "POST",
652
+ headers: {
653
+ "Content-Type": "application/json"
654
+ },
655
+ body: JSON.stringify({
656
+ resource: t,
657
+ couponCode: n || null
658
+ })
659
+ });
660
+ if (o.status !== 402)
661
+ throw new Error(`Expected 402 status, got ${o.status}`);
662
+ const s = await o.json();
663
+ if (s.crypto)
664
+ return s.crypto;
665
+ if (s.accepts && s.accepts.length > 0)
666
+ return s.accepts[0];
667
+ throw new Error("Invalid x402 response: missing crypto or accepts field");
668
+ },
669
+ { ...b.QUICK, name: "x402-quote" }
670
+ ));
671
+ } catch (a) {
672
+ throw a instanceof m ? (c().error("[X402Manager] Circuit breaker is OPEN - x402 service unavailable"), new Error("Payment service is temporarily unavailable. Please try again in a few moments.")) : a;
673
+ }
674
+ }
675
+ /**
676
+ * Request a cart quote for multiple items
677
+ */
678
+ async requestCartQuote(e) {
679
+ const { items: t, metadata: n, couponCode: a } = e;
680
+ if (!this.quoteRateLimiter.tryConsume())
681
+ throw new Error("Rate limit exceeded for cart quote requests. Please try again later.");
682
+ try {
683
+ return await this.circuitBreaker.execute(async () => await g(
684
+ async () => {
685
+ const i = await this.routeDiscovery.buildUrl("/paywall/v1/cart/quote"), o = {
686
+ items: t,
687
+ metadata: n,
688
+ coupon: a,
689
+ // New Rust server field
690
+ couponCode: a
691
+ // Legacy Go server field (backwards compat)
692
+ }, s = await y(i, {
693
+ method: "POST",
694
+ headers: {
695
+ "Content-Type": "application/json",
696
+ "Idempotency-Key": T()
697
+ },
698
+ body: JSON.stringify(o)
699
+ });
700
+ if (s.status !== 402 && !s.ok) {
701
+ const u = await v(s, "Failed to get cart quote");
702
+ throw new Error(u);
703
+ }
704
+ return await s.json();
705
+ },
706
+ { ...b.QUICK, name: "x402-cart-quote" }
707
+ ));
708
+ } catch (i) {
709
+ throw i instanceof m ? (c().error("[X402Manager] Circuit breaker is OPEN - cart quote service unavailable"), new Error("Payment service is temporarily unavailable. Please try again in a few moments.")) : i;
710
+ }
711
+ }
712
+ /**
713
+ * Build X-PAYMENT header from payment payload (base64 encoded)
714
+ */
715
+ buildPaymentHeader(e) {
716
+ const t = JSON.stringify(e);
717
+ return z.encode(t);
718
+ }
719
+ /**
720
+ * Parse X-PAYMENT-RESPONSE header (base64 encoded settlement response)
721
+ */
722
+ parseSettlementResponse(e) {
723
+ const t = e.headers.get("X-PAYMENT-RESPONSE");
724
+ if (!t)
725
+ return null;
726
+ try {
727
+ const n = z.decode(t), a = JSON.parse(n);
728
+ return typeof a.success != "boolean" ? (c().error("Invalid settlement response: missing success field"), null) : a;
729
+ } catch (n) {
730
+ return c().error("Failed to parse settlement response:", n), null;
731
+ }
732
+ }
733
+ /**
734
+ * Retry request with payment proof
735
+ * SECURITY: Coupon and metadata sent in X-PAYMENT header payload, NOT query strings
736
+ */
737
+ async submitPayment(e) {
738
+ const {
739
+ resource: t,
740
+ payload: n,
741
+ couponCode: a,
742
+ metadata: i,
743
+ resourceType: o = "regular"
744
+ } = e;
745
+ if (!this.verifyRateLimiter.tryConsume())
746
+ return {
747
+ success: !1,
748
+ error: "Rate limit exceeded for payment verification. Please try again later."
749
+ };
750
+ try {
751
+ return await this.circuitBreaker.execute(async () => await g(
752
+ async () => {
753
+ const u = {
754
+ ...n,
755
+ payload: {
756
+ ...n.payload,
757
+ resource: t,
758
+ resourceType: o,
759
+ metadata: {
760
+ ...n.payload.metadata || {},
761
+ // Preserve existing metadata
762
+ ...i || {},
763
+ // Layer in new metadata
764
+ ...a ? { couponCode: a } : {}
765
+ // Add coupon if present
766
+ }
767
+ }
768
+ }, l = this.buildPaymentHeader(u), d = "/paywall/v1/verify";
769
+ c().debug("[X402Manager] Submitting payment", {
770
+ resourceType: o,
771
+ hasCoupon: !!a,
772
+ hasMetadata: !!i
773
+ });
774
+ const f = await this.routeDiscovery.buildUrl(d), h = await y(f, {
775
+ method: "POST",
776
+ headers: {
777
+ "Content-Type": "application/json",
778
+ "X-PAYMENT": l,
779
+ "Idempotency-Key": T()
780
+ }
781
+ });
782
+ if (h.ok) {
783
+ const { settlement: p, transactionId: w } = await this.handlePaymentVerification(
784
+ h,
785
+ n.payload.signature
786
+ );
787
+ return {
788
+ success: !0,
789
+ transactionId: w,
790
+ settlement: p || void 0
791
+ };
792
+ }
793
+ return {
794
+ success: !1,
795
+ error: await v(h, "Payment verification failed", !0)
796
+ };
797
+ },
798
+ { ...b.STANDARD, name: "x402-verify" }
799
+ ));
800
+ } catch (s) {
801
+ return s instanceof m ? {
802
+ success: !1,
803
+ error: "Payment verification service is temporarily unavailable. Please try again in a few moments."
804
+ } : {
805
+ success: !1,
806
+ error: k(s, "Unknown error")
807
+ };
808
+ }
809
+ }
810
+ /**
811
+ * Build a complete gasless transaction on the backend
812
+ * Returns an unsigned transaction with all instructions (compute budget, transfer, memo)
813
+ */
814
+ async buildGaslessTransaction(e) {
815
+ const { resourceId: t, userWallet: n, feePayer: a, couponCode: i } = e;
816
+ if (!this.quoteRateLimiter.tryConsume())
817
+ throw new Error("Rate limit exceeded for gasless transaction requests. Please try again later.");
818
+ try {
819
+ return await this.circuitBreaker.execute(async () => await g(
820
+ async () => {
821
+ const o = await this.routeDiscovery.buildUrl(
822
+ "/paywall/v1/gasless-transaction"
823
+ ), s = await y(o, {
824
+ method: "POST",
825
+ headers: {
826
+ "Content-Type": "application/json"
827
+ },
828
+ body: JSON.stringify({
829
+ resourceId: t,
830
+ userWallet: n,
831
+ feePayer: a,
832
+ couponCode: i
833
+ })
834
+ });
835
+ if (!s.ok) {
836
+ const u = await v(s, "Failed to build gasless transaction");
837
+ throw new Error(u);
838
+ }
839
+ return await s.json();
840
+ },
841
+ { ...b.QUICK, name: "x402-gasless-build" }
842
+ ));
843
+ } catch (o) {
844
+ throw o instanceof m ? (c().error("[X402Manager] Circuit breaker is OPEN - gasless transaction service unavailable"), new Error("Gasless transaction service is temporarily unavailable. Please try again in a few moments.")) : o;
845
+ }
846
+ }
847
+ /**
848
+ * Submit gasless partial transaction for co-signing
849
+ * Sends the partially-signed transaction in X-Payment header for backend co-signing
850
+ * SECURITY: Coupon and metadata sent in X-PAYMENT header payload, NOT query strings
851
+ */
852
+ async submitGaslessTransaction(e) {
853
+ const {
854
+ resource: t,
855
+ partialTx: n,
856
+ couponCode: a,
857
+ metadata: i,
858
+ resourceType: o = "regular",
859
+ requirement: s
860
+ } = e;
861
+ if (!this.verifyRateLimiter.tryConsume())
862
+ return {
863
+ success: !1,
864
+ error: "Rate limit exceeded for gasless transaction verification. Please try again later."
865
+ };
866
+ try {
867
+ return await this.circuitBreaker.execute(async () => await g(
868
+ async () => {
869
+ const l = {
870
+ x402Version: 0,
871
+ scheme: s?.scheme || "solana-spl-transfer",
872
+ network: s?.network || "mainnet-beta",
873
+ payload: {
874
+ signature: "",
875
+ // Placeholder - backend will finalize after co-signing
876
+ transaction: n,
877
+ feePayer: s?.extra?.feePayer || "",
878
+ resource: t,
879
+ resourceType: o,
880
+ metadata: {
881
+ ...i || {},
882
+ ...a ? { couponCode: a } : {}
883
+ }
884
+ }
885
+ }, d = this.buildPaymentHeader(l), h = await this.routeDiscovery.buildUrl("/paywall/v1/verify"), A = await y(h, {
886
+ method: "POST",
887
+ headers: {
888
+ "Content-Type": "application/json",
889
+ "X-PAYMENT": d,
890
+ "Idempotency-Key": T()
891
+ }
892
+ });
893
+ if (A.ok) {
894
+ const { settlement: w, transactionId: P } = await this.handlePaymentVerification(
895
+ A,
896
+ "gasless-tx"
897
+ );
898
+ return {
899
+ success: !0,
900
+ transactionId: P,
901
+ settlement: w || void 0
902
+ };
903
+ }
904
+ return {
905
+ success: !1,
906
+ error: await v(A, "Gasless transaction failed", !0)
907
+ };
908
+ },
909
+ { ...b.STANDARD, name: "x402-gasless-verify" }
910
+ ));
911
+ } catch (u) {
912
+ return u instanceof m ? {
913
+ success: !1,
914
+ error: "Gasless transaction verification service is temporarily unavailable. Please try again in a few moments."
915
+ } : {
916
+ success: !1,
917
+ error: k(u, "Unknown error")
918
+ };
919
+ }
920
+ }
921
+ /**
922
+ * Handle payment verification response (shared logic for both submitPayment and submitGaslessTransaction)
923
+ * Parses settlement header and extracts transaction ID from response body
924
+ * @param response - HTTP response from payment verification endpoint
925
+ * @param defaultTxId - Fallback transaction ID if JSON parsing fails
926
+ * @returns Settlement data and transaction ID
927
+ */
928
+ async handlePaymentVerification(e, t) {
929
+ const n = this.parseSettlementResponse(e), a = e.headers.get("Content-Type") || "";
930
+ let i = t;
931
+ if (a.includes("application/json"))
932
+ try {
933
+ i = (await e.json()).signature || t;
934
+ } catch (o) {
935
+ c().warn("Failed to parse JSON response body:", o);
936
+ }
937
+ return { settlement: n, transactionId: i };
938
+ }
939
+ /**
940
+ * Validate x402 requirement structure
941
+ */
942
+ validateRequirement(e) {
943
+ return !!(e.scheme && e.network && e.maxAmountRequired && e.resource && e.payTo && e.asset && e.maxTimeoutSeconds > 0);
944
+ }
945
+ }
946
+ function vt(r) {
947
+ if (r.length >= 255)
948
+ throw new TypeError("Alphabet too long");
949
+ const e = new Uint8Array(256);
950
+ for (let l = 0; l < e.length; l++)
951
+ e[l] = 255;
952
+ for (let l = 0; l < r.length; l++) {
953
+ const d = r.charAt(l), f = d.charCodeAt(0);
954
+ if (e[f] !== 255)
955
+ throw new TypeError(d + " is ambiguous");
956
+ e[f] = l;
957
+ }
958
+ const t = r.length, n = r.charAt(0), a = Math.log(t) / Math.log(256), i = Math.log(256) / Math.log(t);
959
+ function o(l) {
960
+ if (l instanceof Uint8Array || (ArrayBuffer.isView(l) ? l = new Uint8Array(l.buffer, l.byteOffset, l.byteLength) : Array.isArray(l) && (l = Uint8Array.from(l))), !(l instanceof Uint8Array))
961
+ throw new TypeError("Expected Uint8Array");
962
+ if (l.length === 0)
963
+ return "";
964
+ let d = 0, f = 0, h = 0;
965
+ const A = l.length;
966
+ for (; h !== A && l[h] === 0; )
967
+ h++, d++;
968
+ const p = (A - h) * i + 1 >>> 0, w = new Uint8Array(p);
969
+ for (; h !== A; ) {
970
+ let x = l[h], S = 0;
971
+ for (let E = p - 1; (x !== 0 || S < f) && E !== -1; E--, S++)
972
+ x += 256 * w[E] >>> 0, w[E] = x % t >>> 0, x = x / t >>> 0;
973
+ if (x !== 0)
974
+ throw new Error("Non-zero carry");
975
+ f = S, h++;
976
+ }
977
+ let P = p - f;
978
+ for (; P !== p && w[P] === 0; )
979
+ P++;
980
+ let D = n.repeat(d);
981
+ for (; P < p; ++P)
982
+ D += r.charAt(w[P]);
983
+ return D;
984
+ }
985
+ function s(l) {
986
+ if (typeof l != "string")
987
+ throw new TypeError("Expected String");
988
+ if (l.length === 0)
989
+ return new Uint8Array();
990
+ let d = 0, f = 0, h = 0;
991
+ for (; l[d] === n; )
992
+ f++, d++;
993
+ const A = (l.length - d) * a + 1 >>> 0, p = new Uint8Array(A);
994
+ for (; d < l.length; ) {
995
+ const x = l.charCodeAt(d);
996
+ if (x > 255)
997
+ return;
998
+ let S = e[x];
999
+ if (S === 255)
1000
+ return;
1001
+ let E = 0;
1002
+ for (let q = A - 1; (S !== 0 || E < h) && q !== -1; q--, E++)
1003
+ S += t * p[q] >>> 0, p[q] = S % 256 >>> 0, S = S / 256 >>> 0;
1004
+ if (S !== 0)
1005
+ throw new Error("Non-zero carry");
1006
+ h = E, d++;
1007
+ }
1008
+ let w = A - h;
1009
+ for (; w !== A && p[w] === 0; )
1010
+ w++;
1011
+ const P = new Uint8Array(f + (A - w));
1012
+ let D = f;
1013
+ for (; w !== A; )
1014
+ P[D++] = p[w++];
1015
+ return P;
1016
+ }
1017
+ function u(l) {
1018
+ const d = s(l);
1019
+ if (d)
1020
+ return d;
1021
+ throw new Error("Non-base" + t + " character");
1022
+ }
1023
+ return {
1024
+ encode: o,
1025
+ decodeUnsafe: s,
1026
+ decode: u
1027
+ };
1028
+ }
1029
+ var Et = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
1030
+ const he = vt(Et), Ct = "data:image/webp;base64,UklGRnIIAABXRUJQVlA4WAoAAAAYAAAAOwAAOwAAQUxQSK4BAAABkHPbtrE9+z73/RTbqWw7Lf+BbbNKbTudbZe2qy+VbVv3PmeHj05G6ohg4LaRounNMtN1voB42ABA5R7TNlx5+O7du9e3Tiwb0b4EgFyAOCQM1Z16+DWFUZC7m3uVB2zKQGBhe+77RGHonJffCL1zQuHDxQ1hrEmTatDjHIXOC2MgzpNf1tVJkWgsGhyihI7JIE74aUYp2ITFAoz9QO+ZAs7zanvkEilKbIkMJS5ANwoJmrCodYVOmBqh5zIEJjZc9xods4A4rrPGxGitrJSU71yNyH4Myl7JTEl+5zzYSH9nlkrxHBzxWUzLVEnhh+YI/gq3+UphpvA8m/s7/wg9M4bjFNg/0vplrxQ+rQEDg/xihmT23jxYJZ8UPq8OA5z77Wt405FDR4poSMjiAJhPRxUIu8D+UVonOhfNPEVHPM9juFacwo+1V6kJQ3Y9Sa8ljhPuUvRk4UdNWU9ST3b9n0W3iG5DumdS9y7o3kHVu6/75ii/dbpvrO7brvtPUf2X6f5DVf/dmpxBmauociRVbqbKCXW5qCoHVuXempxf1dZQtXFUbat/yKZTtSUBVlA4INwFAABwGgCdASo8ADwAPm0qj0WkIqEZ+zYAQAbEtgBOmZoZF+E8zGoP3X8VbcdLvma8t+jH0E+YB+ofSA8wH7VdQv0AP75/iOsG9ADy3/Y5/b/91fgI/Y7MOesb0e/q+TUR1vt7VO6mwG0imO70GM5/0P7BX6qelv7EP209lz9oDRea09ZR+SjhX7sBu/ZS7tG917rPgI3Q7XsB7luy2hAg/95C2Z1L362OH1oFziDY/K5gWoSytSAtiKvA/jW1MehBzdLzJfszPPBvGa15IYwIVRTjO2Hz5ZS9HjLMehwAAP64SgjD3qeg6NRe/Ok+iFhrG3pgglCfbam3yBaDUH36sUiQx0PB1ZZyOHq0ky+f97h6tJMvo0p9LkfXecWOFJ8J5G7yRPuL4tzGLT09QulTJw42xp2hd+lMgIa51XoHx/iftn8B2D3k92H5jOQr+uIXFHHK5FpcTG+qGEF+np0LiQa+vdW7/+ZzOLVRf7jR5X3ANPt93Ng92DW7NflVr6kMr88O/v2ZNb0vtgao2Am/R3CDKiNq89f86CT6r2L2g1oTui7H3E1yhSPQpEOz01I3fhfiMMv4weqKuoedxn/xLg5uzHa6Gte4C/dQYkG3ZFSy4CXQtRjftBrjX/Oj+HpSUPDsv0wPW+ml5NbBKDCj2f3SD8TVMf2ZfHrOkR602RVk2UmKC+H0Y9iK6k98vsgPINtz0II8X7Mj2nJkTC6IMLuQ8dNTUq9VXOnhXrdhNZoaH94ePo6baBl3hTGFAnD3/b+gR/vtbqV7wktuX6fpnjeTBe/Drp6z3neeANj/aX4CsU9w67nwYOjZhueCjxaDKUnNjLPjI1e0BoTbcOzOQ0wHJHZJ+Pt608StBu4HiJ8NjH46fnvXL3yiMoSvkAuwCE1AakA+eU1u3unyjl1/MnZQmbp8fzfsfrFesehLPcIkYdCiZ+52QbmINNTjEsvjuBuZRubBE+Laihppsxoo4efGIo0xkw0etu1+yzvkqp88w3pBq0mRl13gnnc+2zl6SmhwgmNFbz+F8qAqmdfJL8iaNSGEWlPlpczDDe62GBZMlBhQmq/XCn/1b+VazHvJXkoIFDF+wktMg+rKfLyfTlXdK0cs+Kn8h+rjMakkf3WLo1TftMLn+O+x/Gat+BGstJrM1xvCSSnHQY+NV4B4gRqyZ55gRNnqN/0lWrATOcHUaGXpkTIM/yxFjxcePcSFo+t2aJ5lShtVukETzRxaIXgRkpROeWQHWpTHOaexmXOzF0b833qJSoXMk2zB/uMrgDzKd7d3ohUz8Ra08WYKlAuMQD08bF4+jUepEspqPLoYLQ73TfmL+1LwKxyTV3gEu6WnxBPWPLnYIGYN9U47ZNlB+NgHgYtKTyii6060RAG+wN32WUVFxCZw0HMHnHFgwxD34L/anlpS7mOrjKgyuGYhFC7iHqTQHuoAO1ekBHV+rndnbETKfa1F7LxNLYq+dmJyytmQrJUCGjelorI1m/TMQNiFVrY4FCI1Gl2W1JsZsw9zA+Bh3JmjkC0H5/0JV6JotNMatJIZ4v5PqwJe3r8xd+FNS3ynccdu+xtVdc27qwVdoomciZD5oXYey9KAFSAKO594sBKZNWUJTLXnt0BJbdF8FkQYvg3DQajYY2p+ixd5Ag7o92gw0pVVDDOP+WQxiEmKqgWJyTBsnsBk2Bxi2Unsv8S/4PmE8Hy/vy+Mij+aTAKZvg716IHfHX0/JMeFfmAnsZ39Q0qkfdPtq6+CxbGZ7wKDsK/8l/MVGuyd6faJFt5wyoOXuNrr3JC9EoBmjcOzkVw/6RNP49poZ1xzsX3q7B4HGfI/XSfRQq3HeZ2j12d0E3gCAube4oExaT1sx/v8F+f61QOsGdSaqM2im6qOGkSRkrRQ7L8hvS8vEYJeVkAbFvX5ov7e/egYYNToMHj651c5/rCVYtB9Ned6GvGN8R0x3t7+lsf8+ofhHRzpyvwxd6c5pREZVOKnXzplhJ61mki4JmAAAABFWElGugAAAEV4aWYAAElJKgAIAAAABgASAQMAAQAAAAEAAAAaAQUAAQAAAFYAAAAbAQUAAQAAAF4AAAAoAQMAAQAAAAIAAAATAgMAAQAAAAEAAABphwQAAQAAAGYAAAAAAAAASAAAAAEAAABIAAAAAQAAAAYAAJAHAAQAAAAwMjEwAZEHAAQAAAABAgMAAKAHAAQAAAAwMTAwAaADAAEAAAD//wAAAqAEAAEAAAA8AAAAA6AEAAEAAAA8AAAAAAAAAA==", St = "data:image/svg+xml,%3csvg%20width='868'%20height='868'%20viewBox='0%200%20868%20868'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3ccircle%20cx='434'%20cy='434'%20r='434'%20fill='%231B262D'/%3e%3cpath%20fill-rule='evenodd'%20clip-rule='evenodd'%20d='M234.563%20184H640.697C650.387%20184%20659.339%20189.164%20664.172%20197.542L782.495%20402.657C788.631%20413.294%20786.808%20426.72%20778.056%20435.346L452.368%20756.327C441.818%20766.724%20424.846%20766.724%20414.296%20756.327L89.0484%20435.78C80.0927%20426.954%2078.4157%20413.136%2085.0013%20402.433L211.48%20196.884C216.405%20188.879%20225.146%20184%20234.563%20184ZM588.257%20275.577V333.129H472.567V373.032C553.82%20377.296%20614.782%20394.81%20615.234%20415.802L615.231%20459.563C614.779%20480.556%20553.82%20498.069%20472.567%20502.333V600.259H395.746V502.333C314.492%20498.069%20253.531%20480.555%20253.078%20459.563L253.081%20415.802C253.533%20394.81%20314.492%20377.296%20395.746%20373.032V333.129H280.055V275.577H588.257ZM434.156%20472.268C520.868%20472.268%20593.345%20457.459%20611.082%20437.683C596.041%20420.912%20541.636%20407.713%20472.567%20404.089V445.867C460.187%20446.516%20447.336%20446.858%20434.156%20446.858C420.976%20446.858%20408.125%20446.516%20395.746%20445.867V404.089C326.676%20407.713%20272.271%20420.912%20257.23%20437.683C274.968%20457.459%20347.444%20472.268%20434.156%20472.268Z'%20fill='%23009393'/%3e%3c/svg%3e", Pt = "data:image/webp;base64,UklGRqwEAABXRUJQVlA4WAoAAAAYAAAAOwAAOwAAQUxQSL8BAAABkGvbtmlLc5997yvbmW19gBnbDm2kjF5UmW3bthXZVZFdZ+81r+87Z1XlEaHIbSNlMstwos4XUBSTLAFQo/u01Zdf/yLDDze3zB/YwADJEoOoJAKg7oTdH4SF+XxiZlMgSESzwAJdVn2iUJzzOUMiLhQKf+/va2FtBLMBuu1zpHcsincUXhtoTKLsCTVX/KF3wrLhPLm/OWzZtjQWfZ7RhYyAC/lxMowpSzJYJAyFkZDQc21FBMUT7BqGjpHxf3m+XlEPUHE/f3vGgPzmw4awRUaTexkyJhwfNShctVgZXyJDXq4CUyjNy6Y4fVOBIkAPR2GcOE7Jm2NQ/RE9YzXht3a5VYvlOX0xF0fy+tp/ozBuQg6DzZYb6Bi7ed4rB5Mp/1Co4cNhLUo1StLxDIDqrynUoRswiF6nFnIxsDpnZ5WBW0GFZ1qZ8HfLDk5txHHsGDpSa6B0cXZEa+DsTr1M+P4qPdXwjynU4+1/a7oN3Sm6G+meSd27oHsHde++7puj+tYpv7G6b7vun6L7l6n+oZp/t7JmUNUqqhpJV5upakJVLaqqgVW1t6rmV401NGMc1djqH4rpIseSfyPFkgAAVlA4IAQCAABQDACdASo8ADwAPm0yk0akIyGhJgzogA2JaQAThroHvLxu+aPf5G2BYxv+B6XHzx6GPon/o+qz/tOAA/TM82gR0vnExWoiQRM36jlg2UIvwCSqySErzuguz9EP2x/7hsNazr91aIworWI7AAD+/TZ+6Ipl444OdT+2wU0Ov+T8oJuVP/vUbT/w1Jsv6Awnl6rvF/xetfOPt3gTQZZi0Y/AOx563J7CJkqTR/fc/n34zyeKzR80fhfv4ef+Hjhz/CX5aQo+58zg/FdE+7bLoophGfG0szI513EH+q+Gc73H1PFdJYf7CF8v5dhr3tMwEVX5Ji2ZxejK8xrf/E6nVXqlA4DrYNRP09InHc+fEqO/fH8xr+rMf4y1F9TOnwVffZblLoTP6lot0m/sh7sTiDQr0mIA8TiHoOffGDG6KzV+B3239udfhzD740gkRi/m53abX0Ku3vAgadgFFqL0vk8M/4aI+cI+0fbLW17mWGeMu21wSRRQiv5iNgGKR3vEGXAItcLDft1uUzWAfbe1X3zK/ymT7bA/76PB6UUknm+Y5MM4osurUXU/k7P38pN/3slnGfpFzjl4c3USY4mH9ZCJYUuC/kGEnq/yRPalPdODNFvW6s8MiQeQejYNRY0LsJ0WXkK8vXiDmihCivYAOPoSovesL7on+WAArDNM/BcQSQvCYABFWElGugAAAEV4aWYAAElJKgAIAAAABgASAQMAAQAAAAEAAAAaAQUAAQAAAFYAAAAbAQUAAQAAAF4AAAAoAQMAAQAAAAIAAAATAgMAAQAAAAEAAABphwQAAQAAAGYAAAAAAAAASAAAAAEAAABIAAAAAQAAAAYAAJAHAAQAAAAwMjEwAZEHAAQAAAABAgMAAKAHAAQAAAAwMTAwAaADAAEAAAD//wAAAqAEAAEAAAA8AAAAA6AEAAEAAAA8AAAAAAAAAA==", xt = "data:image/webp;base64,UklGRtgCAABXRUJQVlA4WAoAAAAIAAAAOwAAOwAAVlA4IPgBAABQCwCdASo8ADwAPm0wk0ekIqGhKBQMqIANiWkADPF3uV2D8VcQGk1mg+P36i9SLnZvYAQxszEWYzEwX1RVkqG/4BGbJgMSHqhKDFsjWsGfPPrvfef11goNmCDDlBJHVVD+8gAA/vu4q03kl+E7FpjtZ2gc8pQ619Hjv9NywoRZ6az43C1wcrRr/lWzJlJhLWMHN0MkVl1ueAf6Hn8StVzeUfMBXOKkgfe2msx7QWR5PnHW/5c6/35yrtWnrURc2q6UYlGin+v8C2dQqexkW6rX2EEijTI9eEQ46PWH3/59fM2AlMvvR2abaRk5XX7V1triQncRxvMfz5YmYDN+PY/ikcZUNaiFucKoUq5riv0eKCezuFNHecE11ojwJqWRSTWpalkz5autXp6vFS+FT1tWUsB/fs1CCOZxaA1vR1grOEaiuKe1RYm7e05psWtqbXLVmm1bA8Ly9PFkVdCbc6hR3UuBBsFGnVeGOUeMn2onnfvYhBMcM9YPxGdQkwZLXOk1VuQSTk01Shf3fZrFyRlFauftFdPYhKXwqrr+meav1P+KLKBVosqmHnFFfgExsQ/rOf3TSd+mOqQfJA+cF+HojNU7nmM3uDkoCBi+//Gqp+gPNNW8M4LFrol8rxE+7WsjqMgfwv1f+Nr25RtG1Wa/KkniRCAAAABFWElGugAAAEV4aWYAAElJKgAIAAAABgASAQMAAQAAAAEAAAAaAQUAAQAAAFYAAAAbAQUAAQAAAF4AAAAoAQMAAQAAAAIAAAATAgMAAQAAAAEAAABphwQAAQAAAGYAAAAAAAAASAAAAAEAAABIAAAAAQAAAAYAAJAHAAQAAAAwMjEwAZEHAAQAAAABAgMAAKAHAAQAAAAwMTAwAaADAAEAAAD//wAAAqAEAAEAAAA8AAAAA6AEAAEAAAA8AAAAAAAAAA==", Tt = {
1031
+ EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: {
1032
+ symbol: "USDC",
1033
+ decimals: 6,
1034
+ icon: Ct
1035
+ },
1036
+ Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB: {
1037
+ symbol: "USDT",
1038
+ decimals: 6,
1039
+ icon: St
1040
+ },
1041
+ "2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo": {
1042
+ symbol: "PYUSD",
1043
+ decimals: 6,
1044
+ icon: Pt
1045
+ },
1046
+ CASHx9KJUStyftLFWGvEVf59SGeG9sh5FfcnZMVPCASH: {
1047
+ symbol: "CASH",
1048
+ decimals: 6,
1049
+ icon: xt
1050
+ }
1051
+ }, te = Object.fromEntries(
1052
+ Object.entries(Tt).map(([r, e]) => [r, e.symbol])
1053
+ );
1054
+ function kt(r) {
1055
+ return r in te;
1056
+ }
1057
+ function Ie(r, e = "token mint", t = !1) {
1058
+ if (!r || r.trim().length === 0)
1059
+ return {
1060
+ isValid: !0,
1061
+ isKnownStablecoin: !1
1062
+ };
1063
+ const n = r.trim();
1064
+ if (kt(n))
1065
+ return {
1066
+ isValid: !0,
1067
+ isKnownStablecoin: !0,
1068
+ symbol: te[n]
1069
+ };
1070
+ const a = Object.entries(te).map(([i, o]) => ` ${o}: ${i}`).join(`
1071
+ `);
1072
+ return t ? {
1073
+ isValid: !0,
1074
+ // Allow but warn
1075
+ isKnownStablecoin: !1,
1076
+ warning: [
1077
+ `Warning: Unrecognized token mint address in ${e}`,
1078
+ ` Provided: ${n}`,
1079
+ "",
1080
+ "This token mint does not match any known stablecoin addresses.",
1081
+ "You have set dangerouslyAllowUnknownMint=true, so this will proceed.",
1082
+ "If this is a typo, payments will be sent to the wrong token and funds will be PERMANENTLY LOST.",
1083
+ "",
1084
+ "Known stablecoin mints (mainnet-beta):",
1085
+ a,
1086
+ "",
1087
+ "Double-check your token mint address before deploying to production."
1088
+ ].join(`
1089
+ `)
1090
+ } : {
1091
+ isValid: !1,
1092
+ isKnownStablecoin: !1,
1093
+ error: [
1094
+ `SAFETY ERROR: Unrecognized token mint address in ${e}`,
1095
+ ` Provided: ${n}`,
1096
+ "",
1097
+ "This token mint does not match any known stablecoin addresses.",
1098
+ "Using an unknown token mint can result in PERMANENT LOSS OF FUNDS if it's a typo.",
1099
+ "",
1100
+ "Known stablecoin mints (mainnet-beta):",
1101
+ a,
1102
+ "",
1103
+ "If you are CERTAIN this is the correct mint address (custom token, testnet, or new stablecoin),",
1104
+ "set dangerouslyAllowUnknownMint={true} in your CedrosProvider config:",
1105
+ "",
1106
+ " <CedrosProvider",
1107
+ " config={{",
1108
+ " ...",
1109
+ ' tokenMint: "' + n + '",',
1110
+ " dangerouslyAllowUnknownMint: true, // ⚠️ I have verified this mint address",
1111
+ " }}",
1112
+ " />",
1113
+ "",
1114
+ "⚠️ WARNING: Only enable dangerouslyAllowUnknownMint if you have TRIPLE-CHECKED the mint address."
1115
+ ].join(`
1116
+ `)
1117
+ };
1118
+ }
1119
+ function Rt(r, e = "unknown", t = !1) {
1120
+ return Ie(r, `X402Requirement (resource: ${e})`, t);
1121
+ }
1122
+ class Mt {
1123
+ connection;
1124
+ cluster;
1125
+ endpoint;
1126
+ allowUnknownMint;
1127
+ rpcRateLimiter = R({
1128
+ maxRequests: 50,
1129
+ windowMs: 6e4
1130
+ // 50 requests per minute for RPC calls
1131
+ });
1132
+ rpcCircuitBreaker = U({
1133
+ failureThreshold: 5,
1134
+ timeout: 1e4,
1135
+ // 10 seconds for faster recovery in payment flows
1136
+ name: "solana-rpc"
1137
+ });
1138
+ constructor(e = "mainnet-beta", t, n = !1) {
1139
+ this.cluster = e, this.endpoint = t, this.allowUnknownMint = n, this.connection = this.createConnection();
1140
+ }
1141
+ /**
1142
+ * Create Solana RPC connection
1143
+ */
1144
+ createConnection() {
1145
+ const e = this.endpoint ?? je(this.cluster);
1146
+ return new ze(e, "confirmed");
1147
+ }
1148
+ /**
1149
+ * Transform RPC errors into user-friendly messages
1150
+ */
1151
+ transformRpcError(e) {
1152
+ const t = e instanceof Error ? e.message : typeof e == "string" ? e : String(e);
1153
+ return t.includes("403") || t.includes("Access forbidden") ? new Error(
1154
+ "Public Solana RPC access denied. Please configure a custom RPC endpoint (e.g., from Helius, QuickNode, or Alchemy) in your CedrosProvider config using the solanaEndpoint option."
1155
+ ) : t.includes("429") || t.includes("Too Many Requests") ? new Error(
1156
+ "Solana RPC rate limit exceeded. Please configure a custom RPC endpoint with higher limits in your CedrosProvider config using the solanaEndpoint option."
1157
+ ) : e instanceof Error ? e : new Error(t);
1158
+ }
1159
+ /**
1160
+ * Build transaction from x402 requirement
1161
+ */
1162
+ async buildTransaction(e) {
1163
+ const { requirement: t, payerPublicKey: n, blockhash: a } = e;
1164
+ if (!t || !t.payTo)
1165
+ throw new Error("Invalid requirement: missing payTo");
1166
+ c().debug("[WalletManager] Building transaction for resource:", t.resource);
1167
+ const i = new oe(), o = this.resolveAmountInMinorUnits(t), s = t.asset;
1168
+ if (!s)
1169
+ throw new Error("asset is required in x402 requirement");
1170
+ const u = Rt(s, t.resource, this.allowUnknownMint);
1171
+ if (!u.isValid && u.error)
1172
+ throw new Error(u.error);
1173
+ u.warning && c().warn(u.warning);
1174
+ const l = new N(s), d = await Qe(
1175
+ l,
1176
+ n
1177
+ );
1178
+ if (!this.rpcRateLimiter.tryConsume())
1179
+ throw new Error("RPC rate limit exceeded. Please try again in a moment.");
1180
+ let f;
1181
+ try {
1182
+ f = await this.rpcCircuitBreaker.execute(async () => await g(
1183
+ async () => await this.connection.getAccountInfo(d),
1184
+ { ...b.QUICK, name: "rpc-get-account-info" }
1185
+ ));
1186
+ } catch (p) {
1187
+ throw p instanceof m ? new Error("Solana RPC service is temporarily unavailable. Please try again in a few moments.") : this.transformRpcError(p);
1188
+ }
1189
+ if (!f)
1190
+ throw new Error("Payer is missing an associated token account for this mint");
1191
+ let h;
1192
+ try {
1193
+ h = t.extra?.recipientTokenAccount ? new N(t.extra.recipientTokenAccount) : new N(t.payTo);
1194
+ } catch {
1195
+ throw new Error("We are currently unable to process payment, please try again later");
1196
+ }
1197
+ if (i.add(
1198
+ We(
1199
+ d,
1200
+ h,
1201
+ n,
1202
+ o
1203
+ )
1204
+ ), t.extra?.memo) {
1205
+ const { TransactionInstruction: p } = await import("@solana/web3.js"), w = new p({
1206
+ keys: [],
1207
+ programId: new N("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"),
1208
+ data: Buffer.from(t.extra.memo, "utf8")
1209
+ });
1210
+ i.add(w);
1211
+ }
1212
+ let A;
1213
+ if (a)
1214
+ A = a;
1215
+ else {
1216
+ if (!this.rpcRateLimiter.tryConsume())
1217
+ throw new Error("RPC rate limit exceeded. Please try again in a moment.");
1218
+ try {
1219
+ A = (await this.rpcCircuitBreaker.execute(async () => await g(
1220
+ async () => await this.connection.getLatestBlockhash(),
1221
+ { ...b.QUICK, name: "rpc-get-blockhash" }
1222
+ ))).blockhash;
1223
+ } catch (p) {
1224
+ throw p instanceof m ? new Error("Solana RPC service is temporarily unavailable. Please try again in a few moments.") : this.transformRpcError(p);
1225
+ }
1226
+ }
1227
+ return i.recentBlockhash = A, t.extra?.feePayer ? i.feePayer = new N(t.extra.feePayer) : i.feePayer = n, i;
1228
+ }
1229
+ /**
1230
+ * Parse amount from x402 requirement (already in atomic units as string)
1231
+ */
1232
+ resolveAmountInMinorUnits(e) {
1233
+ const t = parseInt(e.maxAmountRequired, 10);
1234
+ if (Number.isNaN(t) || t <= 0)
1235
+ throw new Error("Invalid maxAmountRequired in requirement");
1236
+ return t;
1237
+ }
1238
+ /**
1239
+ * Build payment payload from signed transaction (x402 spec)
1240
+ */
1241
+ buildPaymentPayload(e) {
1242
+ const { requirement: t, signedTx: n, payerPublicKey: a } = e;
1243
+ return {
1244
+ x402Version: 0,
1245
+ scheme: t.scheme,
1246
+ network: t.network,
1247
+ payload: {
1248
+ signature: n.signature,
1249
+ transaction: n.serialized,
1250
+ payer: a.toString(),
1251
+ memo: t.extra?.memo,
1252
+ recipientTokenAccount: t.extra?.recipientTokenAccount
1253
+ }
1254
+ };
1255
+ }
1256
+ /**
1257
+ * Sign transaction using wallet adapter (fully signed for regular mode)
1258
+ */
1259
+ async signTransaction(e) {
1260
+ const { transaction: t, signTransaction: n } = e;
1261
+ c().debug("[WalletManager] Requesting wallet to sign transaction");
1262
+ const a = await n(t), i = a.serialize(), o = a.signatures[0]?.signature;
1263
+ if (!o)
1264
+ throw new Error("Signed transaction missing signature");
1265
+ const s = he.encode(o);
1266
+ return c().debug("[WalletManager] Transaction signed with signature:", s.substring(0, 20) + "..."), {
1267
+ serialized: z.fromUint8Array(i),
1268
+ signature: s
1269
+ };
1270
+ }
1271
+ /**
1272
+ * Deserialize a base64-encoded transaction from the backend
1273
+ * Used for gasless flow where backend builds the complete transaction
1274
+ */
1275
+ deserializeTransaction(e) {
1276
+ try {
1277
+ const t = z.toUint8Array(e);
1278
+ return oe.from(t);
1279
+ } catch (t) {
1280
+ throw new Error(
1281
+ `Failed to deserialize transaction: ${k(t, "Unknown error")}`
1282
+ );
1283
+ }
1284
+ }
1285
+ /**
1286
+ * Partially sign transaction for gasless mode
1287
+ * User signs their authority, server will co-sign as fee payer
1288
+ */
1289
+ async partiallySignTransaction(e) {
1290
+ const { transaction: t, signTransaction: n, blockhash: a } = e;
1291
+ a && t.recentBlockhash !== a && (t.recentBlockhash = a);
1292
+ const i = await n(t), o = i.signatures[0]?.signature;
1293
+ if (o) {
1294
+ const u = he.encode(o);
1295
+ c().debug("[WalletManager] Partially signed with signature:", u.substring(0, 20) + "...");
1296
+ }
1297
+ const s = i.serialize({
1298
+ requireAllSignatures: !1,
1299
+ verifySignatures: !1
1300
+ });
1301
+ return z.fromUint8Array(s);
1302
+ }
1303
+ /**
1304
+ * Get wallet balance
1305
+ */
1306
+ async getBalance(e) {
1307
+ if (!this.rpcRateLimiter.tryConsume())
1308
+ throw new Error("RPC rate limit exceeded. Please try again in a moment.");
1309
+ try {
1310
+ return await this.rpcCircuitBreaker.execute(async () => await g(
1311
+ async () => await this.connection.getBalance(e),
1312
+ { ...b.QUICK, name: "rpc-get-balance" }
1313
+ )) / qe;
1314
+ } catch (t) {
1315
+ throw t instanceof m ? new Error("Solana RPC service is temporarily unavailable. Please try again in a few moments.") : this.transformRpcError(t);
1316
+ }
1317
+ }
1318
+ /**
1319
+ * Verify transaction on-chain
1320
+ */
1321
+ async verifyTransaction(e) {
1322
+ if (!this.rpcRateLimiter.tryConsume())
1323
+ return c().warn("[WalletManager] RPC rate limit exceeded for transaction verification"), !1;
1324
+ try {
1325
+ return !!(await this.rpcCircuitBreaker.execute(async () => await g(
1326
+ async () => await this.connection.getSignatureStatus(e),
1327
+ { ...b.QUICK, name: "rpc-verify-tx" }
1328
+ ))).value?.confirmationStatus;
1329
+ } catch (t) {
1330
+ return t instanceof m && c().warn("[WalletManager] Circuit breaker OPEN - cannot verify transaction"), !1;
1331
+ }
1332
+ }
1333
+ }
1334
+ class Dt {
1335
+ stripe = null;
1336
+ publicKey;
1337
+ routeDiscovery;
1338
+ // Separate rate limiters for different operation types
1339
+ sessionRateLimiter = R(M.PAYMENT);
1340
+ statusRateLimiter = R(M.QUOTE);
1341
+ circuitBreaker = U({
1342
+ failureThreshold: 5,
1343
+ timeout: 1e4,
1344
+ // 10 seconds for faster recovery
1345
+ name: "subscription-manager"
1346
+ });
1347
+ constructor(e, t) {
1348
+ this.publicKey = e, this.routeDiscovery = t;
1349
+ }
1350
+ /** Initialize Stripe.js library */
1351
+ async initialize() {
1352
+ if (!this.stripe && (this.stripe = await ve(this.publicKey), !this.stripe))
1353
+ throw new Error("Failed to initialize Stripe");
1354
+ }
1355
+ /** Internal helper: execute with rate limiting, circuit breaker, and retry */
1356
+ async executeWithResilience(e, t, n, a) {
1357
+ if (!e.tryConsume())
1358
+ throw new Error("Rate limit exceeded. Please try again later.");
1359
+ try {
1360
+ return await this.circuitBreaker.execute(
1361
+ () => g(t, { ...b.STANDARD, name: n })
1362
+ );
1363
+ } catch (i) {
1364
+ throw i instanceof m ? (c().error(`[SubscriptionManager] Circuit breaker OPEN for ${a}`), new Error("Service temporarily unavailable. Please try again in a few moments.")) : i;
1365
+ }
1366
+ }
1367
+ /**
1368
+ * Create a Stripe subscription checkout session
1369
+ */
1370
+ async createSubscriptionSession(e) {
1371
+ if (!this.sessionRateLimiter.tryConsume())
1372
+ throw new Error("Rate limit exceeded for subscription session creation. Please try again later.");
1373
+ try {
1374
+ return await this.circuitBreaker.execute(async () => await g(
1375
+ async () => {
1376
+ const t = await this.routeDiscovery.buildUrl("/paywall/v1/subscription/stripe-session");
1377
+ c().debug("[SubscriptionManager] Creating subscription session:", {
1378
+ resource: e.resource,
1379
+ interval: e.interval,
1380
+ trialDays: e.trialDays
1381
+ });
1382
+ const n = await y(t, {
1383
+ method: "POST",
1384
+ headers: {
1385
+ "Content-Type": "application/json",
1386
+ "Idempotency-Key": T()
1387
+ },
1388
+ body: JSON.stringify(e)
1389
+ });
1390
+ if (!n.ok) {
1391
+ const a = await v(
1392
+ n,
1393
+ "Failed to create subscription session"
1394
+ );
1395
+ throw new Error(a);
1396
+ }
1397
+ return await n.json();
1398
+ },
1399
+ { ...b.STANDARD, name: "subscription-create-session" }
1400
+ ));
1401
+ } catch (t) {
1402
+ throw t instanceof m ? (c().error("[SubscriptionManager] Circuit breaker is OPEN - service unavailable"), new Error(
1403
+ "Subscription service is temporarily unavailable. Please try again in a few moments."
1404
+ )) : t;
1405
+ }
1406
+ }
1407
+ /**
1408
+ * Redirect to Stripe checkout
1409
+ */
1410
+ async redirectToCheckout(e) {
1411
+ if (this.stripe || await this.initialize(), !this.stripe)
1412
+ return {
1413
+ success: !1,
1414
+ error: "Stripe not initialized"
1415
+ };
1416
+ const t = await this.stripe.redirectToCheckout({ sessionId: e });
1417
+ return t.error ? {
1418
+ success: !1,
1419
+ error: t.error.message
1420
+ } : { success: !0, transactionId: e };
1421
+ }
1422
+ /**
1423
+ * Complete subscription flow: create session and redirect
1424
+ */
1425
+ async processSubscription(e) {
1426
+ try {
1427
+ const t = await this.createSubscriptionSession(e);
1428
+ return await this.redirectToCheckout(t.sessionId);
1429
+ } catch (t) {
1430
+ return {
1431
+ success: !1,
1432
+ error: k(t, "Subscription failed")
1433
+ };
1434
+ }
1435
+ }
1436
+ /**
1437
+ * Check subscription status (for x402 gating)
1438
+ */
1439
+ async checkSubscriptionStatus(e) {
1440
+ if (!this.statusRateLimiter.tryConsume())
1441
+ throw new Error("Rate limit exceeded for subscription status check. Please try again later.");
1442
+ try {
1443
+ return await this.circuitBreaker.execute(async () => await g(
1444
+ async () => {
1445
+ const t = new URLSearchParams({
1446
+ resource: e.resource,
1447
+ userId: e.userId
1448
+ }), n = await this.routeDiscovery.buildUrl(
1449
+ `/paywall/v1/subscription/status?${t.toString()}`
1450
+ );
1451
+ c().debug("[SubscriptionManager] Checking subscription status:", e);
1452
+ const a = await y(n, {
1453
+ method: "GET",
1454
+ headers: {
1455
+ "Content-Type": "application/json"
1456
+ }
1457
+ });
1458
+ if (!a.ok) {
1459
+ const i = await v(
1460
+ a,
1461
+ "Failed to check subscription status"
1462
+ );
1463
+ throw new Error(i);
1464
+ }
1465
+ return await a.json();
1466
+ },
1467
+ { ...b.STANDARD, name: "subscription-status-check" }
1468
+ ));
1469
+ } catch (t) {
1470
+ throw t instanceof m ? (c().error("[SubscriptionManager] Circuit breaker is OPEN for status check"), new Error(
1471
+ "Subscription status service is temporarily unavailable. Please try again in a few moments."
1472
+ )) : t;
1473
+ }
1474
+ }
1475
+ /**
1476
+ * Request a subscription quote for x402 crypto payment
1477
+ */
1478
+ async requestSubscriptionQuote(e, t, n) {
1479
+ if (!this.statusRateLimiter.tryConsume())
1480
+ throw new Error("Rate limit exceeded for subscription quote. Please try again later.");
1481
+ try {
1482
+ return await this.circuitBreaker.execute(async () => await g(
1483
+ async () => {
1484
+ const a = await this.routeDiscovery.buildUrl("/paywall/v1/subscription/quote"), i = {
1485
+ resource: e,
1486
+ interval: t,
1487
+ couponCode: n?.couponCode,
1488
+ intervalDays: n?.intervalDays
1489
+ };
1490
+ c().debug("[SubscriptionManager] Requesting subscription quote:", i);
1491
+ const o = await y(a, {
1492
+ method: "POST",
1493
+ headers: {
1494
+ "Content-Type": "application/json"
1495
+ },
1496
+ body: JSON.stringify(i)
1497
+ });
1498
+ if (o.status !== 402 && !o.ok) {
1499
+ const s = await v(
1500
+ o,
1501
+ "Failed to get subscription quote"
1502
+ );
1503
+ throw new Error(s);
1504
+ }
1505
+ return await o.json();
1506
+ },
1507
+ { ...b.STANDARD, name: "subscription-quote" }
1508
+ ));
1509
+ } catch (a) {
1510
+ throw a instanceof m ? (c().error("[SubscriptionManager] Circuit breaker is OPEN for quote"), new Error(
1511
+ "Subscription quote service is temporarily unavailable. Please try again in a few moments."
1512
+ )) : a;
1513
+ }
1514
+ }
1515
+ /** Cancel a subscription */
1516
+ async cancelSubscription(e) {
1517
+ return this.executeWithResilience(
1518
+ this.sessionRateLimiter,
1519
+ async () => {
1520
+ const t = await this.routeDiscovery.buildUrl("/paywall/v1/subscription/cancel");
1521
+ c().debug("[SubscriptionManager] Canceling subscription:", e);
1522
+ const n = await y(t, {
1523
+ method: "POST",
1524
+ headers: { "Content-Type": "application/json" },
1525
+ body: JSON.stringify(e)
1526
+ });
1527
+ if (!n.ok) throw new Error(await v(n, "Failed to cancel"));
1528
+ return await n.json();
1529
+ },
1530
+ "subscription-cancel",
1531
+ "cancellation"
1532
+ );
1533
+ }
1534
+ /** Get Stripe billing portal URL for subscription management */
1535
+ async getBillingPortalUrl(e) {
1536
+ return this.executeWithResilience(
1537
+ this.statusRateLimiter,
1538
+ async () => {
1539
+ const t = await this.routeDiscovery.buildUrl("/paywall/v1/subscription/portal");
1540
+ c().debug("[SubscriptionManager] Getting billing portal URL:", e);
1541
+ const n = await y(t, {
1542
+ method: "POST",
1543
+ headers: { "Content-Type": "application/json" },
1544
+ body: JSON.stringify(e)
1545
+ });
1546
+ if (!n.ok) throw new Error(await v(n, "Failed to get portal"));
1547
+ return await n.json();
1548
+ },
1549
+ "subscription-portal",
1550
+ "portal"
1551
+ );
1552
+ }
1553
+ /** Activate x402 subscription after payment verification */
1554
+ async activateX402Subscription(e) {
1555
+ return this.executeWithResilience(
1556
+ this.sessionRateLimiter,
1557
+ async () => {
1558
+ const t = await this.routeDiscovery.buildUrl("/paywall/v1/subscription/x402/activate");
1559
+ c().debug("[SubscriptionManager] Activating x402 subscription:", e);
1560
+ const n = await y(t, {
1561
+ method: "POST",
1562
+ headers: { "Content-Type": "application/json" },
1563
+ body: JSON.stringify(e)
1564
+ });
1565
+ if (!n.ok) throw new Error(await v(n, "Failed to activate"));
1566
+ return await n.json();
1567
+ },
1568
+ "subscription-activate",
1569
+ "activation"
1570
+ );
1571
+ }
1572
+ }
1573
+ class Bt {
1574
+ routeDiscovery;
1575
+ rateLimiter = R(M.PAYMENT);
1576
+ queryRateLimiter = R(M.QUOTE);
1577
+ circuitBreaker = U({
1578
+ failureThreshold: 5,
1579
+ timeout: 1e4,
1580
+ name: "subscription-change-manager"
1581
+ });
1582
+ constructor(e) {
1583
+ this.routeDiscovery = e;
1584
+ }
1585
+ /** Internal helper: execute with rate limiting, circuit breaker, and retry */
1586
+ async executeWithResilience(e, t, n, a) {
1587
+ if (!e.tryConsume())
1588
+ throw new Error("Rate limit exceeded. Please try again later.");
1589
+ try {
1590
+ return await this.circuitBreaker.execute(
1591
+ () => g(t, { ...b.STANDARD, name: n })
1592
+ );
1593
+ } catch (i) {
1594
+ throw i instanceof m ? (c().error(`[SubscriptionChangeManager] Circuit breaker OPEN for ${a}`), new Error("Service temporarily unavailable. Please try again in a few moments.")) : i;
1595
+ }
1596
+ }
1597
+ /** Change subscription plan (upgrade or downgrade) */
1598
+ async changeSubscription(e) {
1599
+ return this.executeWithResilience(
1600
+ this.rateLimiter,
1601
+ async () => {
1602
+ const t = await this.routeDiscovery.buildUrl("/paywall/v1/subscription/change");
1603
+ c().debug("[SubscriptionChangeManager] Changing subscription:", e);
1604
+ const n = await y(t, {
1605
+ method: "POST",
1606
+ headers: { "Content-Type": "application/json", "Idempotency-Key": T() },
1607
+ body: JSON.stringify(e)
1608
+ });
1609
+ if (!n.ok)
1610
+ throw new Error(await v(n, "Failed to change subscription"));
1611
+ return await n.json();
1612
+ },
1613
+ "subscription-change",
1614
+ "plan change"
1615
+ );
1616
+ }
1617
+ /** Preview subscription change (get proration details) */
1618
+ async previewChange(e) {
1619
+ return this.executeWithResilience(
1620
+ this.queryRateLimiter,
1621
+ async () => {
1622
+ const t = await this.routeDiscovery.buildUrl("/paywall/v1/subscription/change/preview");
1623
+ c().debug("[SubscriptionChangeManager] Previewing subscription change:", e);
1624
+ const n = await y(t, {
1625
+ method: "POST",
1626
+ headers: { "Content-Type": "application/json" },
1627
+ body: JSON.stringify(e)
1628
+ });
1629
+ if (!n.ok)
1630
+ throw new Error(await v(n, "Failed to preview change"));
1631
+ return await n.json();
1632
+ },
1633
+ "subscription-preview",
1634
+ "change preview"
1635
+ );
1636
+ }
1637
+ /** Get full subscription details */
1638
+ async getDetails(e, t) {
1639
+ return this.executeWithResilience(
1640
+ this.queryRateLimiter,
1641
+ async () => {
1642
+ const n = new URLSearchParams({ resource: e, userId: t }), a = await this.routeDiscovery.buildUrl(`/paywall/v1/subscription/details?${n}`);
1643
+ c().debug("[SubscriptionChangeManager] Getting subscription details:", { resource: e, userId: t });
1644
+ const i = await y(a, {
1645
+ method: "GET",
1646
+ headers: { "Content-Type": "application/json" }
1647
+ });
1648
+ if (!i.ok)
1649
+ throw new Error(await v(i, "Failed to get subscription details"));
1650
+ return await i.json();
1651
+ },
1652
+ "subscription-details",
1653
+ "details"
1654
+ );
1655
+ }
1656
+ /** Cancel a subscription */
1657
+ async cancel(e) {
1658
+ return this.executeWithResilience(
1659
+ this.rateLimiter,
1660
+ async () => {
1661
+ const t = await this.routeDiscovery.buildUrl("/paywall/v1/subscription/cancel");
1662
+ c().debug("[SubscriptionChangeManager] Canceling subscription:", e);
1663
+ const n = await y(t, {
1664
+ method: "POST",
1665
+ headers: { "Content-Type": "application/json" },
1666
+ body: JSON.stringify(e)
1667
+ });
1668
+ if (!n.ok)
1669
+ throw new Error(await v(n, "Failed to cancel subscription"));
1670
+ return await n.json();
1671
+ },
1672
+ "subscription-cancel",
1673
+ "cancellation"
1674
+ );
1675
+ }
1676
+ /** Get Stripe billing portal URL */
1677
+ async getBillingPortalUrl(e) {
1678
+ return this.executeWithResilience(
1679
+ this.queryRateLimiter,
1680
+ async () => {
1681
+ const t = await this.routeDiscovery.buildUrl("/paywall/v1/subscription/portal");
1682
+ c().debug("[SubscriptionChangeManager] Getting billing portal URL:", e);
1683
+ const n = await y(t, {
1684
+ method: "POST",
1685
+ headers: { "Content-Type": "application/json" },
1686
+ body: JSON.stringify(e)
1687
+ });
1688
+ if (!n.ok)
1689
+ throw new Error(await v(n, "Failed to get billing portal URL"));
1690
+ return await n.json();
1691
+ },
1692
+ "subscription-portal",
1693
+ "portal"
1694
+ );
1695
+ }
1696
+ }
1697
+ class Ut {
1698
+ routeDiscovery;
1699
+ rateLimiter = R(M.PAYMENT);
1700
+ circuitBreaker = U({
1701
+ failureThreshold: 5,
1702
+ timeout: 1e4,
1703
+ name: "credits-manager"
1704
+ });
1705
+ constructor(e) {
1706
+ this.routeDiscovery = e;
1707
+ }
1708
+ async requestQuote(e, t) {
1709
+ if (!this.rateLimiter.tryConsume())
1710
+ throw new Error("Rate limit exceeded for credits quote. Please try again later.");
1711
+ try {
1712
+ return await this.circuitBreaker.execute(async () => await g(
1713
+ async () => {
1714
+ const n = await this.routeDiscovery.buildUrl("/paywall/v1/quote");
1715
+ c().debug("[CreditsManager] Requesting quote for resource:", e);
1716
+ const a = await y(n, {
1717
+ method: "POST",
1718
+ headers: { "Content-Type": "application/json" },
1719
+ body: JSON.stringify({ resource: e, couponCode: t })
1720
+ });
1721
+ if (a.status === 402)
1722
+ return (await a.json()).credits || null;
1723
+ if (!a.ok) {
1724
+ const i = await v(a, "Failed to get credits quote");
1725
+ throw new Error(i);
1726
+ }
1727
+ return null;
1728
+ },
1729
+ { ...b.STANDARD, name: "credits-quote" }
1730
+ ));
1731
+ } catch (n) {
1732
+ throw n instanceof m ? (c().error("[CreditsManager] Circuit breaker is OPEN - credits service unavailable"), new Error("Credits service is temporarily unavailable. Please try again in a few moments.")) : n;
1733
+ }
1734
+ }
1735
+ async requestCartQuote(e, t) {
1736
+ if (!this.rateLimiter.tryConsume())
1737
+ throw new Error("Rate limit exceeded for cart credits quote. Please try again later.");
1738
+ try {
1739
+ return await this.circuitBreaker.execute(async () => await g(
1740
+ async () => {
1741
+ const n = await this.routeDiscovery.buildUrl("/paywall/v1/cart/quote");
1742
+ c().debug("[CreditsManager] Requesting cart quote for items:", e.length);
1743
+ const a = await y(n, {
1744
+ method: "POST",
1745
+ headers: { "Content-Type": "application/json" },
1746
+ body: JSON.stringify({ items: e, couponCode: t })
1747
+ });
1748
+ if (!a.ok) {
1749
+ const o = await v(a, "Failed to get cart credits quote");
1750
+ throw new Error(o);
1751
+ }
1752
+ const i = await a.json();
1753
+ return i.credits ? {
1754
+ cartId: i.cartId,
1755
+ credits: i.credits
1756
+ } : null;
1757
+ },
1758
+ { ...b.STANDARD, name: "credits-cart-quote" }
1759
+ ));
1760
+ } catch (n) {
1761
+ throw n instanceof m ? new Error("Credits service is temporarily unavailable. Please try again in a few moments.") : n;
1762
+ }
1763
+ }
1764
+ /**
1765
+ * Create a hold on user's credits
1766
+ * Requires Authorization header with cedros-login JWT token
1767
+ */
1768
+ async createHold(e) {
1769
+ const { resource: t, couponCode: n, authToken: a } = e;
1770
+ if (!this.rateLimiter.tryConsume())
1771
+ throw new Error("Rate limit exceeded for credits hold. Please try again later.");
1772
+ try {
1773
+ return await this.circuitBreaker.execute(async () => await g(
1774
+ async () => {
1775
+ const i = await this.routeDiscovery.buildUrl("/paywall/v1/credits/hold");
1776
+ c().debug("[CreditsManager] Creating hold for resource:", t);
1777
+ const o = await y(i, {
1778
+ method: "POST",
1779
+ headers: {
1780
+ "Content-Type": "application/json",
1781
+ Authorization: `Bearer ${a}`,
1782
+ "Idempotency-Key": T()
1783
+ },
1784
+ body: JSON.stringify({ resource: t, couponCode: n })
1785
+ });
1786
+ if (!o.ok) {
1787
+ const s = await v(o, "Failed to create credits hold");
1788
+ throw new Error(s);
1789
+ }
1790
+ return await o.json();
1791
+ },
1792
+ { ...b.STANDARD, name: "credits-create-hold" }
1793
+ ));
1794
+ } catch (i) {
1795
+ throw i instanceof m ? new Error("Credits service is temporarily unavailable. Please try again in a few moments.") : i;
1796
+ }
1797
+ }
1798
+ /**
1799
+ * Create a hold on user's credits for a cart
1800
+ * Requires Authorization header with cedros-login JWT token
1801
+ */
1802
+ async createCartHold(e) {
1803
+ const { cartId: t, authToken: n } = e;
1804
+ if (!this.rateLimiter.tryConsume())
1805
+ throw new Error("Rate limit exceeded for cart credits hold. Please try again later.");
1806
+ try {
1807
+ return await this.circuitBreaker.execute(async () => await g(
1808
+ async () => {
1809
+ const a = await this.routeDiscovery.buildUrl(`/paywall/v1/cart/${t}/credits/hold`);
1810
+ c().debug("[CreditsManager] Creating cart hold for cart:", t);
1811
+ const i = await y(a, {
1812
+ method: "POST",
1813
+ headers: {
1814
+ "Content-Type": "application/json",
1815
+ Authorization: `Bearer ${n}`,
1816
+ "Idempotency-Key": T()
1817
+ },
1818
+ body: JSON.stringify({})
1819
+ });
1820
+ if (!i.ok) {
1821
+ const o = await v(i, "Failed to create cart credits hold");
1822
+ throw new Error(o);
1823
+ }
1824
+ return await i.json();
1825
+ },
1826
+ { ...b.STANDARD, name: "credits-create-cart-hold" }
1827
+ ));
1828
+ } catch (a) {
1829
+ throw a instanceof m ? new Error("Credits service is temporarily unavailable. Please try again in a few moments.") : a;
1830
+ }
1831
+ }
1832
+ async authorizePayment(e) {
1833
+ const { resource: t, holdId: n, couponCode: a, authToken: i, metadata: o } = e;
1834
+ if (!this.rateLimiter.tryConsume())
1835
+ return {
1836
+ success: !1,
1837
+ error: "Rate limit exceeded for credits authorization. Please try again later.",
1838
+ errorCode: "rate_limit_exceeded"
1839
+ };
1840
+ try {
1841
+ return await this.circuitBreaker.execute(async () => await g(
1842
+ async () => {
1843
+ const s = await this.routeDiscovery.buildUrl("/paywall/v1/credits/authorize");
1844
+ c().debug("[CreditsManager] Authorizing payment for resource:", t);
1845
+ const u = await y(s, {
1846
+ method: "POST",
1847
+ headers: {
1848
+ "Content-Type": "application/json",
1849
+ Authorization: `Bearer ${i}`,
1850
+ "Idempotency-Key": T()
1851
+ },
1852
+ body: JSON.stringify({
1853
+ resource: t,
1854
+ holdId: n,
1855
+ couponCode: a,
1856
+ ...o && { metadata: o }
1857
+ })
1858
+ });
1859
+ if (!u.ok) {
1860
+ const d = await u.json().catch(() => ({}));
1861
+ return {
1862
+ success: !1,
1863
+ error: d.error?.message || "Credits authorization failed",
1864
+ errorCode: d.error?.code || "authorization_failed"
1865
+ };
1866
+ }
1867
+ return {
1868
+ success: !0,
1869
+ transactionId: (await u.json()).transactionId
1870
+ };
1871
+ },
1872
+ { ...b.STANDARD, name: "credits-authorize" }
1873
+ ));
1874
+ } catch (s) {
1875
+ return s instanceof m ? {
1876
+ success: !1,
1877
+ error: "Credits service is temporarily unavailable. Please try again in a few moments.",
1878
+ errorCode: "service_unavailable"
1879
+ } : {
1880
+ success: !1,
1881
+ error: k(s, "Credits authorization failed"),
1882
+ errorCode: "authorization_failed"
1883
+ };
1884
+ }
1885
+ }
1886
+ async authorizeCartPayment(e) {
1887
+ const { cartId: t, holdId: n, authToken: a, metadata: i } = e;
1888
+ if (!this.rateLimiter.tryConsume())
1889
+ return {
1890
+ success: !1,
1891
+ error: "Rate limit exceeded for cart credits authorization. Please try again later.",
1892
+ errorCode: "rate_limit_exceeded"
1893
+ };
1894
+ try {
1895
+ return await this.circuitBreaker.execute(async () => await g(
1896
+ async () => {
1897
+ const o = await this.routeDiscovery.buildUrl(`/paywall/v1/cart/${t}/credits/authorize`);
1898
+ c().debug("[CreditsManager] Authorizing cart payment for cart:", t);
1899
+ const s = await y(o, {
1900
+ method: "POST",
1901
+ headers: {
1902
+ "Content-Type": "application/json",
1903
+ Authorization: `Bearer ${a}`,
1904
+ "Idempotency-Key": T()
1905
+ },
1906
+ body: JSON.stringify({
1907
+ holdId: n,
1908
+ ...i && { metadata: i }
1909
+ })
1910
+ });
1911
+ if (!s.ok) {
1912
+ const l = await s.json().catch((d) => (c().error("[CreditsManager] Failed to parse error response JSON:", d, {
1913
+ cartId: t,
1914
+ status: s.status,
1915
+ statusText: s.statusText
1916
+ }), {}));
1917
+ return {
1918
+ success: !1,
1919
+ error: l.error?.message || "Cart credits authorization failed",
1920
+ errorCode: l.error?.code || "authorization_failed"
1921
+ };
1922
+ }
1923
+ return {
1924
+ success: !0,
1925
+ transactionId: (await s.json()).transactionId
1926
+ };
1927
+ },
1928
+ { ...b.STANDARD, name: "credits-cart-authorize" }
1929
+ ));
1930
+ } catch (o) {
1931
+ return o instanceof m ? {
1932
+ success: !1,
1933
+ error: "Credits service is temporarily unavailable. Please try again in a few moments.",
1934
+ errorCode: "service_unavailable"
1935
+ } : {
1936
+ success: !1,
1937
+ error: k(o, "Cart credits authorization failed"),
1938
+ errorCode: "authorization_failed"
1939
+ };
1940
+ }
1941
+ }
1942
+ /**
1943
+ * Process a complete credits payment (convenience method)
1944
+ * Combines createHold + authorizePayment in one call
1945
+ *
1946
+ * @param resource - Resource being purchased
1947
+ * @param authToken - JWT token from cedros-login
1948
+ * @param couponCode - Optional coupon code
1949
+ * @param metadata - Optional metadata
1950
+ */
1951
+ async processPayment(e, t, n, a) {
1952
+ try {
1953
+ const i = await this.createHold({ resource: e, couponCode: n, authToken: t }), o = await this.authorizePayment({
1954
+ resource: e,
1955
+ holdId: i.holdId,
1956
+ couponCode: n,
1957
+ authToken: t,
1958
+ metadata: a
1959
+ });
1960
+ return {
1961
+ success: o.success,
1962
+ transactionId: o.transactionId,
1963
+ error: o.error
1964
+ };
1965
+ } catch (i) {
1966
+ return {
1967
+ success: !1,
1968
+ error: k(i, "Credits payment failed")
1969
+ };
1970
+ }
1971
+ }
1972
+ }
1973
+ class Ot {
1974
+ serverUrl;
1975
+ routePrefix = null;
1976
+ discoveryPromise = null;
1977
+ maxRetries = 3;
1978
+ baseDelayMs = 1e3;
1979
+ constructor(e) {
1980
+ this.serverUrl = e;
1981
+ }
1982
+ /**
1983
+ * Discover route prefix from backend health endpoint
1984
+ *
1985
+ * DEDUPLICATION: Multiple concurrent calls share the same in-flight request
1986
+ * SECURITY FIX: Only cache on success, retry on failures with exponential backoff
1987
+ * This prevents permanent bricking of payments due to transient failures
1988
+ */
1989
+ async discoverPrefix() {
1990
+ if (this.routePrefix !== null)
1991
+ return this.routePrefix;
1992
+ if (this.discoveryPromise)
1993
+ return this.discoveryPromise;
1994
+ const e = (async () => {
1995
+ let t = 0;
1996
+ for (; t < this.maxRetries; )
1997
+ try {
1998
+ const n = await y(`${this.serverUrl}/cedros-health`);
1999
+ if (!n.ok) {
2000
+ if (n.status >= 400 && n.status < 500)
2001
+ return c().warn(`Route discovery received ${n.status} - not retrying client error`), this.routePrefix = "", "";
2002
+ throw new Error(`Health check returned ${n.status}`);
2003
+ }
2004
+ const i = (await n.json()).routePrefix || "";
2005
+ return this.routePrefix = i, c().debug("Route discovery successful, prefix:", i || "(empty)"), i;
2006
+ } catch (n) {
2007
+ if (t++, t >= this.maxRetries)
2008
+ return c().warn(
2009
+ `Route discovery failed after ${t} attempts, using empty prefix for this request:`,
2010
+ n
2011
+ ), "";
2012
+ const a = this.baseDelayMs * Math.pow(2, t - 1);
2013
+ c().warn(
2014
+ `Route discovery failed (attempt ${t}/${this.maxRetries}), retrying in ${a}ms:`,
2015
+ n
2016
+ ), await new Promise((i) => setTimeout(i, a));
2017
+ }
2018
+ return "";
2019
+ })();
2020
+ this.discoveryPromise = e;
2021
+ try {
2022
+ return await this.discoveryPromise;
2023
+ } finally {
2024
+ this.discoveryPromise === e && (this.discoveryPromise = null);
2025
+ }
2026
+ }
2027
+ /**
2028
+ * Build API URL with discovered prefix
2029
+ */
2030
+ async buildUrl(e) {
2031
+ const t = await this.discoverPrefix(), n = e.startsWith("/") ? e : `/${e}`;
2032
+ return `${this.serverUrl}${t}${n}`;
2033
+ }
2034
+ /**
2035
+ * Reset cached prefix (useful for testing or reconnecting)
2036
+ */
2037
+ reset() {
2038
+ this.routePrefix = null, this.discoveryPromise = null;
2039
+ }
2040
+ }
2041
+ const K = /* @__PURE__ */ new Map();
2042
+ function Fe(r, e, t, n, a) {
2043
+ return JSON.stringify({
2044
+ stripePublicKey: r,
2045
+ serverUrl: e,
2046
+ solanaCluster: t,
2047
+ solanaEndpoint: n || "",
2048
+ dangerouslyAllowUnknownMint: a || !1
2049
+ });
2050
+ }
2051
+ function Nt(r, e, t, n, a) {
2052
+ const i = Fe(
2053
+ r,
2054
+ e,
2055
+ t,
2056
+ n,
2057
+ a
2058
+ );
2059
+ let o = K.get(i);
2060
+ if (o)
2061
+ return o.refCount++, c().debug(
2062
+ `[ManagerCache] Reusing cached managers (refCount: ${o.refCount}):`,
2063
+ { stripePublicKey: r.slice(0, 10) + "...", serverUrl: e }
2064
+ ), o;
2065
+ c().debug(
2066
+ "[ManagerCache] Creating new manager instances:",
2067
+ { stripePublicKey: r.slice(0, 10) + "...", serverUrl: e }
2068
+ );
2069
+ const s = new Ot(e), u = new lt(r, s), l = new bt(s), d = new Mt(
2070
+ t,
2071
+ n,
2072
+ a ?? !1
2073
+ ), f = new Dt(r, s), h = new Bt(s), A = new Ut(s);
2074
+ return o = {
2075
+ stripeManager: u,
2076
+ x402Manager: l,
2077
+ walletManager: d,
2078
+ subscriptionManager: f,
2079
+ subscriptionChangeManager: h,
2080
+ creditsManager: A,
2081
+ routeDiscovery: s,
2082
+ refCount: 1
2083
+ }, K.set(i, o), o;
2084
+ }
2085
+ function It(r, e, t, n, a) {
2086
+ const i = Fe(
2087
+ r,
2088
+ e,
2089
+ t,
2090
+ n,
2091
+ a
2092
+ ), o = K.get(i);
2093
+ if (!o) {
2094
+ c().warn("[ManagerCache] Attempted to release non-existent managers:", { cacheKey: i });
2095
+ return;
2096
+ }
2097
+ o.refCount--, c().debug(
2098
+ `[ManagerCache] Released manager reference (refCount: ${o.refCount}):`,
2099
+ { stripePublicKey: r.slice(0, 10) + "...", serverUrl: e }
2100
+ ), o.refCount <= 0 && (K.delete(i), c().debug("[ManagerCache] Removed managers from cache (refCount reached 0)"));
2101
+ }
2102
+ const Ft = [
2103
+ "stripePublicKey"
2104
+ ], Ae = /* @__PURE__ */ new Set(["mainnet-beta", "devnet", "testnet"]);
2105
+ function Lt() {
2106
+ if (typeof window < "u" && window.location)
2107
+ return window.location.origin;
2108
+ throw new Error(
2109
+ "serverUrl is required in SSR/Node environments. In browser environments, it defaults to window.location.origin"
2110
+ );
2111
+ }
2112
+ function jt(r) {
2113
+ const e = [];
2114
+ Ft.forEach((n) => {
2115
+ const a = r[n];
2116
+ (typeof a != "string" || a.trim().length === 0) && e.push({
2117
+ field: n,
2118
+ message: "must be a non-empty string"
2119
+ });
2120
+ });
2121
+ let t;
2122
+ if (r.serverUrl !== void 0)
2123
+ typeof r.serverUrl != "string" || r.serverUrl.trim().length === 0 ? (e.push({
2124
+ field: "serverUrl",
2125
+ message: "must be a non-empty string when provided"
2126
+ }), t = "") : t = r.serverUrl;
2127
+ else
2128
+ try {
2129
+ t = Lt();
2130
+ } catch (n) {
2131
+ e.push({
2132
+ field: "serverUrl",
2133
+ message: n instanceof Error ? n.message : "failed to determine default"
2134
+ }), t = "";
2135
+ }
2136
+ if (Ae.has(r.solanaCluster) || e.push({
2137
+ field: "solanaCluster",
2138
+ message: `must be one of ${Array.from(Ae).join(", ")}`
2139
+ }), r.solanaEndpoint !== void 0 && (typeof r.solanaEndpoint != "string" ? e.push({
2140
+ field: "solanaEndpoint",
2141
+ message: "must be a string when provided"
2142
+ }) : r.solanaEndpoint.trim().length === 0 ? e.push({
2143
+ field: "solanaEndpoint",
2144
+ message: 'must be a non-empty string when provided (e.g., "https://api.mainnet-beta.solana.com")'
2145
+ }) : !r.solanaEndpoint.startsWith("http://") && !r.solanaEndpoint.startsWith("https://") && e.push({
2146
+ field: "solanaEndpoint",
2147
+ message: 'must start with "http://" or "https://" (e.g., "https://api.mainnet-beta.solana.com")'
2148
+ })), r.tokenMint && typeof r.tokenMint != "string" && e.push({
2149
+ field: "tokenMint",
2150
+ message: "must be a string when provided"
2151
+ }), e.length > 0) {
2152
+ const n = e.map((a) => `- ${a.field} ${a.message}`).join(`
2153
+ `);
2154
+ throw new Error(`Invalid Cedros configuration:
2155
+ ${n}`);
2156
+ }
2157
+ if (r.tokenMint) {
2158
+ const n = r.dangerouslyAllowUnknownMint === !0, a = Ie(r.tokenMint, "CedrosConfig.tokenMint", n);
2159
+ if (!a.isValid && a.error)
2160
+ throw new Error(a.error);
2161
+ a.warning && c().warn(a.warning);
2162
+ }
2163
+ return {
2164
+ ...r,
2165
+ serverUrl: t
2166
+ };
2167
+ }
2168
+ class zt {
2169
+ adapters = null;
2170
+ poolId;
2171
+ isCleanedUp = !1;
2172
+ constructor(e) {
2173
+ this.poolId = e ?? `pool_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`, c().debug(`[WalletPool] Created pool: ${this.poolId}`);
2174
+ }
2175
+ /**
2176
+ * Get wallet adapters for this pool
2177
+ *
2178
+ * Lazy initialization: adapters are created on first access.
2179
+ * Returns empty array in SSR environments.
2180
+ */
2181
+ getAdapters() {
2182
+ return typeof window > "u" ? [] : this.isCleanedUp ? (c().warn(`[WalletPool] Attempted to use pool after cleanup: ${this.poolId}`), []) : this.adapters !== null ? this.adapters : (c().debug(`[WalletPool] Initializing adapters for pool: ${this.poolId}`), this.adapters = [
2183
+ new He(),
2184
+ new Ve()
2185
+ ], this.adapters);
2186
+ }
2187
+ /**
2188
+ * Cleanup wallet adapters
2189
+ *
2190
+ * Disconnects all wallets and clears the adapter cache.
2191
+ * Called automatically when CedrosProvider unmounts.
2192
+ *
2193
+ * IMPORTANT: After cleanup, getAdapters() will return empty array.
2194
+ */
2195
+ async cleanup() {
2196
+ if (this.isCleanedUp) {
2197
+ c().debug(`[WalletPool] Pool already cleaned up: ${this.poolId}`);
2198
+ return;
2199
+ }
2200
+ if (c().debug(`[WalletPool] Cleaning up pool: ${this.poolId}`), this.isCleanedUp = !0, this.adapters === null)
2201
+ return;
2202
+ const e = this.adapters.map(async (t) => {
2203
+ try {
2204
+ t.connected && (c().debug(`[WalletPool] Disconnecting wallet: ${t.name}`), await t.disconnect());
2205
+ } catch (n) {
2206
+ c().warn(`[WalletPool] Failed to disconnect wallet ${t.name}:`, n);
2207
+ }
2208
+ });
2209
+ await Promise.allSettled(e), this.adapters = null, c().debug(`[WalletPool] Pool cleanup complete: ${this.poolId}`);
2210
+ }
2211
+ /**
2212
+ * Check if this pool has been initialized
2213
+ *
2214
+ * Useful for testing or debugging.
2215
+ */
2216
+ isInitialized() {
2217
+ return this.adapters !== null;
2218
+ }
2219
+ /**
2220
+ * Get pool ID (for debugging/logging)
2221
+ */
2222
+ getId() {
2223
+ return this.poolId;
2224
+ }
2225
+ }
2226
+ function qt(r) {
2227
+ return new zt(r);
2228
+ }
2229
+ const Qt = Object.freeze({
2230
+ surfaceBackground: "rgba(255, 255, 255, 0)",
2231
+ surfaceText: "#111827",
2232
+ surfaceBorder: "rgba(15, 23, 42, 0.08)",
2233
+ stripeBackground: "linear-gradient(135deg, #635bff 0%, #4f46e5 100%)",
2234
+ stripeText: "#ffffff",
2235
+ stripeShadow: "rgba(79, 70, 229, 0.25)",
2236
+ cryptoBackground: "linear-gradient(135deg, #14f195 0%, #9945ff 100%)",
2237
+ cryptoText: "#ffffff",
2238
+ cryptoShadow: "rgba(99, 102, 241, 0.25)",
2239
+ errorBackground: "#fee2e2",
2240
+ errorBorder: "#fca5a5",
2241
+ errorText: "#b91c1c",
2242
+ successBackground: "#dcfce7",
2243
+ successBorder: "#86efac",
2244
+ successText: "#166534",
2245
+ modalOverlay: "rgba(0, 0, 0, 0.5)",
2246
+ modalBackground: "#ffffff",
2247
+ modalBorder: "rgba(15, 23, 42, 0.08)",
2248
+ buttonBorderRadius: "8px",
2249
+ buttonPadding: "0.75rem 1.5rem",
2250
+ buttonFontSize: "1rem",
2251
+ buttonFontWeight: "600"
2252
+ }), Wt = Object.freeze({
2253
+ surfaceBackground: "rgba(17, 24, 39, 0.6)",
2254
+ surfaceText: "#f9fafb",
2255
+ surfaceBorder: "rgba(148, 163, 184, 0.25)",
2256
+ stripeBackground: "linear-gradient(135deg, #4f46e5 0%, #3730a3 100%)",
2257
+ stripeText: "#f5f3ff",
2258
+ stripeShadow: "rgba(99, 102, 241, 0.35)",
2259
+ cryptoBackground: "linear-gradient(135deg, #1dd4a6 0%, #6d28d9 100%)",
2260
+ cryptoText: "#ecfeff",
2261
+ cryptoShadow: "rgba(75, 85, 99, 0.35)",
2262
+ errorBackground: "#7f1d1d",
2263
+ errorBorder: "#fca5a5",
2264
+ errorText: "#fecaca",
2265
+ successBackground: "#14532d",
2266
+ successBorder: "#4ade80",
2267
+ successText: "#bbf7d0",
2268
+ modalOverlay: "rgba(0, 0, 0, 0.75)",
2269
+ modalBackground: "#1f2937",
2270
+ modalBorder: "rgba(148, 163, 184, 0.25)",
2271
+ buttonBorderRadius: "8px",
2272
+ buttonPadding: "0.75rem 1.5rem",
2273
+ buttonFontSize: "1rem",
2274
+ buttonFontWeight: "600"
2275
+ }), Ht = {
2276
+ surfaceBackground: "--cedros-surface-bg",
2277
+ surfaceText: "--cedros-surface-text",
2278
+ surfaceBorder: "--cedros-surface-border",
2279
+ stripeBackground: "--cedros-stripe-bg",
2280
+ stripeText: "--cedros-stripe-text",
2281
+ stripeShadow: "--cedros-stripe-shadow",
2282
+ cryptoBackground: "--cedros-crypto-bg",
2283
+ cryptoText: "--cedros-crypto-text",
2284
+ cryptoShadow: "--cedros-crypto-shadow",
2285
+ errorBackground: "--cedros-error-bg",
2286
+ errorBorder: "--cedros-error-border",
2287
+ errorText: "--cedros-error-text",
2288
+ successBackground: "--cedros-success-bg",
2289
+ successBorder: "--cedros-success-border",
2290
+ successText: "--cedros-success-text",
2291
+ modalOverlay: "--cedros-modal-overlay",
2292
+ modalBackground: "--cedros-modal-bg",
2293
+ modalBorder: "--cedros-modal-border",
2294
+ buttonBorderRadius: "--cedros-button-radius",
2295
+ buttonPadding: "--cedros-button-padding",
2296
+ buttonFontSize: "--cedros-button-font-size",
2297
+ buttonFontWeight: "--cedros-button-font-weight"
2298
+ }, ie = ye(null);
2299
+ function Vt(r, e) {
2300
+ return {
2301
+ ...r === "dark" ? Wt : Qt,
2302
+ ...e
2303
+ };
2304
+ }
2305
+ function Gt(r) {
2306
+ const e = Object.entries(r).map(([t, n]) => [
2307
+ Ht[t],
2308
+ n
2309
+ ]);
2310
+ return Object.fromEntries(e);
2311
+ }
2312
+ function Kt({
2313
+ initialMode: r = "light",
2314
+ overrides: e,
2315
+ unstyled: t = !1,
2316
+ children: n
2317
+ }) {
2318
+ const [a, i] = Z(r), [o, s] = Z(e), u = we(e);
2319
+ L(() => {
2320
+ if (e === u.current)
2321
+ return;
2322
+ (!e || !u.current ? e !== u.current : Object.keys({ ...e, ...u.current }).some(
2323
+ (f) => e[f] !== u.current?.[f]
2324
+ )) && (u.current = e, s(e));
2325
+ }, [e]);
2326
+ const l = $(() => {
2327
+ const d = Vt(a, o), f = t ? {} : Gt(d), h = t ? "" : `cedros-theme-root cedros-theme cedros-theme--${a}`;
2328
+ return {
2329
+ mode: a,
2330
+ setMode: i,
2331
+ tokens: d,
2332
+ className: h,
2333
+ style: f,
2334
+ unstyled: t
2335
+ };
2336
+ }, [a, o, t]);
2337
+ return /* @__PURE__ */ X(ie.Provider, { value: l, children: n });
2338
+ }
2339
+ function nr() {
2340
+ const r = re(ie);
2341
+ if (!r)
2342
+ throw new Error("useCedrosTheme must be used within CedrosProvider");
2343
+ return r;
2344
+ }
2345
+ function ar() {
2346
+ return re(ie);
2347
+ }
2348
+ let J = !1, Y = !1;
2349
+ async function Jt() {
2350
+ if (J)
2351
+ return Y ? { available: !0 } : {
2352
+ available: !1,
2353
+ error: pe()
2354
+ };
2355
+ try {
2356
+ return await import("@solana/web3.js"), J = !0, Y = !0, { available: !0 };
2357
+ } catch {
2358
+ return J = !0, Y = !1, {
2359
+ available: !1,
2360
+ error: pe()
2361
+ };
2362
+ }
2363
+ }
2364
+ function pe() {
2365
+ return `Solana dependencies not installed. To use crypto payments, install them with:
2366
+
2367
+ npm install @solana/web3.js @solana/spl-token @solana/wallet-adapter-react @solana/wallet-adapter-react-ui @solana/wallet-adapter-wallets @solana/wallet-adapter-base
2368
+
2369
+ Or if you only need Stripe payments, hide the crypto button with:
2370
+ <CedrosPay showCrypto={false} />`;
2371
+ }
2372
+ function Yt() {
2373
+ return typeof process < "u" && process.env.NODE_ENV === "development" ? 0 : 2;
2374
+ }
2375
+ const Le = ye(null);
2376
+ function ir({ config: r, children: e }) {
2377
+ const t = $(() => jt(r), [r]), n = we(null);
2378
+ n.current === null && (n.current = qt());
2379
+ const [a, i] = Z(null);
2380
+ L(() => {
2381
+ let s = !1;
2382
+ return Jt().then((u) => {
2383
+ s || (u.available ? i(void 0) : i(u.error || "Solana dependencies not available"));
2384
+ }), () => {
2385
+ s = !0;
2386
+ };
2387
+ }, []), L(() => {
2388
+ const s = t.logLevel ?? Yt(), u = rt({
2389
+ level: s,
2390
+ prefix: "[CedrosPay]"
2391
+ });
2392
+ tt(u);
2393
+ }, [t.logLevel]), L(() => {
2394
+ const s = n.current;
2395
+ return () => {
2396
+ s && s.cleanup().catch((u) => {
2397
+ c().warn("[CedrosProvider] Wallet pool cleanup failed:", u);
2398
+ });
2399
+ };
2400
+ }, []), L(() => {
2401
+ const s = t.stripePublicKey, u = t.serverUrl ?? "", l = t.solanaCluster, d = t.solanaEndpoint, f = t.dangerouslyAllowUnknownMint;
2402
+ return () => {
2403
+ It(s, u, l, d, f);
2404
+ };
2405
+ }, [
2406
+ t.stripePublicKey,
2407
+ t.serverUrl,
2408
+ t.solanaCluster,
2409
+ t.solanaEndpoint,
2410
+ t.dangerouslyAllowUnknownMint
2411
+ ]);
2412
+ const o = $(() => {
2413
+ const { stripeManager: s, x402Manager: u, walletManager: l, subscriptionManager: d, subscriptionChangeManager: f, creditsManager: h } = Nt(
2414
+ t.stripePublicKey,
2415
+ t.serverUrl ?? "",
2416
+ t.solanaCluster,
2417
+ t.solanaEndpoint,
2418
+ t.dangerouslyAllowUnknownMint
2419
+ );
2420
+ return {
2421
+ config: t,
2422
+ stripeManager: s,
2423
+ x402Manager: u,
2424
+ walletManager: l,
2425
+ subscriptionManager: d,
2426
+ subscriptionChangeManager: f,
2427
+ creditsManager: h,
2428
+ walletPool: n.current,
2429
+ solanaError: a
2430
+ };
2431
+ }, [t, a]);
2432
+ return /* @__PURE__ */ X(Le.Provider, { value: o, children: /* @__PURE__ */ X(
2433
+ Kt,
2434
+ {
2435
+ initialMode: t.theme ?? "light",
2436
+ overrides: t.themeOverrides,
2437
+ unstyled: t.unstyled ?? !1,
2438
+ children: e
2439
+ }
2440
+ ) });
2441
+ }
2442
+ function or() {
2443
+ const r = re(Le);
2444
+ if (!r)
2445
+ throw new Error("useCedrosContext must be used within CedrosProvider");
2446
+ return r;
2447
+ }
2448
+ export {
2449
+ ir as C,
2450
+ te as K,
2451
+ _e as L,
2452
+ M as R,
2453
+ Tt as S,
2454
+ zt as W,
2455
+ nr as a,
2456
+ Ee as b,
2457
+ R as c,
2458
+ rt as d,
2459
+ Ie as e,
2460
+ k as f,
2461
+ c as g,
2462
+ he as h,
2463
+ y as i,
2464
+ ar as j,
2465
+ U as k,
2466
+ it as l,
2467
+ m,
2468
+ rr as n,
2469
+ b as o,
2470
+ qt as p,
2471
+ g as r,
2472
+ or as u,
2473
+ jt as v
2474
+ };