@cedros/pay-react 1.1.24 → 1.1.25

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 (127) hide show
  1. package/dist/{AISettingsSection-IXS1Wt_1.js → AISettingsSection-BvSSiK2G.js} +1 -1
  2. package/dist/{AISettingsSection-Dw0ZlxMf.mjs → AISettingsSection-Dg1kazTI.mjs} +2 -2
  3. package/dist/{AutosaveIndicator-BJsg_kFZ.mjs → AutosaveIndicator-BHfkV59p.mjs} +1 -1
  4. package/dist/{AutosaveIndicator-CY_YHM1D.js → AutosaveIndicator-D2l7U8R1.js} +1 -1
  5. package/dist/CedrosContext-C2RjHLaQ.js +6 -0
  6. package/dist/{CedrosContext-DQUbL8yP.mjs → CedrosContext-CY6zvjvJ.mjs} +768 -617
  7. package/dist/ComplianceSection-BSE2f3Wo.mjs +534 -0
  8. package/dist/ComplianceSection-D6ETKG6b.js +1 -0
  9. package/dist/{CryptoButton-D1BCZBk4.mjs → CryptoButton-BV9owVe2.mjs} +2 -2
  10. package/dist/{CryptoButton-C1AAOOfj.js → CryptoButton-DpiCnyXE.js} +1 -1
  11. package/dist/{FAQSection-BmgmzDN5.js → FAQSection-6nGI0FK9.js} +1 -1
  12. package/dist/{FAQSection-C78MnK4k.mjs → FAQSection-uZG5V3pJ.mjs} +1 -1
  13. package/dist/{MessagingSection-CWLZcg11.js → MessagingSection-DrXb578q.js} +1 -1
  14. package/dist/{MessagingSection-De3t8bSI.mjs → MessagingSection-M0lj5yo4.mjs} +2 -2
  15. package/dist/{OrdersSection-_xKVzjSZ.mjs → OrdersSection-DteItv_O.mjs} +6 -6
  16. package/dist/{OrdersSection-BKOxsZw0.js → OrdersSection-_-rIw6XW.js} +1 -1
  17. package/dist/{PaymentSettingsSection-KjU_dN_d.mjs → PaymentSettingsSection-CdtdLFTg.mjs} +1 -1
  18. package/dist/{PaymentSettingsSection-BTEn9Dxb.js → PaymentSettingsSection-enTbUI95.js} +1 -1
  19. package/dist/SettingsSection-DUTEd6uV.js +1 -0
  20. package/dist/{SettingsSection-8QHZB59k.mjs → SettingsSection-mcT4LEhO.mjs} +19 -13
  21. package/dist/{SingleCategorySettings--LK0TZW0.mjs → SingleCategorySettings-BvHBVfSe.mjs} +4 -4
  22. package/dist/{SingleCategorySettings-CRXTMTo5.js → SingleCategorySettings-D2LVM5mn.js} +1 -1
  23. package/dist/{StorefrontSection-CeCpr8hn.mjs → StorefrontSection-BqQ36JIS.mjs} +2 -2
  24. package/dist/{StorefrontSection-C9DzCmOf.js → StorefrontSection-Du7hV2Gc.js} +1 -1
  25. package/dist/{SubscriptionsSection-C2xk8ApF.mjs → SubscriptionsSection-BYiCBwKZ.mjs} +7 -7
  26. package/dist/{SubscriptionsSection-Dn5SY6S_.js → SubscriptionsSection-C4BRN1dP.js} +1 -1
  27. package/dist/Token22Section-0c22NM5G.js +1 -0
  28. package/dist/Token22Section-BHvOhz5d.mjs +2260 -0
  29. package/dist/{WalletManager-Bwk3rgr1.js → WalletManager-B3UdQ5pQ.js} +1 -1
  30. package/dist/{WalletManager-CXvQ0Zu9.mjs → WalletManager-BIwH8Dw_.mjs} +1 -1
  31. package/dist/{configApi-Ch0Rr7TD.mjs → configApi-6XhAJGKX.mjs} +31 -0
  32. package/dist/{configApi-CxEbCAgG.js → configApi-DkduMQg1.js} +1 -1
  33. package/dist/crypto-only.js +1 -1
  34. package/dist/crypto-only.mjs +85 -83
  35. package/dist/{index-BHF82XBB.mjs → index-BkDimQDF.mjs} +7987 -7322
  36. package/dist/index-C7MWL6O8.js +84 -0
  37. package/dist/index.js +1 -1
  38. package/dist/index.mjs +42 -40
  39. package/dist/{sections-8e5Y3ukY.js → sections-5jO2aHAo.js} +1 -1
  40. package/dist/{sections-C1rb9YRh.mjs → sections-By4H1baL.mjs} +2 -2
  41. package/dist/src/admin/plugin.d.ts.map +1 -1
  42. package/dist/src/components/ComplianceGatePage.d.ts +38 -0
  43. package/dist/src/components/ComplianceGatePage.d.ts.map +1 -0
  44. package/dist/src/components/SubscribeButton.d.ts +1 -5
  45. package/dist/src/components/SubscribeButton.d.ts.map +1 -1
  46. package/dist/src/components/admin/AdminAuthManager.d.ts +7 -3
  47. package/dist/src/components/admin/AdminAuthManager.d.ts.map +1 -1
  48. package/dist/src/components/admin/AssetClassesTab.d.ts.map +1 -1
  49. package/dist/src/components/admin/CedrosPayAdminDashboard.d.ts +1 -1
  50. package/dist/src/components/admin/CedrosPayAdminDashboard.d.ts.map +1 -1
  51. package/dist/src/components/admin/ComplianceSanctionsApi.d.ts +3 -0
  52. package/dist/src/components/admin/ComplianceSanctionsApi.d.ts.map +1 -0
  53. package/dist/src/components/admin/ComplianceSection.d.ts +3 -0
  54. package/dist/src/components/admin/ComplianceSection.d.ts.map +1 -0
  55. package/dist/src/components/admin/GiftCardAnalytics.d.ts +3 -0
  56. package/dist/src/components/admin/GiftCardAnalytics.d.ts.map +1 -0
  57. package/dist/src/components/admin/GiftCardManager.d.ts +3 -0
  58. package/dist/src/components/admin/GiftCardManager.d.ts.map +1 -0
  59. package/dist/src/components/admin/LiquidityPoolTab.d.ts.map +1 -1
  60. package/dist/src/components/admin/PoolManagementView.d.ts +14 -0
  61. package/dist/src/components/admin/PoolManagementView.d.ts.map +1 -0
  62. package/dist/src/components/admin/ProductsSection.d.ts.map +1 -1
  63. package/dist/src/components/admin/RefundsSection.d.ts.map +1 -1
  64. package/dist/src/components/admin/SettingsSection.d.ts.map +1 -1
  65. package/dist/src/components/admin/Token22Section.d.ts.map +1 -1
  66. package/dist/src/components/admin/complianceTypes.d.ts +60 -0
  67. package/dist/src/components/admin/complianceTypes.d.ts.map +1 -0
  68. package/dist/src/components/admin/configApi.d.ts.map +1 -1
  69. package/dist/src/components/admin/icons.d.ts +1 -0
  70. package/dist/src/components/admin/icons.d.ts.map +1 -1
  71. package/dist/src/components/admin/useAdminAuth.d.ts +1 -1
  72. package/dist/src/components/admin/useAdminAuth.d.ts.map +1 -1
  73. package/dist/src/context/CedrosContext.d.ts.map +1 -1
  74. package/dist/src/ecommerce/components/catalog/TokenDisplay.d.ts +36 -0
  75. package/dist/src/ecommerce/components/catalog/TokenDisplay.d.ts.map +1 -0
  76. package/dist/src/ecommerce/components/checkout/CheckoutForm.d.ts.map +1 -1
  77. package/dist/src/ecommerce/components/checkout/SendAsGiftSection.d.ts +15 -0
  78. package/dist/src/ecommerce/components/checkout/SendAsGiftSection.d.ts.map +1 -0
  79. package/dist/src/ecommerce/components/gift-cards/GiftCardBalanceChecker.d.ts +19 -0
  80. package/dist/src/ecommerce/components/gift-cards/GiftCardBalanceChecker.d.ts.map +1 -0
  81. package/dist/src/ecommerce/components/orders/MyRedemptionsPage.d.ts +13 -0
  82. package/dist/src/ecommerce/components/orders/MyRedemptionsPage.d.ts.map +1 -0
  83. package/dist/src/ecommerce/components/orders/MyTokensPage.d.ts +15 -0
  84. package/dist/src/ecommerce/components/orders/MyTokensPage.d.ts.map +1 -0
  85. package/dist/src/ecommerce/components/orders/OrderDetails.d.ts.map +1 -1
  86. package/dist/src/ecommerce/hooks/useCartInventory.d.ts.map +1 -1
  87. package/dist/src/ecommerce/index.d.ts +10 -0
  88. package/dist/src/ecommerce/index.d.ts.map +1 -1
  89. package/dist/src/ecommerce/state/checkout/checkoutSchema.d.ts +3 -0
  90. package/dist/src/ecommerce/state/checkout/checkoutSchema.d.ts.map +1 -1
  91. package/dist/src/ecommerce/state/checkout/useCheckout.d.ts.map +1 -1
  92. package/dist/src/ecommerce/types.d.ts +6 -0
  93. package/dist/src/ecommerce/types.d.ts.map +1 -1
  94. package/dist/src/ecommerce/utils/cartItemMetadata.d.ts.map +1 -1
  95. package/dist/src/hooks/useComplianceCheck.d.ts +30 -0
  96. package/dist/src/hooks/useComplianceCheck.d.ts.map +1 -0
  97. package/dist/src/hooks/useSubscriptionManagement.d.ts.map +1 -1
  98. package/dist/src/index.d.ts +4 -0
  99. package/dist/src/index.d.ts.map +1 -1
  100. package/dist/src/managers/CreditsManager.d.ts.map +1 -1
  101. package/dist/src/managers/ManagerCache.d.ts +2 -2
  102. package/dist/src/managers/ManagerCache.d.ts.map +1 -1
  103. package/dist/src/managers/StripeManager.d.ts +7 -1
  104. package/dist/src/managers/StripeManager.d.ts.map +1 -1
  105. package/dist/src/managers/SubscriptionChangeManager.d.ts.map +1 -1
  106. package/dist/src/managers/SubscriptionManager.d.ts.map +1 -1
  107. package/dist/src/types/index.d.ts +14 -0
  108. package/dist/src/types/index.d.ts.map +1 -1
  109. package/dist/src/types/subscription.d.ts +21 -33
  110. package/dist/src/types/subscription.d.ts.map +1 -1
  111. package/dist/src/utils/exponentialBackoff.d.ts +22 -0
  112. package/dist/src/utils/exponentialBackoff.d.ts.map +1 -1
  113. package/dist/stripe-only.js +1 -1
  114. package/dist/stripe-only.mjs +2 -2
  115. package/dist/styles-BT4bhFey.js +1 -0
  116. package/dist/{styles-Ag-7ZvAB.mjs → styles-D4SQkuV3.mjs} +606 -609
  117. package/dist/testing/index.js +1 -1
  118. package/dist/testing/index.mjs +1 -1
  119. package/dist/{walletPool-C_0P4mTw.mjs → walletPool-DE-t1wSW.mjs} +1 -1
  120. package/dist/{walletPool-Ddv33tej.js → walletPool-IS7R3MR1.js} +1 -1
  121. package/package.json +1 -1
  122. package/dist/CedrosContext-7dwmEeUY.js +0 -6
  123. package/dist/SettingsSection-cKF0tLnS.js +0 -1
  124. package/dist/Token22Section-DUUl59dZ.js +0 -1
  125. package/dist/Token22Section-HygkDNtL.mjs +0 -1685
  126. package/dist/index-OaWkrl0G.js +0 -84
  127. package/dist/styles-21F1-oqx.js +0 -1
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Wr=require("react/jsx-runtime"),Wu=require("../CedrosContext-7dwmEeUY.js");var xs={reset:[0,0],bold:[1,22,"\x1B[22m\x1B[1m"],dim:[2,22,"\x1B[22m\x1B[2m"],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]};function yo(e){return String(e)}yo.open="";yo.close="";function Vu(){let e=typeof process<"u"?process:void 0,t=e?.env||{},n=t.FORCE_TTY!=="false",r=e?.argv||[];return!("NO_COLOR"in t||r.includes("--no-color"))&&("FORCE_COLOR"in t||r.includes("--color")||e?.platform==="win32"||n&&t.TERM!=="dumb"||"CI"in t)||typeof window<"u"&&!!window.chrome}function Uu(){let e=Vu(),t=(s,i,a,u)=>{let c="",l=0;do c+=s.substring(l,u)+a,l=u+i.length,u=s.indexOf(i,l);while(~u);return c+s.substring(l)},n=(s,i,a=s)=>{let u=c=>{let l=String(c),f=l.indexOf(i,s.length);return~f?s+t(l,i,a,f)+i:s+l+i};return u.open=s,u.close=i,u},r={isColorSupported:e},o=s=>`\x1B[${s}m`;for(let s in xs){let i=xs[s];r[s]=e?n(o(i[0]),o(i[1]),i[2]):yo}return r}var ce=Uu();function Pc(e,t){return t.forEach(function(n){n&&typeof n!="string"&&!Array.isArray(n)&&Object.keys(n).forEach(function(r){if(r!=="default"&&!(r in e)){var o=Object.getOwnPropertyDescriptor(n,r);Object.defineProperty(e,r,o.get?o:{enumerable:!0,get:function(){return n[r]}})}})}),Object.freeze(e)}function Ku(e,t){const n=Object.keys(e),r=t===null?n:n.sort(t);if(Object.getOwnPropertySymbols)for(const o of Object.getOwnPropertySymbols(e))Object.getOwnPropertyDescriptor(e,o).enumerable&&r.push(o);return r}function rn(e,t,n,r,o,s,i=": "){let a="",u=0,c=e.next();if(!c.done){a+=t.spacingOuter;const l=n+t.indent;for(;!c.done;){if(a+=l,u++===t.maxWidth){a+="…";break}const f=s(c.value[0],t,l,r,o),h=s(c.value[1],t,l,r,o);a+=f+i+h,c=e.next(),c.done?t.min||(a+=","):a+=`,${t.spacingInner}`}a+=t.spacingOuter+n}return a}function bo(e,t,n,r,o,s){let i="",a=0,u=e.next();if(!u.done){i+=t.spacingOuter;const c=n+t.indent;for(;!u.done;){if(i+=c,a++===t.maxWidth){i+="…";break}i+=s(u.value,t,c,r,o),u=e.next(),u.done?t.min||(i+=","):i+=`,${t.spacingInner}`}i+=t.spacingOuter+n}return i}function $n(e,t,n,r,o,s){let i="";e=e instanceof ArrayBuffer?new DataView(e):e;const a=c=>c instanceof DataView,u=a(e)?e.byteLength:e.length;if(u>0){i+=t.spacingOuter;const c=n+t.indent;for(let l=0;l<u;l++){if(i+=c,l===t.maxWidth){i+="…";break}(a(e)||l in e)&&(i+=s(a(e)?e.getInt8(l):e[l],t,c,r,o)),l<u-1?i+=`,${t.spacingInner}`:t.min||(i+=",")}i+=t.spacingOuter+n}return i}function wo(e,t,n,r,o,s){let i="";const a=Ku(e,t.compareKeys);if(a.length>0){i+=t.spacingOuter;const u=n+t.indent;for(let c=0;c<a.length;c++){const l=a[c],f=s(l,t,u,r,o),h=s(e[l],t,u,r,o);i+=`${u+f}: ${h}`,c<a.length-1?i+=`,${t.spacingInner}`:t.min||(i+=",")}i+=t.spacingOuter+n}return i}const Gu=typeof Symbol=="function"&&Symbol.for?Symbol.for("jest.asymmetricMatcher"):1267621,fn=" ",Yu=(e,t,n,r,o,s)=>{const i=e.toString();if(i==="ArrayContaining"||i==="ArrayNotContaining")return++r>t.maxDepth?`[${i}]`:`${i+fn}[${$n(e.sample,t,n,r,o,s)}]`;if(i==="ObjectContaining"||i==="ObjectNotContaining")return++r>t.maxDepth?`[${i}]`:`${i+fn}{${wo(e.sample,t,n,r,o,s)}}`;if(i==="StringMatching"||i==="StringNotMatching"||i==="StringContaining"||i==="StringNotContaining")return i+fn+s(e.sample,t,n,r,o);if(typeof e.toAsymmetricMatcher!="function")throw new TypeError(`Asymmetric matcher ${e.constructor.name} does not implement toAsymmetricMatcher()`);return e.toAsymmetricMatcher()},Ju=e=>e&&e.$$typeof===Gu,Xu={serialize:Yu,test:Ju},Hu=" ",Ic=new Set(["DOMStringMap","NamedNodeMap"]),Zu=/^(?:HTML\w*Collection|NodeList)$/;function Qu(e){return Ic.has(e)||Zu.test(e)}const el=e=>e&&e.constructor&&!!e.constructor.name&&Qu(e.constructor.name);function tl(e){return e.constructor.name==="NamedNodeMap"}const nl=(e,t,n,r,o,s)=>{const i=e.constructor.name;return++r>t.maxDepth?`[${i}]`:(t.min?"":i+Hu)+(Ic.has(i)?`{${wo(tl(e)?[...e].reduce((a,u)=>(a[u.name]=u.value,a),{}):{...e},t,n,r,o,s)}}`:`[${$n([...e],t,n,r,o,s)}]`)},rl={serialize:nl,test:el};function Nc(e){return e.replaceAll("<","&lt;").replaceAll(">","&gt;")}function To(e,t,n,r,o,s,i){const a=r+n.indent,u=n.colors;return e.map(c=>{const l=t[c];let f=i(l,n,a,o,s);return typeof l!="string"&&(f.includes(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Wr=require("react/jsx-runtime"),Wu=require("../CedrosContext-C2RjHLaQ.js");var xs={reset:[0,0],bold:[1,22,"\x1B[22m\x1B[1m"],dim:[2,22,"\x1B[22m\x1B[2m"],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]};function yo(e){return String(e)}yo.open="";yo.close="";function Vu(){let e=typeof process<"u"?process:void 0,t=e?.env||{},n=t.FORCE_TTY!=="false",r=e?.argv||[];return!("NO_COLOR"in t||r.includes("--no-color"))&&("FORCE_COLOR"in t||r.includes("--color")||e?.platform==="win32"||n&&t.TERM!=="dumb"||"CI"in t)||typeof window<"u"&&!!window.chrome}function Uu(){let e=Vu(),t=(s,i,a,u)=>{let c="",l=0;do c+=s.substring(l,u)+a,l=u+i.length,u=s.indexOf(i,l);while(~u);return c+s.substring(l)},n=(s,i,a=s)=>{let u=c=>{let l=String(c),f=l.indexOf(i,s.length);return~f?s+t(l,i,a,f)+i:s+l+i};return u.open=s,u.close=i,u},r={isColorSupported:e},o=s=>`\x1B[${s}m`;for(let s in xs){let i=xs[s];r[s]=e?n(o(i[0]),o(i[1]),i[2]):yo}return r}var ce=Uu();function Pc(e,t){return t.forEach(function(n){n&&typeof n!="string"&&!Array.isArray(n)&&Object.keys(n).forEach(function(r){if(r!=="default"&&!(r in e)){var o=Object.getOwnPropertyDescriptor(n,r);Object.defineProperty(e,r,o.get?o:{enumerable:!0,get:function(){return n[r]}})}})}),Object.freeze(e)}function Ku(e,t){const n=Object.keys(e),r=t===null?n:n.sort(t);if(Object.getOwnPropertySymbols)for(const o of Object.getOwnPropertySymbols(e))Object.getOwnPropertyDescriptor(e,o).enumerable&&r.push(o);return r}function rn(e,t,n,r,o,s,i=": "){let a="",u=0,c=e.next();if(!c.done){a+=t.spacingOuter;const l=n+t.indent;for(;!c.done;){if(a+=l,u++===t.maxWidth){a+="…";break}const f=s(c.value[0],t,l,r,o),h=s(c.value[1],t,l,r,o);a+=f+i+h,c=e.next(),c.done?t.min||(a+=","):a+=`,${t.spacingInner}`}a+=t.spacingOuter+n}return a}function bo(e,t,n,r,o,s){let i="",a=0,u=e.next();if(!u.done){i+=t.spacingOuter;const c=n+t.indent;for(;!u.done;){if(i+=c,a++===t.maxWidth){i+="…";break}i+=s(u.value,t,c,r,o),u=e.next(),u.done?t.min||(i+=","):i+=`,${t.spacingInner}`}i+=t.spacingOuter+n}return i}function $n(e,t,n,r,o,s){let i="";e=e instanceof ArrayBuffer?new DataView(e):e;const a=c=>c instanceof DataView,u=a(e)?e.byteLength:e.length;if(u>0){i+=t.spacingOuter;const c=n+t.indent;for(let l=0;l<u;l++){if(i+=c,l===t.maxWidth){i+="…";break}(a(e)||l in e)&&(i+=s(a(e)?e.getInt8(l):e[l],t,c,r,o)),l<u-1?i+=`,${t.spacingInner}`:t.min||(i+=",")}i+=t.spacingOuter+n}return i}function wo(e,t,n,r,o,s){let i="";const a=Ku(e,t.compareKeys);if(a.length>0){i+=t.spacingOuter;const u=n+t.indent;for(let c=0;c<a.length;c++){const l=a[c],f=s(l,t,u,r,o),h=s(e[l],t,u,r,o);i+=`${u+f}: ${h}`,c<a.length-1?i+=`,${t.spacingInner}`:t.min||(i+=",")}i+=t.spacingOuter+n}return i}const Gu=typeof Symbol=="function"&&Symbol.for?Symbol.for("jest.asymmetricMatcher"):1267621,fn=" ",Yu=(e,t,n,r,o,s)=>{const i=e.toString();if(i==="ArrayContaining"||i==="ArrayNotContaining")return++r>t.maxDepth?`[${i}]`:`${i+fn}[${$n(e.sample,t,n,r,o,s)}]`;if(i==="ObjectContaining"||i==="ObjectNotContaining")return++r>t.maxDepth?`[${i}]`:`${i+fn}{${wo(e.sample,t,n,r,o,s)}}`;if(i==="StringMatching"||i==="StringNotMatching"||i==="StringContaining"||i==="StringNotContaining")return i+fn+s(e.sample,t,n,r,o);if(typeof e.toAsymmetricMatcher!="function")throw new TypeError(`Asymmetric matcher ${e.constructor.name} does not implement toAsymmetricMatcher()`);return e.toAsymmetricMatcher()},Ju=e=>e&&e.$$typeof===Gu,Xu={serialize:Yu,test:Ju},Hu=" ",Ic=new Set(["DOMStringMap","NamedNodeMap"]),Zu=/^(?:HTML\w*Collection|NodeList)$/;function Qu(e){return Ic.has(e)||Zu.test(e)}const el=e=>e&&e.constructor&&!!e.constructor.name&&Qu(e.constructor.name);function tl(e){return e.constructor.name==="NamedNodeMap"}const nl=(e,t,n,r,o,s)=>{const i=e.constructor.name;return++r>t.maxDepth?`[${i}]`:(t.min?"":i+Hu)+(Ic.has(i)?`{${wo(tl(e)?[...e].reduce((a,u)=>(a[u.name]=u.value,a),{}):{...e},t,n,r,o,s)}}`:`[${$n([...e],t,n,r,o,s)}]`)},rl={serialize:nl,test:el};function Nc(e){return e.replaceAll("<","&lt;").replaceAll(">","&gt;")}function To(e,t,n,r,o,s,i){const a=r+n.indent,u=n.colors;return e.map(c=>{const l=t[c];let f=i(l,n,a,o,s);return typeof l!="string"&&(f.includes(`
2
2
  `)&&(f=n.spacingOuter+a+f+n.spacingOuter+r),f=`{${f}}`),`${n.spacingInner+r+u.prop.open+c+u.prop.close}=${u.value.open}${f}${u.value.close}`}).join("")}function Rn(e,t,n,r,o,s){return e.map(i=>t.spacingOuter+n+(typeof i=="string"?jc(i,t):s(i,t,n,r,o))).join("")}function ol(e,t,n,r,o,s){return t.printShadowRoot===!1?"":[`${t.spacingOuter+n}#shadow-root`,Rn(e,t,n+t.indent,r,o,s)].join("")}function jc(e,t){const n=t.colors.content;return n.open+Nc(e)+n.close}function sl(e,t){const n=t.colors.comment;return`${n.open}<!--${Nc(e)}-->${n.close}`}function So(e,t,n,r,o){const s=r.colors.tag;return`${s.open}<${e}${t&&s.close+t+r.spacingOuter+o+s.open}${n?`>${s.close}${n}${r.spacingOuter}${o}${s.open}</${e}`:`${t&&!r.min?"":" "}/`}>${s.close}`}function Eo(e,t){const n=t.colors.tag;return`${n.open}<${e}${n.close} …${n.open} />${n.close}`}const il=1,Rc=3,Fc=8,Dc=11,cl=/^(?:(?:HTML|SVG)\w*)?Element$/;function al(e){try{return typeof e.hasAttribute=="function"&&e.hasAttribute("is")}catch{return!1}}function ul(e){const t=e.constructor.name,{nodeType:n,tagName:r}=e,o=typeof r=="string"&&r.includes("-")||al(e);return n===il&&(cl.test(t)||o)||n===Rc&&t==="Text"||n===Fc&&t==="Comment"||n===Dc&&t==="DocumentFragment"}const ll=e=>e?.constructor?.name&&ul(e);function fl(e){return e.nodeType===Rc}function hl(e){return e.nodeType===Fc}function hn(e){return e.nodeType===Dc}const pl=(e,t,n,r,o,s)=>{if(fl(e))return jc(e.data,t);if(hl(e))return sl(e.data,t);const i=hn(e)?"DocumentFragment":e.tagName.toLowerCase();return++r>t.maxDepth?Eo(i,t):So(i,To(hn(e)?[]:Array.from(e.attributes,a=>a.name).sort(),hn(e)?{}:[...e.attributes].reduce((a,u)=>(a[u.name]=u.value,a),{}),t,n+t.indent,r,o,s),(hn(e)||!e.shadowRoot?"":ol(Array.prototype.slice.call(e.shadowRoot.children),t,n+t.indent,r,o,s))+Rn(Array.prototype.slice.call(e.childNodes||e.children),t,n+t.indent,r,o,s),t,n)},dl={serialize:pl,test:ll},ml="@@__IMMUTABLE_ITERABLE__@@",gl="@@__IMMUTABLE_LIST__@@",yl="@@__IMMUTABLE_KEYED__@@",bl="@@__IMMUTABLE_MAP__@@",Ms="@@__IMMUTABLE_ORDERED__@@",wl="@@__IMMUTABLE_RECORD__@@",Tl="@@__IMMUTABLE_SEQ__@@",Sl="@@__IMMUTABLE_SET__@@",El="@@__IMMUTABLE_STACK__@@",At=e=>`Immutable.${e}`,Fn=e=>`[${e}]`,Qt=" ",_s="…";function vl(e,t,n,r,o,s,i){return++r>t.maxDepth?Fn(At(i)):`${At(i)+Qt}{${rn(e.entries(),t,n,r,o,s)}}`}function $l(e){let t=0;return{next(){if(t<e._keys.length){const n=e._keys[t++];return{done:!1,value:[n,e.get(n)]}}return{done:!0,value:void 0}}}}function xl(e,t,n,r,o,s){const i=At(e._name||"Record");return++r>t.maxDepth?Fn(i):`${i+Qt}{${rn($l(e),t,n,r,o,s)}}`}function Ml(e,t,n,r,o,s){const i=At("Seq");return++r>t.maxDepth?Fn(i):e[yl]?`${i+Qt}{${e._iter||e._object?rn(e.entries(),t,n,r,o,s):_s}}`:`${i+Qt}[${e._iter||e._array||e._collection||e._iterable?bo(e.values(),t,n,r,o,s):_s}]`}function sr(e,t,n,r,o,s,i){return++r>t.maxDepth?Fn(At(i)):`${At(i)+Qt}[${bo(e.values(),t,n,r,o,s)}]`}const _l=(e,t,n,r,o,s)=>e[bl]?vl(e,t,n,r,o,s,e[Ms]?"OrderedMap":"Map"):e[gl]?sr(e,t,n,r,o,s,"List"):e[Sl]?sr(e,t,n,r,o,s,e[Ms]?"OrderedSet":"Set"):e[El]?sr(e,t,n,r,o,s,"Stack"):e[Tl]?Ml(e,t,n,r,o,s):xl(e,t,n,r,o,s),Ol=e=>e&&(e[ml]===!0||e[wl]===!0),kl={serialize:_l,test:Ol};function Lc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ir={exports:{}},Z={};var Os;function Al(){if(Os)return Z;Os=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),s=Symbol.for("react.consumer"),i=Symbol.for("react.context"),a=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),c=Symbol.for("react.suspense_list"),l=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),h=Symbol.for("react.view_transition"),p=Symbol.for("react.client.reference");function d(g){if(typeof g=="object"&&g!==null){var w=g.$$typeof;switch(w){case e:switch(g=g.type,g){case n:case o:case r:case u:case c:case h:return g;default:switch(g=g&&g.$$typeof,g){case i:case a:case f:case l:return g;case s:return g;default:return w}}case t:return w}}}return Z.ContextConsumer=s,Z.ContextProvider=i,Z.Element=e,Z.ForwardRef=a,Z.Fragment=n,Z.Lazy=f,Z.Memo=l,Z.Portal=t,Z.Profiler=o,Z.StrictMode=r,Z.Suspense=u,Z.SuspenseList=c,Z.isContextConsumer=function(g){return d(g)===s},Z.isContextProvider=function(g){return d(g)===i},Z.isElement=function(g){return typeof g=="object"&&g!==null&&g.$$typeof===e},Z.isForwardRef=function(g){return d(g)===a},Z.isFragment=function(g){return d(g)===n},Z.isLazy=function(g){return d(g)===f},Z.isMemo=function(g){return d(g)===l},Z.isPortal=function(g){return d(g)===t},Z.isProfiler=function(g){return d(g)===o},Z.isStrictMode=function(g){return d(g)===r},Z.isSuspense=function(g){return d(g)===u},Z.isSuspenseList=function(g){return d(g)===c},Z.isValidElementType=function(g){return typeof g=="string"||typeof g=="function"||g===n||g===o||g===r||g===u||g===c||typeof g=="object"&&g!==null&&(g.$$typeof===f||g.$$typeof===l||g.$$typeof===i||g.$$typeof===s||g.$$typeof===a||g.$$typeof===p||g.getModuleId!==void 0)},Z.typeOf=d,Z}var ks;function Cl(){return ks||(ks=1,ir.exports=Al()),ir.exports}var qc=Cl(),Pl=Lc(qc),Il=Pc({__proto__:null,default:Pl},[qc]),cr={exports:{}},J={};var As;function Nl(){if(As)return J;As=1;var e=Symbol.for("react.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),s=Symbol.for("react.provider"),i=Symbol.for("react.context"),a=Symbol.for("react.server_context"),u=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),l=Symbol.for("react.suspense_list"),f=Symbol.for("react.memo"),h=Symbol.for("react.lazy"),p=Symbol.for("react.offscreen"),d;d=Symbol.for("react.module.reference");function g(w){if(typeof w=="object"&&w!==null){var T=w.$$typeof;switch(T){case e:switch(w=w.type,w){case n:case o:case r:case c:case l:return w;default:switch(w=w&&w.$$typeof,w){case a:case i:case u:case h:case f:case s:return w;default:return T}}case t:return T}}}return J.ContextConsumer=i,J.ContextProvider=s,J.Element=e,J.ForwardRef=u,J.Fragment=n,J.Lazy=h,J.Memo=f,J.Portal=t,J.Profiler=o,J.StrictMode=r,J.Suspense=c,J.SuspenseList=l,J.isAsyncMode=function(){return!1},J.isConcurrentMode=function(){return!1},J.isContextConsumer=function(w){return g(w)===i},J.isContextProvider=function(w){return g(w)===s},J.isElement=function(w){return typeof w=="object"&&w!==null&&w.$$typeof===e},J.isForwardRef=function(w){return g(w)===u},J.isFragment=function(w){return g(w)===n},J.isLazy=function(w){return g(w)===h},J.isMemo=function(w){return g(w)===f},J.isPortal=function(w){return g(w)===t},J.isProfiler=function(w){return g(w)===o},J.isStrictMode=function(w){return g(w)===r},J.isSuspense=function(w){return g(w)===c},J.isSuspenseList=function(w){return g(w)===l},J.isValidElementType=function(w){return typeof w=="string"||typeof w=="function"||w===n||w===o||w===r||w===c||w===l||w===p||typeof w=="object"&&w!==null&&(w.$$typeof===h||w.$$typeof===f||w.$$typeof===s||w.$$typeof===i||w.$$typeof===u||w.$$typeof===d||w.getModuleId!==void 0)},J.typeOf=g,J}var Cs;function jl(){return Cs||(Cs=1,cr.exports=Nl()),cr.exports}var Bc=jl(),Rl=Lc(Bc),Fl=Pc({__proto__:null,default:Rl},[Bc]);const Dl=["isAsyncMode","isConcurrentMode","isContextConsumer","isContextProvider","isElement","isForwardRef","isFragment","isLazy","isMemo","isPortal","isProfiler","isStrictMode","isSuspense","isSuspenseList","isValidElementType"],ut=Object.fromEntries(Dl.map(e=>[e,t=>Fl[e](t)||Il[e](t)]));function zc(e,t=[]){if(Array.isArray(e))for(const n of e)zc(n,t);else e!=null&&e!==!1&&e!==""&&t.push(e);return t}function Ps(e){const t=e.type;if(typeof t=="string")return t;if(typeof t=="function")return t.displayName||t.name||"Unknown";if(ut.isFragment(e))return"React.Fragment";if(ut.isSuspense(e))return"React.Suspense";if(typeof t=="object"&&t!==null){if(ut.isContextProvider(e))return"Context.Provider";if(ut.isContextConsumer(e))return"Context.Consumer";if(ut.isForwardRef(e)){if(t.displayName)return t.displayName;const n=t.render.displayName||t.render.name||"";return n===""?"ForwardRef":`ForwardRef(${n})`}if(ut.isMemo(e)){const n=t.displayName||t.type.displayName||t.type.name||"";return n===""?"Memo":`Memo(${n})`}}return"UNDEFINED"}function Ll(e){const{props:t}=e;return Object.keys(t).filter(n=>n!=="children"&&t[n]!==void 0).sort()}const ql=(e,t,n,r,o,s)=>++r>t.maxDepth?Eo(Ps(e),t):So(Ps(e),To(Ll(e),e.props,t,n+t.indent,r,o,s),Rn(zc(e.props.children),t,n+t.indent,r,o,s),t,n),Bl=e=>e!=null&&ut.isElement(e),zl={serialize:ql,test:Bl},Wl=typeof Symbol=="function"&&Symbol.for?Symbol.for("react.test.json"):245830487;function Vl(e){const{props:t}=e;return t?Object.keys(t).filter(n=>t[n]!==void 0).sort():[]}const Ul=(e,t,n,r,o,s)=>++r>t.maxDepth?Eo(e.type,t):So(e.type,e.props?To(Vl(e),e.props,t,n+t.indent,r,o,s):"",e.children?Rn(e.children,t,n+t.indent,r,o,s):"",t,n),Kl=e=>e&&e.$$typeof===Wl,Gl={serialize:Ul,test:Kl},Wc=Object.prototype.toString,Yl=Date.prototype.toISOString,Jl=Error.prototype.toString,Is=RegExp.prototype.toString;function bn(e){return typeof e.constructor=="function"&&e.constructor.name||"Object"}function Xl(e){return typeof window<"u"&&e===window}const Hl=/^Symbol\((.*)\)(.*)$/,Zl=/\n/g;class Vc extends Error{constructor(t,n){super(t),this.stack=n,this.name=this.constructor.name}}function Ql(e){return e==="[object Array]"||e==="[object ArrayBuffer]"||e==="[object DataView]"||e==="[object Float32Array]"||e==="[object Float64Array]"||e==="[object Int8Array]"||e==="[object Int16Array]"||e==="[object Int32Array]"||e==="[object Uint8Array]"||e==="[object Uint8ClampedArray]"||e==="[object Uint16Array]"||e==="[object Uint32Array]"}function ef(e){return Object.is(e,-0)?"-0":String(e)}function tf(e){return`${e}n`}function Ns(e,t){return t?`[Function ${e.name||"anonymous"}]`:"[Function]"}function js(e){return String(e).replace(Hl,"Symbol($1)")}function Rs(e){return`[${Jl.call(e)}]`}function Uc(e,t,n,r){if(e===!0||e===!1)return`${e}`;if(e===void 0)return"undefined";if(e===null)return"null";const o=typeof e;if(o==="number")return ef(e);if(o==="bigint")return tf(e);if(o==="string")return r?`"${e.replaceAll(/"|\\/g,"\\$&")}"`:`"${e}"`;if(o==="function")return Ns(e,t);if(o==="symbol")return js(e);const s=Wc.call(e);return s==="[object WeakMap]"?"WeakMap {}":s==="[object WeakSet]"?"WeakSet {}":s==="[object Function]"||s==="[object GeneratorFunction]"?Ns(e,t):s==="[object Symbol]"?js(e):s==="[object Date]"?Number.isNaN(+e)?"Date { NaN }":Yl.call(e):s==="[object Error]"?Rs(e):s==="[object RegExp]"?n?Is.call(e).replaceAll(/[$()*+.?[\\\]^{|}]/g,"\\$&"):Is.call(e):e instanceof Error?Rs(e):null}function Kc(e,t,n,r,o,s){if(o.includes(e))return"[Circular]";o=[...o],o.push(e);const i=++r>t.maxDepth,a=t.min;if(t.callToJSON&&!i&&e.toJSON&&typeof e.toJSON=="function"&&!s)return tt(e.toJSON(),t,n,r,o,!0);const u=Wc.call(e);return u==="[object Arguments]"?i?"[Arguments]":`${a?"":"Arguments "}[${$n(e,t,n,r,o,tt)}]`:Ql(u)?i?`[${e.constructor.name}]`:`${a||!t.printBasicPrototype&&e.constructor.name==="Array"?"":`${e.constructor.name} `}[${$n(e,t,n,r,o,tt)}]`:u==="[object Map]"?i?"[Map]":`Map {${rn(e.entries(),t,n,r,o,tt," => ")}}`:u==="[object Set]"?i?"[Set]":`Set {${bo(e.values(),t,n,r,o,tt)}}`:i||Xl(e)?`[${bn(e)}]`:`${a||!t.printBasicPrototype&&bn(e)==="Object"?"":`${bn(e)} `}{${wo(e,t,n,r,o,tt)}}`}const nf={test:e=>e&&e instanceof Error,serialize(e,t,n,r,o,s){if(o.includes(e))return"[Circular]";o=[...o,e];const i=++r>t.maxDepth,{message:a,cause:u,...c}=e,l={message:a,...typeof u<"u"?{cause:u}:{},...e instanceof AggregateError?{errors:e.errors}:{},...c},f=e.name!=="Error"?e.name:bn(e);return i?`[${f}]`:`${f} {${rn(Object.entries(l).values(),t,n,r,o,s)}}`}};function rf(e){return e.serialize!=null}function Gc(e,t,n,r,o,s){let i;try{i=rf(e)?e.serialize(t,n,r,o,s,tt):e.print(t,a=>tt(a,n,r,o,s),a=>{const u=r+n.indent;return u+a.replaceAll(Zl,`
3
3
  ${u}`)},{edgeSpacing:n.spacingOuter,min:n.min,spacing:n.spacingInner},n.colors)}catch(a){throw new Vc(a.message,a.stack)}if(typeof i!="string")throw new TypeError(`pretty-format: Plugin must return type "string" but instead returned "${typeof i}".`);return i}function Yc(e,t){for(const n of e)try{if(n.test(t))return n}catch(r){throw new Vc(r.message,r.stack)}return null}function tt(e,t,n,r,o,s){const i=Yc(t.plugins,e);if(i!==null)return Gc(i,e,t,n,r,o);const a=Uc(e,t.printFunctionName,t.escapeRegex,t.escapeString);return a!==null?a:Kc(e,t,n,r,o,s)}const vo={comment:"gray",content:"reset",prop:"yellow",tag:"cyan",value:"green"},Jc=Object.keys(vo),Fe={callToJSON:!0,compareKeys:void 0,escapeRegex:!1,escapeString:!0,highlight:!1,indent:2,maxDepth:Number.POSITIVE_INFINITY,maxWidth:Number.POSITIVE_INFINITY,min:!1,plugins:[],printBasicPrototype:!0,printFunctionName:!0,printShadowRoot:!0,theme:vo};function of(e){for(const t of Object.keys(e))if(!Object.hasOwn(Fe,t))throw new Error(`pretty-format: Unknown option "${t}".`);if(e.min&&e.indent!==void 0&&e.indent!==0)throw new Error('pretty-format: Options "min" and "indent" cannot be used together.')}function sf(){return Jc.reduce((e,t)=>{const n=vo[t],r=n&&ce[n];if(r&&typeof r.close=="string"&&typeof r.open=="string")e[t]=r;else throw new Error(`pretty-format: Option "theme" has a key "${t}" whose value "${n}" is undefined in ansi-styles.`);return e},Object.create(null))}function cf(){return Jc.reduce((e,t)=>(e[t]={close:"",open:""},e),Object.create(null))}function Xc(e){return e?.printFunctionName??Fe.printFunctionName}function Hc(e){return e?.escapeRegex??Fe.escapeRegex}function Zc(e){return e?.escapeString??Fe.escapeString}function Fs(e){return{callToJSON:e?.callToJSON??Fe.callToJSON,colors:e?.highlight?sf():cf(),compareKeys:typeof e?.compareKeys=="function"||e?.compareKeys===null?e.compareKeys:Fe.compareKeys,escapeRegex:Hc(e),escapeString:Zc(e),indent:e?.min?"":af(e?.indent??Fe.indent),maxDepth:e?.maxDepth??Fe.maxDepth,maxWidth:e?.maxWidth??Fe.maxWidth,min:e?.min??Fe.min,plugins:e?.plugins??Fe.plugins,printBasicPrototype:e?.printBasicPrototype??!0,printFunctionName:Xc(e),printShadowRoot:e?.printShadowRoot??!0,spacingInner:e?.min?" ":`
4
4
  `,spacingOuter:e?.min?"":`
@@ -1,5 +1,5 @@
1
1
  import { jsx as Cc, Fragment as zu } from "react/jsx-runtime";
2
- import { a as Wu } from "../CedrosContext-DQUbL8yP.mjs";
2
+ import { a as Wu } from "../CedrosContext-CY6zvjvJ.mjs";
3
3
  var $s = {
4
4
  reset: [0, 0],
5
5
  bold: [1, 22, "\x1B[22m\x1B[1m"],
@@ -1,5 +1,5 @@
1
1
  import { PhantomWalletAdapter as n, SolflareWalletAdapter as i } from "@solana/wallet-adapter-wallets";
2
- import { i as e } from "./CedrosContext-DQUbL8yP.mjs";
2
+ import { i as e } from "./CedrosContext-CY6zvjvJ.mjs";
3
3
  class r {
4
4
  adapters = null;
5
5
  poolId;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("@solana/wallet-adapter-wallets"),e=require("./CedrosContext-7dwmEeUY.js");class r{adapters=null;poolId;isCleanedUp=!1;constructor(l){this.poolId=l??`pool_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,e.getLogger().debug(`[WalletPool] Created pool: ${this.poolId}`)}getAdapters(){return typeof window>"u"?[]:this.isCleanedUp?(e.getLogger().warn(`[WalletPool] Attempted to use pool after cleanup: ${this.poolId}`),[]):this.adapters!==null?this.adapters:(e.getLogger().debug(`[WalletPool] Initializing adapters for pool: ${this.poolId}`),this.adapters=[new a.PhantomWalletAdapter,new a.SolflareWalletAdapter],this.adapters)}async cleanup(){if(this.isCleanedUp){e.getLogger().debug(`[WalletPool] Pool already cleaned up: ${this.poolId}`);return}if(e.getLogger().debug(`[WalletPool] Cleaning up pool: ${this.poolId}`),this.isCleanedUp=!0,this.adapters===null)return;const l=this.adapters.map(async t=>{try{t.connected&&(e.getLogger().debug(`[WalletPool] Disconnecting wallet: ${t.name}`),await t.disconnect())}catch(n){e.getLogger().warn(`[WalletPool] Failed to disconnect wallet ${t.name}:`,n)}});await Promise.allSettled(l),this.adapters=null,e.getLogger().debug(`[WalletPool] Pool cleanup complete: ${this.poolId}`)}isInitialized(){return this.adapters!==null}getId(){return this.poolId}}function i(o){return new r(o)}exports.WalletPool=r;exports.createWalletPool=i;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("@solana/wallet-adapter-wallets"),e=require("./CedrosContext-C2RjHLaQ.js");class r{adapters=null;poolId;isCleanedUp=!1;constructor(l){this.poolId=l??`pool_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,e.getLogger().debug(`[WalletPool] Created pool: ${this.poolId}`)}getAdapters(){return typeof window>"u"?[]:this.isCleanedUp?(e.getLogger().warn(`[WalletPool] Attempted to use pool after cleanup: ${this.poolId}`),[]):this.adapters!==null?this.adapters:(e.getLogger().debug(`[WalletPool] Initializing adapters for pool: ${this.poolId}`),this.adapters=[new a.PhantomWalletAdapter,new a.SolflareWalletAdapter],this.adapters)}async cleanup(){if(this.isCleanedUp){e.getLogger().debug(`[WalletPool] Pool already cleaned up: ${this.poolId}`);return}if(e.getLogger().debug(`[WalletPool] Cleaning up pool: ${this.poolId}`),this.isCleanedUp=!0,this.adapters===null)return;const l=this.adapters.map(async t=>{try{t.connected&&(e.getLogger().debug(`[WalletPool] Disconnecting wallet: ${t.name}`),await t.disconnect())}catch(n){e.getLogger().warn(`[WalletPool] Failed to disconnect wallet ${t.name}:`,n)}});await Promise.allSettled(l),this.adapters=null,e.getLogger().debug(`[WalletPool] Pool cleanup complete: ${this.poolId}`)}isInitialized(){return this.adapters!==null}getId(){return this.poolId}}function i(o){return new r(o)}exports.WalletPool=r;exports.createWalletPool=i;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cedros/pay-react",
3
- "version": "1.1.24",
3
+ "version": "1.1.25",
4
4
  "description": "React frontend library for Cedros Pay - unified Stripe and Solana x402 payments",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -1,6 +0,0 @@
1
- "use strict";const W=require("react/jsx-runtime"),g=require("react"),x=require("./uuid-C5B8o31X.js");var Ae="https://js.stripe.com/v3",ze=/^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/;var Qe=function(){for(var e=document.querySelectorAll('script[src^="'.concat(Ae,'"]')),r=0;r<e.length;r++){var a=e[r];if(ze.test(a.src))return a}return null},ce=function(e){var r="",a=document.createElement("script");a.src="".concat(Ae).concat(r);var n=document.head||document.body;if(!n)throw new Error("Expected document.body not to be null. Stripe.js requires a <body> element.");return n.appendChild(a),a},We=function(e,r){!e||!e._registerWrapper||e._registerWrapper({name:"stripe-js",version:"4.6.0",startTime:r})},L=null,j=null,z=null,Ke=function(e){return function(){e(new Error("Failed to load Stripe.js"))}},Ge=function(e,r){return function(){window.Stripe?e(window.Stripe):r(new Error("Stripe.js not available"))}},Ve=function(e){return L!==null?L:(L=new Promise(function(r,a){if(typeof window>"u"||typeof document>"u"){r(null);return}if(window.Stripe){r(window.Stripe);return}try{var n=Qe();if(!(n&&e)){if(!n)n=ce(e);else if(n&&z!==null&&j!==null){var i;n.removeEventListener("load",z),n.removeEventListener("error",j),(i=n.parentNode)===null||i===void 0||i.removeChild(n),n=ce(e)}}z=Ge(r,a),j=Ke(a),n.addEventListener("load",z),n.addEventListener("error",j)}catch(o){a(o);return}}),L.catch(function(r){return L=null,Promise.reject(r)}))},Je=function(e,r,a){if(e===null)return null;var n=e.apply(void 0,r);return We(n,a),n},H,pe=!1,ge=function(){return H||(H=Ve(null).catch(function(e){return H=null,Promise.reject(e)}),H)};Promise.resolve().then(function(){return ge()}).catch(function(t){pe||console.warn(t)});var we=function(){for(var e=arguments.length,r=new Array(e),a=0;a<e;a++)r[a]=arguments[a];pe=!0;var n=Date.now();return ge().then(function(i){return Je(i,r,n)})},be=(t=>(t[t.DEBUG=0]="DEBUG",t[t.INFO=1]="INFO",t[t.WARN=2]="WARN",t[t.ERROR=3]="ERROR",t[t.SILENT=4]="SILENT",t))(be||{});class ae{config;constructor(e){this.config=e}setLevel(e){this.config.level=e}getLevel(){return this.config.level}debug(...e){this.config.level<=0&&this.log("DEBUG",console.log,e)}info(...e){this.config.level<=1&&this.log("INFO",console.info,e)}warn(...e){this.config.level<=2&&this.log("WARN",console.warn,e)}error(...e){this.config.level<=3&&this.log("ERROR",console.error,e)}log(e,r,a){const n=this.config.prefix?`${this.config.prefix} `:"",i=new Date().toISOString();r(`[${i}] ${n}[${e}]`,...a)}}const Ye=()=>typeof process<"u"&&process.env.NODE_ENV==="development"?0:2;let K=null;function l(){return K||(K=new ae({level:Ye(),prefix:"[CedrosPay]"})),K}function Xe(t){K=t}function ve(t){return new ae(t)}function R(t,e){return t instanceof Error?t.message:typeof t=="string"?t:e}const Ze={service_unavailable:"Service temporarily unavailable. Please try again later or contact support.",server_insufficient_funds:"Service temporarily unavailable. Please try again later or contact support.",insufficient_funds_token:"Insufficient token balance in your wallet. Please add more tokens and try again.",insufficient_funds_sol:"Insufficient SOL for transaction fees. Please add some SOL to your wallet and try again.",insufficient_amount:"Payment amount is insufficient. Please check the required amount.",invalid_signature:"Transaction signature is invalid. Please try again.",send_failed:"Failed to send transaction. Please try again or contact support.",timeout:"Transaction timed out. Please check the blockchain explorer or try again."};async function w(t,e,r=!1){const a=typeof t.clone=="function",n=a?t.clone():void 0;try{const i=await t.json();if(r&&i.verificationError){l().debug(`Payment verification failed: ${i.verificationError.code}`);const o=i.verificationError.code;return Ze[o]||i.verificationError.message||e}return typeof i.error=="string"?i.error:i.error&&typeof i.error=="object"&&"message"in i.error?i.error.message:e}catch{if(n)try{const i=await n.text();if(i)return i}catch{}if(!a&&typeof t.text=="function")try{const i=await t.text();if(i)return i}catch{}return e}}const $e=15e3;async function A(t,e={},r=$e){const a=new AbortController,n=e.signal;if(n?.aborted)throw a.abort(),new DOMException("The operation was aborted","AbortError");const i=setTimeout(()=>a.abort(),r);let o=null;n&&(o=()=>a.abort(),n.addEventListener("abort",o));try{return await fetch(t,{...e,signal:a.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?n?.aborted?s:new Error(`Request timeout after ${r}ms`):s}finally{clearTimeout(i),n&&o&&n.removeEventListener("abort",o)}}function M(t){const{maxRequests:e,windowMs:r}=t;let a=e,n=Date.now();const i=e/r;function o(){const u=Date.now(),y=u-n;if(y>0){const f=y*i;a=Math.min(e,a+f),n=u}}function s(){return o(),a>=1?(a-=1,!0):!1}function c(){return o(),Math.floor(a)}function d(){if(o(),a>=1)return 0;const y=(1-a)/i;return Math.ceil(y)}function m(){a=e,n=Date.now()}return{tryConsume:s,getAvailableTokens:c,getTimeUntilRefill:d,reset:m}}const D={PAYMENT:{maxRequests:10,windowMs:6e4},QUOTE:{maxRequests:30,windowMs:6e4},STRICT:{maxRequests:5,windowMs:6e4},PERMISSIVE:{maxRequests:100,windowMs:6e4}};var Ee=(t=>(t.CLOSED="CLOSED",t.OPEN="OPEN",t.HALF_OPEN="HALF_OPEN",t))(Ee||{});class p extends Error{constructor(e){super(e),this.name="CircuitBreakerOpenError"}}function N(t){const{failureThreshold:e,timeout:r,failureWindow:a=r*2,name:n="circuit-breaker"}=t;let i="CLOSED",o=[],s=0,c=0,d=null,m=null,u=null,y=!1;function f(){const B=Date.now()-a;o=o.filter(S=>S>B)}function h(){i==="OPEN"&&u!==null&&Date.now()>=u&&(l().debug(`[CircuitBreaker:${n}] Transitioning OPEN → HALF_OPEN (timeout expired)`),i="HALF_OPEN",u=null)}function b(){m=Date.now(),s++,i==="HALF_OPEN"?(l().debug(`[CircuitBreaker:${n}] Success in HALF_OPEN → CLOSED`),i="CLOSED",o=[]):i==="CLOSED"&&(o=[])}function P(B){const S=Date.now();d=S,o.push(S),f();const Y=o.length;l().warn(`[CircuitBreaker:${n}] Failure recorded (${Y}/${e}):`,B.message),i==="HALF_OPEN"?(l().warn(`[CircuitBreaker:${n}] Failed in HALF_OPEN → OPEN`),i="OPEN",u=S+r):i==="CLOSED"&&Y>=e&&(l().error(`[CircuitBreaker:${n}] Failure threshold reached (${Y}) → OPEN`),i="OPEN",u=S+r)}async function T(B){if(h(),i==="OPEN"){c++;const S=u?Math.ceil((u-Date.now())/1e3):0;throw new p(`Circuit breaker is OPEN. Service is unavailable. Retry in ${S}s.`)}if(i==="HALF_OPEN"&&y)throw c++,new p("Circuit breaker is HALF_OPEN. A probe request is already in progress.");i==="HALF_OPEN"&&(y=!0);try{const S=await B();return b(),S}catch(S){throw P(S instanceof Error?S:new Error(String(S))),S}finally{y&&(y=!1)}}function U(){return h(),i}function k(){return h(),f(),{state:i,failures:o.length,successes:s,rejections:c,lastFailureTime:d,lastSuccessTime:m}}function I(){l().debug(`[CircuitBreaker:${n}] Manual reset → CLOSED`),i="CLOSED",o=[],s=0,c=0,d=null,m=null,u=null}function je(){l().warn(`[CircuitBreaker:${n}] Manual trip → OPEN`),i="OPEN",u=Date.now()+r}return{execute:T,getState:U,getStats:k,reset:I,trip:je}}const et={STRICT:{failureThreshold:3,timeout:6e4},STANDARD:{failureThreshold:5,timeout:3e4},LENIENT:{failureThreshold:10,timeout:15e3}},tt={invalid_payment_proof:{message:"Payment verification failed",action:"Please try your payment again. If this continues, contact support.",technicalHint:"Invalid payment proof format"},invalid_signature:{message:"Transaction signature is invalid",action:"Please approve the transaction in your wallet and try again.",technicalHint:"Transaction signature verification failed"},invalid_transaction:{message:"Transaction format is invalid",action:"Please try your payment again. If this continues, try updating your wallet app.",technicalHint:"Malformed transaction structure"},transaction_not_found:{message:"Transaction not found on the blockchain",action:"Your transaction may still be processing. Please wait a moment and check your wallet, or try again.",technicalHint:"Transaction signature not found on-chain"},transaction_not_confirmed:{message:"Transaction is still processing",action:"Please wait a moment for the blockchain to confirm your transaction, then try again.",technicalHint:"Transaction not yet confirmed"},transaction_failed:{message:"Transaction failed on the blockchain",action:"Check your wallet for details. You may need to adjust your transaction settings or add more SOL for fees.",technicalHint:"On-chain transaction failure"},transaction_expired:{message:"Transaction took too long to process",action:"Please try your payment again. Consider increasing transaction priority if your wallet supports it.",technicalHint:"Transaction blockhash expired"},invalid_recipient:{message:"Payment was sent to the wrong address",action:"Please try again and ensure you approve the correct transaction in your wallet.",technicalHint:"Recipient address mismatch"},invalid_sender:{message:"Payment sender wallet is invalid",action:"Please reconnect your wallet and try again.",technicalHint:"Sender address validation failed"},unauthorized_refund_issuer:{message:"You are not authorized to issue refunds",action:"Only authorized accounts can process refunds. Please contact support if you believe this is an error.",technicalHint:"Refund issuer not in authorized list"},amount_below_minimum:{message:"Payment amount is too low",action:"Please check the required amount and try again.",technicalHint:"Amount below minimum threshold"},amount_mismatch:{message:"Payment amount does not match the quote",action:"The price may have changed. Please refresh and try your payment again.",technicalHint:"Amount does not match quote"},insufficient_funds_sol:{message:"Not enough SOL for transaction fees",action:"Add at least 0.001 SOL to your wallet to cover network fees, then try again.",technicalHint:"Insufficient SOL balance for fees"},insufficient_funds_token:{message:"Insufficient balance in your wallet",action:"Add more funds to your wallet and try again.",technicalHint:"Insufficient token balance"},invalid_token_mint:{message:"Incorrect payment token",action:"Please pay with the correct token as shown in the payment details.",technicalHint:"Token mint address mismatch"},not_spl_transfer:{message:"Transaction is not a valid token transfer",action:"Please ensure you are sending the correct token type from your wallet.",technicalHint:"Transaction is not an SPL token transfer"},missing_token_account:{message:"Token account not found",action:"Your wallet may need to create a token account first. Try again or use a different wallet.",technicalHint:"Associated token account does not exist"},invalid_token_program:{message:"Invalid token program",action:"Please try your payment again. If this continues, try using a different wallet.",technicalHint:"Token program ID mismatch"},missing_memo:{message:"Payment memo is required but was not included",action:"Please try your payment again and ensure transaction details are approved in your wallet.",technicalHint:"Required memo instruction missing"},invalid_memo:{message:"Payment memo format is invalid",action:"Please try your payment again.",technicalHint:"Memo does not match expected format"},payment_already_used:{message:"This payment has already been processed",action:"Check your transaction history. If you need to make another payment, please start a new transaction.",technicalHint:"Payment signature already recorded"},signature_reused:{message:"Transaction signature has already been used",action:"Please create a new payment transaction.",technicalHint:"Duplicate signature detected"},quote_expired:{message:"Payment quote has expired",action:"Prices are updated frequently. Please refresh and try your payment again.",technicalHint:"Quote timestamp expired"},missing_field:{message:"Required information is missing",action:"Please check all required fields and try again.",technicalHint:"Required field not provided"},invalid_field:{message:"Some information is invalid",action:"Please check your input and try again.",technicalHint:"Field validation failed"},invalid_amount:{message:"Payment amount is invalid",action:"Please check the amount and try again.",technicalHint:"Amount validation failed"},invalid_wallet:{message:"Wallet address is invalid",action:"Please reconnect your wallet and try again.",technicalHint:"Wallet address validation failed"},invalid_resource:{message:"Invalid item selection",action:"Please refresh the page and try again.",technicalHint:"Resource ID validation failed"},invalid_coupon:{message:"Invalid coupon code",action:"Please check the coupon code and try again.",technicalHint:"Coupon code format invalid"},invalid_cart_item:{message:"One or more cart items are invalid",action:"Please review your cart and try again.",technicalHint:"Cart item validation failed"},empty_cart:{message:"Your cart is empty",action:"Please add items to your cart before checking out.",technicalHint:"Cart contains no items"},resource_not_found:{message:"Item not found",action:"This item may no longer be available. Please refresh and try again.",technicalHint:"Resource not found in database"},cart_not_found:{message:"Shopping cart not found",action:"Your cart may have expired. Please start a new order.",technicalHint:"Cart ID not found"},refund_not_found:{message:"Refund not found",action:"Please check your refund reference number or contact support.",technicalHint:"Refund ID not found"},product_not_found:{message:"Product not available",action:"This product may no longer be available. Please browse our current selection.",technicalHint:"Product ID not found"},coupon_not_found:{message:"Coupon code not found",action:"Please check the coupon code or remove it to continue.",technicalHint:"Coupon code not in database"},session_not_found:{message:"Payment session expired",action:"Please start a new payment.",technicalHint:"Session ID not found or expired"},cart_already_paid:{message:"This order has already been paid",action:"Check your order history. If you need to make another purchase, please start a new order.",technicalHint:"Cart marked as paid"},refund_already_processed:{message:"This refund has already been processed",action:"Check your transaction history or contact support for details.",technicalHint:"Refund already completed"},coupon_expired:{message:"Coupon has expired",action:"Please remove the coupon code or use a different code.",technicalHint:"Coupon expiration date passed"},coupon_usage_limit_reached:{message:"Coupon usage limit reached",action:"This coupon has been fully redeemed. Please try a different code.",technicalHint:"Coupon max uses exceeded"},coupon_not_applicable:{message:"Coupon cannot be applied to this purchase",action:"Please check the coupon terms or remove it to continue.",technicalHint:"Coupon conditions not met"},coupon_wrong_payment_method:{message:"Coupon not valid for this payment method",action:"Try a different payment method or remove the coupon code.",technicalHint:"Coupon restricted to specific payment methods"},stripe_error:{message:"Card payment service temporarily unavailable",action:"Please try again in a moment, or use cryptocurrency payment instead.",technicalHint:"Stripe API error"},rpc_error:{message:"Blockchain network temporarily unavailable",action:"Please try again in a moment, or use card payment instead.",technicalHint:"Solana RPC error"},network_error:{message:"Network connection issue",action:"Please check your internet connection and try again.",technicalHint:"Network request failed"},internal_error:{message:"Something went wrong on our end",action:"Please try again. If this continues, contact support.",technicalHint:"Internal server error"},database_error:{message:"Service temporarily unavailable",action:"Please try again in a moment.",technicalHint:"Database operation failed"},config_error:{message:"Service configuration error",action:"Please contact support for assistance.",technicalHint:"Server misconfiguration"}};function Ce(t){return tt[t]||{message:"An unexpected error occurred",action:"Please try again or contact support if this continues.",technicalHint:`Unknown error code: ${t}`}}class O extends Error{code;retryable;details;httpStatus;constructor(e,r,a=!1,n,i){super(r),this.name="PaymentError",this.code=e,this.retryable=a,this.details=n,this.httpStatus=i,Object.setPrototypeOf(this,O.prototype)}canRetry(){return this.retryable}is(e){return this.code===e}isInCategory(e){return e.includes(this.code)}getUserMessage(){const e=this.getErrorInfo();return e.action?`${e.message} ${e.action}`:e.message}getShortMessage(){return this.getErrorInfo().message}getAction(){return this.getErrorInfo().action}getErrorInfo(){return Ce(this.code)}static fromErrorResponse(e,r){const a=e.error.retryable??Pe.RETRYABLE.includes(e.error.code);return new O(e.error.code,e.error.message,a,e.error.details,r)}static fromUnknown(e){return e instanceof O?e:e instanceof Error?new O("internal_error",e.message,!1):new O("internal_error",String(e),!1)}}const Pe={INSUFFICIENT_FUNDS:["insufficient_funds_sol","insufficient_funds_token"],TRANSACTION_PENDING:["transaction_not_confirmed","transaction_not_found"],VALIDATION:["missing_field","invalid_field","invalid_amount","invalid_wallet","invalid_resource","invalid_cart_item","empty_cart"],COUPON:["invalid_coupon","coupon_not_found","coupon_expired","coupon_usage_limit_reached","coupon_not_applicable","coupon_wrong_payment_method"],RETRYABLE:["transaction_not_confirmed","rpc_error","network_error","stripe_error"],NOT_FOUND:["resource_not_found","cart_not_found","refund_not_found","product_not_found","coupon_not_found","session_not_found","credits_hold_not_found"],CREDITS:["insufficient_credits","credits_hold_expired","credits_hold_not_found"],SECURITY:["invalid_redirect_url","rate_limit_exceeded","nonce_already_used"]};function rt(t,e){if(t instanceof O&&t.httpStatus!=null){const a=t.httpStatus;return a===429||a>=500&&a<600}const r=t.message.toLowerCase();return!!(r.includes("network")||r.includes("timeout")||r.includes("fetch failed")||r.includes("econnrefused"))}function at(t,e,r,a,n){const i=e*Math.pow(r,t),o=Math.min(i,a);return Math.floor(n?o*.5+Math.random()*o*.5:o)}function nt(t){return new Promise(e=>setTimeout(e,t))}async function v(t,e={}){const{maxRetries:r=3,initialDelayMs:a=1e3,backoffFactor:n=2,maxDelayMs:i=3e4,jitter:o=!0,shouldRetry:s=rt,name:c="retry"}=e;let d=null,m=0;for(let u=0;u<=r;u++)try{const y=await t();return u>0&&l().debug(`[Retry:${c}] Succeeded on attempt ${u+1}/${r+1} after ${m}ms`),y}catch(y){d=y instanceof Error?y:new Error(String(y));const f=u===r,h=s(d,u);if(f||!h)throw l().warn(`[Retry:${c}] Failed on attempt ${u+1}/${r+1}. ${f?"No more retries.":"Error not retryable."}`),d;const b=at(u,a,n,i,o);m+=b,l().warn(`[Retry:${c}] Attempt ${u+1}/${r+1} failed: ${d.message}. Retrying in ${b}ms...`),await nt(b)}throw d||new Error("Retry failed with no error")}const C={QUICK:{maxRetries:3,initialDelayMs:1e3,backoffFactor:2,maxDelayMs:1e4},STANDARD:{maxRetries:3,initialDelayMs:2e3,backoffFactor:2,maxDelayMs:3e4},AGGRESSIVE:{maxRetries:5,initialDelayMs:500,backoffFactor:1.5,maxDelayMs:15e3},PATIENT:{maxRetries:5,initialDelayMs:5e3,backoffFactor:2,maxDelayMs:6e4}};class it{stripe=null;initPromise=null;publicKey;routeDiscovery;rateLimiter=M(D.PAYMENT);circuitBreaker=N({failureThreshold:5,timeout:1e4,name:"stripe-manager"});constructor(e,r){this.publicKey=e,this.routeDiscovery=r}async initialize(){this.stripe||(this.initPromise||(this.initPromise=(async()=>{try{if(this.stripe=await we(this.publicKey),!this.stripe)throw new Error("Failed to initialize Stripe")}catch(e){throw this.initPromise=null,e}})()),await this.initPromise)}async createSession(e){if(!this.rateLimiter.tryConsume())throw new Error("Rate limit exceeded for Stripe session creation. Please try again later.");const r=x.generateUUID();try{return await this.circuitBreaker.execute(async()=>await v(async()=>{const a=await this.routeDiscovery.buildUrl("/paywall/v1/stripe-session");l().debug("[StripeManager] Creating session",{resource:e.resource,hasCouponCode:!!e.couponCode,hasMetadata:!!(e.metadata&&Object.keys(e.metadata).length),metadataKeyCount:e.metadata?Object.keys(e.metadata).length:0});const n=await A(a,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":r},body:JSON.stringify(e)});if(!n.ok){const i=await w(n,"Failed to create Stripe session");throw new Error(i)}return await n.json()},{...C.STANDARD,name:"stripe-create-session"}))}catch(a){throw a instanceof p?(l().error("[StripeManager] Circuit breaker is OPEN - Stripe service unavailable"),new Error("Stripe payment service is temporarily unavailable. Please try again in a few moments.")):a}}async redirectToCheckout(e){if(this.stripe||await this.initialize(),!this.stripe)return{success:!1,error:"Stripe not initialized"};const r=await this.stripe.redirectToCheckout({sessionId:e});return r.error?{success:!1,error:r.error.message}:{success:!0}}async processPayment(e){try{const r=await this.createSession(e);return await this.redirectToCheckout(r.sessionId)}catch(r){return{success:!1,error:R(r,"Unknown error")}}}async processCartCheckout(e){const{items:r,successUrl:a,cancelUrl:n,metadata:i,customerEmail:o,customerName:s,customerPhone:c,shippingAddress:d,billingAddress:m,couponCode:u,tipAmount:y,shippingMethodId:f,paymentMethodId:h}=e;if(!this.rateLimiter.tryConsume())return{success:!1,error:"Rate limit exceeded for cart checkout. Please try again later."};const b=x.generateUUID();try{const P=await this.circuitBreaker.execute(async()=>await v(async()=>{const T=await this.routeDiscovery.buildUrl("/paywall/v1/cart/checkout"),k=await A(T,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":b},body:JSON.stringify({items:r,successUrl:a,cancelUrl:n,metadata:i,customerEmail:o,customerName:s,customerPhone:c,shippingAddress:d,billingAddress:m,coupon:u,couponCode:u,tipAmount:y,shippingMethodId:f,paymentMethodId:h})});if(!k.ok){const I=await w(k,"Failed to create cart checkout session");throw new Error(I)}return await k.json()},{...C.STANDARD,name:"stripe-cart-checkout"}));return await this.redirectToCheckout(P.sessionId)}catch(P){return P instanceof p?{success:!1,error:"Stripe payment service is temporarily unavailable. Please try again in a few moments."}:{success:!1,error:R(P,"Cart checkout failed")}}}}const Se="3.7.8",ot=Se,F=typeof Buffer=="function",le=typeof TextDecoder=="function"?new TextDecoder:void 0,ue=typeof TextEncoder=="function"?new TextEncoder:void 0,st="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",q=Array.prototype.slice.call(st),Q=(t=>{let e={};return t.forEach((r,a)=>e[r]=a),e})(q),ct=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,E=String.fromCharCode.bind(String),de=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):t=>new Uint8Array(Array.prototype.slice.call(t,0)),xe=t=>t.replace(/=/g,"").replace(/[+\/]/g,e=>e=="+"?"-":"_"),Te=t=>t.replace(/[^A-Za-z0-9\+\/]/g,""),ke=t=>{let e,r,a,n,i="";const o=t.length%3;for(let s=0;s<t.length;){if((r=t.charCodeAt(s++))>255||(a=t.charCodeAt(s++))>255||(n=t.charCodeAt(s++))>255)throw new TypeError("invalid character found");e=r<<16|a<<8|n,i+=q[e>>18&63]+q[e>>12&63]+q[e>>6&63]+q[e&63]}return o?i.slice(0,o-3)+"===".substring(o):i},ne=typeof btoa=="function"?t=>btoa(t):F?t=>Buffer.from(t,"binary").toString("base64"):ke,ee=F?t=>Buffer.from(t).toString("base64"):t=>{let r=[];for(let a=0,n=t.length;a<n;a+=4096)r.push(E.apply(null,t.subarray(a,a+4096)));return ne(r.join(""))},G=(t,e=!1)=>e?xe(ee(t)):ee(t),lt=t=>{if(t.length<2){var e=t.charCodeAt(0);return e<128?t:e<2048?E(192|e>>>6)+E(128|e&63):E(224|e>>>12&15)+E(128|e>>>6&63)+E(128|e&63)}else{var e=65536+(t.charCodeAt(0)-55296)*1024+(t.charCodeAt(1)-56320);return E(240|e>>>18&7)+E(128|e>>>12&63)+E(128|e>>>6&63)+E(128|e&63)}},ut=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,Re=t=>t.replace(ut,lt),fe=F?t=>Buffer.from(t,"utf8").toString("base64"):ue?t=>ee(ue.encode(t)):t=>ne(Re(t)),_=(t,e=!1)=>e?xe(fe(t)):fe(t),he=t=>_(t,!0),dt=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,ft=t=>{switch(t.length){case 4:var e=(7&t.charCodeAt(0))<<18|(63&t.charCodeAt(1))<<12|(63&t.charCodeAt(2))<<6|63&t.charCodeAt(3),r=e-65536;return E((r>>>10)+55296)+E((r&1023)+56320);case 3:return E((15&t.charCodeAt(0))<<12|(63&t.charCodeAt(1))<<6|63&t.charCodeAt(2));default:return E((31&t.charCodeAt(0))<<6|63&t.charCodeAt(1))}},Me=t=>t.replace(dt,ft),De=t=>{if(t=t.replace(/\s+/g,""),!ct.test(t))throw new TypeError("malformed base64.");t+="==".slice(2-(t.length&3));let e,r,a,n=[];for(let i=0;i<t.length;)e=Q[t.charAt(i++)]<<18|Q[t.charAt(i++)]<<12|(r=Q[t.charAt(i++)])<<6|(a=Q[t.charAt(i++)]),r===64?n.push(E(e>>16&255)):a===64?n.push(E(e>>16&255,e>>8&255)):n.push(E(e>>16&255,e>>8&255,e&255));return n.join("")},ie=typeof atob=="function"?t=>atob(Te(t)):F?t=>Buffer.from(t,"base64").toString("binary"):De,Oe=F?t=>de(Buffer.from(t,"base64")):t=>de(ie(t).split("").map(e=>e.charCodeAt(0))),Ie=t=>Oe(Ue(t)),ht=F?t=>Buffer.from(t,"base64").toString("utf8"):le?t=>le.decode(Oe(t)):t=>Me(ie(t)),Ue=t=>Te(t.replace(/[-_]/g,e=>e=="-"?"+":"/")),te=t=>ht(Ue(t)),mt=t=>{if(typeof t!="string")return!1;const e=t.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(e)||!/[^\s0-9a-zA-Z\-_]/.test(e)},Be=t=>({value:t,enumerable:!1,writable:!0,configurable:!0}),_e=function(){const t=(e,r)=>Object.defineProperty(String.prototype,e,Be(r));t("fromBase64",function(){return te(this)}),t("toBase64",function(e){return _(this,e)}),t("toBase64URI",function(){return _(this,!0)}),t("toBase64URL",function(){return _(this,!0)}),t("toUint8Array",function(){return Ie(this)})},Ne=function(){const t=(e,r)=>Object.defineProperty(Uint8Array.prototype,e,Be(r));t("toBase64",function(e){return G(this,e)}),t("toBase64URI",function(){return G(this,!0)}),t("toBase64URL",function(){return G(this,!0)})},yt=()=>{_e(),Ne()},re={version:Se,VERSION:ot,atob:ie,atobPolyfill:De,btoa:ne,btoaPolyfill:ke,fromBase64:te,toBase64:_,encode:_,encodeURI:he,encodeURL:he,utob:Re,btou:Me,decode:te,isValid:mt,fromUint8Array:G,toUint8Array:Ie,extendString:_e,extendUint8Array:Ne,extendBuiltins:yt};class At{routeDiscovery;quoteRateLimiter=M(D.QUOTE);verifyRateLimiter=M(D.PAYMENT);circuitBreaker=N({failureThreshold:5,timeout:1e4,name:"x402-manager"});constructor(e){this.routeDiscovery=e}async requestQuote(e){const{resource:r,couponCode:a}=e;if(!this.quoteRateLimiter.tryConsume())throw new Error("Rate limit exceeded for quote requests. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await v(async()=>{const n="/paywall/v1/quote";l().debug("[X402Manager] Requesting quote",a?"with coupon":"without coupon");const i=await this.routeDiscovery.buildUrl(n),o=await A(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({resource:r,couponCode:a||null})});if(o.status!==402)throw new Error(`Expected 402 status, got ${o.status}`);const s=await o.json();if(s.crypto){const c=s.crypto;if(!this.validateRequirement(c))throw new Error("Invalid x402 requirement received from server: missing required fields");return c}else if(s.accepts&&s.accepts.length>0){const c=s.accepts[0];if(!this.validateRequirement(c))throw new Error("Invalid x402 requirement received from server: missing required fields");return c}else throw new Error("Invalid x402 response: missing crypto or accepts field")},{...C.QUICK,name:"x402-quote"}))}catch(n){throw n instanceof p?(l().error("[X402Manager] Circuit breaker is OPEN - x402 service unavailable"),new Error("Payment service is temporarily unavailable. Please try again in a few moments.")):n}}async requestCartQuote(e){const{items:r,metadata:a,couponCode:n}=e;if(!this.quoteRateLimiter.tryConsume())throw new Error("Rate limit exceeded for cart quote requests. Please try again later.");const i=x.generateUUID();try{return await this.circuitBreaker.execute(async()=>await v(async()=>{const o=await this.routeDiscovery.buildUrl("/paywall/v1/cart/quote"),c=await A(o,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":i},body:JSON.stringify({items:r,metadata:a,coupon:n,couponCode:n})});if(c.status!==402&&!c.ok){const m=await w(c,"Failed to get cart quote");throw new Error(m)}const d=await c.json();if(!d.cartId||!d.quote)throw new Error("Invalid cart quote response: missing cartId or quote");if(d.quote.crypto&&!this.validateRequirement(d.quote.crypto))throw new Error("Invalid x402 cart quote: missing required fields in crypto quote");return d},{...C.QUICK,name:"x402-cart-quote"}))}catch(o){throw o instanceof p?(l().error("[X402Manager] Circuit breaker is OPEN - cart quote service unavailable"),new Error("Payment service is temporarily unavailable. Please try again in a few moments.")):o}}buildPaymentHeader(e){const r=JSON.stringify(e);return re.encode(r)}parseSettlementResponse(e){const r=e.headers.get("X-PAYMENT-RESPONSE");if(!r)return null;try{const a=re.decode(r),n=JSON.parse(a);return typeof n.success!="boolean"?(l().error("Invalid settlement response: missing success field"),null):n}catch(a){return l().error("Failed to parse settlement response:",a),null}}async submitPayment(e){const{resource:r,payload:a,couponCode:n,metadata:i,resourceType:o="regular"}=e;if(!this.verifyRateLimiter.tryConsume())return{success:!1,error:"Rate limit exceeded for payment verification. Please try again later."};const s=x.generateUUID();try{return await this.circuitBreaker.execute(async()=>await v(async()=>{const d={...a,payload:{...a.payload,resource:r,resourceType:o,metadata:{...a.payload.metadata||{},...i||{},...n?{couponCode:n}:{}}}},m=this.buildPaymentHeader(d),u="/paywall/v1/verify";l().debug("[X402Manager] Submitting payment",{resourceType:o,hasCoupon:!!n,hasMetadata:!!i});const y=await this.routeDiscovery.buildUrl(u),f=await A(y,{method:"POST",headers:{"Content-Type":"application/json","X-PAYMENT":m,"Idempotency-Key":s}});if(f.ok){const{settlement:b,transactionId:P}=await this.handlePaymentVerification(f,a.payload.signature);return{success:!0,transactionId:P,settlement:b||void 0}}return{success:!1,error:await w(f,"Payment verification failed",!0)}},{maxRetries:0,initialDelayMs:0,backoffFactor:1,maxDelayMs:0,name:"x402-verify"}))}catch(c){return c instanceof p?{success:!1,error:"Payment verification service is temporarily unavailable. Please try again in a few moments."}:{success:!1,error:R(c,"Unknown error")}}}async buildGaslessTransaction(e){const{resourceId:r,userWallet:a,feePayer:n,couponCode:i}=e;if(!this.quoteRateLimiter.tryConsume())throw new Error("Rate limit exceeded for gasless transaction requests. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await v(async()=>{const o=await this.routeDiscovery.buildUrl("/paywall/v1/gasless-transaction"),s=await A(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({resourceId:r,userWallet:a,feePayer:n,couponCode:i})});if(!s.ok){const c=await w(s,"Failed to build gasless transaction");throw new Error(c)}return await s.json()},{...C.QUICK,name:"x402-gasless-build"}))}catch(o){throw o instanceof p?(l().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}}async submitGaslessTransaction(e){const{resource:r,partialTx:a,couponCode:n,metadata:i,resourceType:o="regular",requirement:s}=e;if(!this.verifyRateLimiter.tryConsume())return{success:!1,error:"Rate limit exceeded for gasless transaction verification. Please try again later."};const c=x.generateUUID();try{return await this.circuitBreaker.execute(async()=>await v(async()=>{const m={x402Version:0,scheme:s?.scheme||"solana-spl-transfer",network:s?.network||"mainnet-beta",payload:{signature:"",transaction:a,feePayer:s?.extra?.feePayer||"",resource:r,resourceType:o,metadata:{...i||{},...n?{couponCode:n}:{}}}},u=this.buildPaymentHeader(m),f=await this.routeDiscovery.buildUrl("/paywall/v1/verify"),h=await A(f,{method:"POST",headers:{"Content-Type":"application/json","X-PAYMENT":u,"Idempotency-Key":c}});if(h.ok){const{settlement:P,transactionId:T}=await this.handlePaymentVerification(h,"gasless-tx");return{success:!0,transactionId:T,settlement:P||void 0}}return{success:!1,error:await w(h,"Gasless transaction failed",!0)}},{maxRetries:0,initialDelayMs:0,backoffFactor:1,maxDelayMs:0,name:"x402-gasless-verify"}))}catch(d){return d instanceof p?{success:!1,error:"Gasless transaction verification service is temporarily unavailable. Please try again in a few moments."}:{success:!1,error:R(d,"Unknown error")}}}async handlePaymentVerification(e,r){const a=this.parseSettlementResponse(e),n=e.headers.get("Content-Type")||"";let i=r;if(n.includes("application/json"))try{i=(await e.json()).signature||r}catch(o){l().warn("Failed to parse JSON response body:",o)}return{settlement:a,transactionId:i}}validateRequirement(e){return!!(e.scheme&&e.network&&e.maxAmountRequired&&e.resource&&e.payTo&&e.asset&&e.maxTimeoutSeconds>0)}}class pt{stripe=null;initPromise=null;publicKey;routeDiscovery;sessionRateLimiter=M(D.PAYMENT);statusRateLimiter=M(D.QUOTE);circuitBreaker=N({failureThreshold:5,timeout:1e4,name:"subscription-manager"});constructor(e,r){this.publicKey=e,this.routeDiscovery=r}async initialize(){this.stripe||(this.initPromise||(this.initPromise=(async()=>{if(this.stripe=await we(this.publicKey),!this.stripe)throw new Error("Failed to initialize Stripe")})()),await this.initPromise)}async executeWithResilience(e,r,a,n){if(!e.tryConsume())throw new Error("Rate limit exceeded. Please try again later.");try{return await this.circuitBreaker.execute(()=>v(r,{...C.STANDARD,name:a}))}catch(i){throw i instanceof p?(l().error(`[SubscriptionManager] Circuit breaker OPEN for ${n}`),new Error("Service temporarily unavailable. Please try again in a few moments.")):i}}async createSubscriptionSession(e){if(!this.sessionRateLimiter.tryConsume())throw new Error("Rate limit exceeded for subscription session creation. Please try again later.");const r=x.generateUUID();try{return await this.circuitBreaker.execute(async()=>await v(async()=>{const a=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/stripe-session");l().debug("[SubscriptionManager] Creating subscription session:",{resource:e.resource,interval:e.interval,trialDays:e.trialDays});const n=await A(a,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":r},body:JSON.stringify(e)});if(!n.ok){const i=await w(n,"Failed to create subscription session");throw new Error(i)}return await n.json()},{...C.STANDARD,name:"subscription-create-session"}))}catch(a){throw a instanceof p?(l().error("[SubscriptionManager] Circuit breaker is OPEN - service unavailable"),new Error("Subscription service is temporarily unavailable. Please try again in a few moments.")):a}}async redirectToCheckout(e){if(this.stripe||await this.initialize(),!this.stripe)return{success:!1,error:"Stripe not initialized"};const r=await this.stripe.redirectToCheckout({sessionId:e});return r.error?{success:!1,error:r.error.message}:{success:!0,transactionId:e}}async processSubscription(e){try{const r=await this.createSubscriptionSession(e);return await this.redirectToCheckout(r.sessionId)}catch(r){return{success:!1,error:R(r,"Subscription failed")}}}async checkSubscriptionStatus(e){if(!this.statusRateLimiter.tryConsume())throw new Error("Rate limit exceeded for subscription status check. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await v(async()=>{const r=new URLSearchParams({resource:e.resource,userId:e.userId}),a=await this.routeDiscovery.buildUrl(`/paywall/v1/subscription/status?${r.toString()}`);l().debug("[SubscriptionManager] Checking subscription status:",e);const n=await A(a,{method:"GET",headers:{"Content-Type":"application/json"}});if(!n.ok){const i=await w(n,"Failed to check subscription status");throw new Error(i)}return await n.json()},{...C.STANDARD,name:"subscription-status-check"}))}catch(r){throw r instanceof p?(l().error("[SubscriptionManager] Circuit breaker is OPEN for status check"),new Error("Subscription status service is temporarily unavailable. Please try again in a few moments.")):r}}async requestSubscriptionQuote(e,r,a){if(!this.statusRateLimiter.tryConsume())throw new Error("Rate limit exceeded for subscription quote. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await v(async()=>{const n=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/quote"),i={resource:e,interval:r,couponCode:a?.couponCode,intervalDays:a?.intervalDays};l().debug("[SubscriptionManager] Requesting subscription quote:",i);const o=await A(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(o.status!==402&&!o.ok){const s=await w(o,"Failed to get subscription quote");throw new Error(s)}return await o.json()},{...C.STANDARD,name:"subscription-quote"}))}catch(n){throw n instanceof p?(l().error("[SubscriptionManager] Circuit breaker is OPEN for quote"),new Error("Subscription quote service is temporarily unavailable. Please try again in a few moments.")):n}}async activateX402Subscription(e){return this.executeWithResilience(this.sessionRateLimiter,async()=>{const r=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/x402/activate");l().debug("[SubscriptionManager] Activating x402 subscription:",e);const a=await A(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!a.ok)throw new Error(await w(a,"Failed to activate"));return await a.json()},"subscription-activate","activation")}}class gt{routeDiscovery;rateLimiter=M(D.PAYMENT);queryRateLimiter=M(D.QUOTE);circuitBreaker=N({failureThreshold:5,timeout:1e4,name:"subscription-change-manager"});constructor(e){this.routeDiscovery=e}async executeWithResilience(e,r,a,n){if(!e.tryConsume())throw new Error("Rate limit exceeded. Please try again later.");try{return await this.circuitBreaker.execute(()=>v(r,{...C.STANDARD,name:a}))}catch(i){throw i instanceof p?(l().error(`[SubscriptionChangeManager] Circuit breaker OPEN for ${n}`),new Error("Service temporarily unavailable. Please try again in a few moments.")):i}}async changeSubscription(e){const r=x.generateUUID();return this.executeWithResilience(this.rateLimiter,async()=>{const a=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/change");l().debug("[SubscriptionChangeManager] Changing subscription:",e);const n=await A(a,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":r},body:JSON.stringify(e)});if(!n.ok)throw new Error(await w(n,"Failed to change subscription"));return await n.json()},"subscription-change","plan change")}async previewChange(e){return this.executeWithResilience(this.queryRateLimiter,async()=>{const r=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/change/preview");l().debug("[SubscriptionChangeManager] Previewing subscription change:",e);const a=await A(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!a.ok)throw new Error(await w(a,"Failed to preview change"));return await a.json()},"subscription-preview","change preview")}async getDetails(e,r){return this.executeWithResilience(this.queryRateLimiter,async()=>{const a=new URLSearchParams({resource:e,userId:r}),n=await this.routeDiscovery.buildUrl(`/paywall/v1/subscription/details?${a}`);l().debug("[SubscriptionChangeManager] Getting subscription details:",{resource:e,userId:r});const i=await A(n,{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(await w(i,"Failed to get subscription details"));return await i.json()},"subscription-details","details")}async cancel(e){return this.executeWithResilience(this.rateLimiter,async()=>{const r=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/cancel");l().debug("[SubscriptionChangeManager] Canceling subscription:",e);const a=await A(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!a.ok)throw new Error(await w(a,"Failed to cancel subscription"));return await a.json()},"subscription-cancel","cancellation")}async getBillingPortalUrl(e){return this.executeWithResilience(this.queryRateLimiter,async()=>{const r=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/portal");l().debug("[SubscriptionChangeManager] Getting billing portal URL:",e);const a=await A(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!a.ok)throw new Error(await w(a,"Failed to get billing portal URL"));return await a.json()},"subscription-portal","portal")}}class wt{routeDiscovery;rateLimiter=M(D.PAYMENT);circuitBreaker=N({failureThreshold:5,timeout:1e4,name:"credits-manager"});constructor(e){this.routeDiscovery=e}async requestQuote(e,r){if(!this.rateLimiter.tryConsume())throw new Error("Rate limit exceeded for credits quote. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await v(async()=>{const a=await this.routeDiscovery.buildUrl("/paywall/v1/quote");l().debug("[CreditsManager] Requesting quote");const n=await A(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({resource:e,couponCode:r})});if(n.status===402)return(await n.json()).credits||null;if(!n.ok){const i=await w(n,"Failed to get credits quote");throw new Error(i)}return null},{...C.STANDARD,name:"credits-quote"}))}catch(a){throw a instanceof p?(l().error("[CreditsManager] Circuit breaker is OPEN - credits service unavailable"),new Error("Credits service is temporarily unavailable. Please try again in a few moments.")):a}}async requestCartQuote(e,r){if(!this.rateLimiter.tryConsume())throw new Error("Rate limit exceeded for cart credits quote. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await v(async()=>{const a=await this.routeDiscovery.buildUrl("/paywall/v1/cart/quote");l().debug("[CreditsManager] Requesting cart quote for items:",e.length);const n=await A(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({items:e,couponCode:r})});if(n.status===402||n.ok){const o=await n.json();return o.credits?{cartId:o.cartId,credits:o.credits}:null}const i=await w(n,"Failed to get cart credits quote");throw new Error(i)},{...C.STANDARD,name:"credits-cart-quote"}))}catch(a){throw a instanceof p?new Error("Credits service is temporarily unavailable. Please try again in a few moments."):a}}async createHold(e){const{resource:r,couponCode:a,authToken:n}=e;if(!this.rateLimiter.tryConsume())throw new Error("Rate limit exceeded for credits hold. Please try again later.");const i=x.generateUUID();try{return await this.circuitBreaker.execute(async()=>await v(async()=>{const o=await this.routeDiscovery.buildUrl("/paywall/v1/credits/hold");l().debug("[CreditsManager] Creating hold");const s=await A(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,"Idempotency-Key":i},body:JSON.stringify({resource:r,couponCode:a})});if(!s.ok){const c=await w(s,"Failed to create credits hold");throw new Error(c)}return await s.json()},{...C.STANDARD,name:"credits-create-hold"}))}catch(o){throw o instanceof p?new Error("Credits service is temporarily unavailable. Please try again in a few moments."):o}}async createCartHold(e){const{cartId:r,authToken:a}=e;if(!this.rateLimiter.tryConsume())throw new Error("Rate limit exceeded for cart credits hold. Please try again later.");const n=x.generateUUID();try{return await this.circuitBreaker.execute(async()=>await v(async()=>{const i=await this.routeDiscovery.buildUrl(`/paywall/v1/cart/${encodeURIComponent(r)}/credits/hold`);l().debug("[CreditsManager] Creating cart hold for cart:",r);const o=await A(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`,"Idempotency-Key":n},body:JSON.stringify({})});if(!o.ok){const s=await w(o,"Failed to create cart credits hold");throw new Error(s)}return await o.json()},{...C.STANDARD,name:"credits-create-cart-hold"}))}catch(i){throw i instanceof p?new Error("Credits service is temporarily unavailable. Please try again in a few moments."):i}}async authorizePayment(e){const{resource:r,holdId:a,couponCode:n,authToken:i,metadata:o}=e;if(!this.rateLimiter.tryConsume())return{success:!1,error:"Rate limit exceeded for credits authorization. Please try again later.",errorCode:"rate_limit_exceeded"};const s=x.generateUUID();try{return await this.circuitBreaker.execute(async()=>await v(async()=>{const c=await this.routeDiscovery.buildUrl("/paywall/v1/credits/authorize");l().debug("[CreditsManager] Authorizing payment");const d=await A(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`,"Idempotency-Key":s},body:JSON.stringify({resource:r,holdId:a,couponCode:n,...o&&{metadata:o}})});if(!d.ok){const u=await d.json().catch(()=>({}));return{success:!1,error:u.error?.message||"Credits authorization failed",errorCode:u.error?.code||"authorization_failed"}}return{success:!0,transactionId:(await d.json()).transactionId}},{...C.STANDARD,name:"credits-authorize"}))}catch(c){return c instanceof p?{success:!1,error:"Credits service is temporarily unavailable. Please try again in a few moments.",errorCode:"service_unavailable"}:{success:!1,error:R(c,"Credits authorization failed"),errorCode:"authorization_failed"}}}async authorizeCartPayment(e){const{cartId:r,holdId:a,authToken:n,metadata:i}=e;if(!this.rateLimiter.tryConsume())return{success:!1,error:"Rate limit exceeded for cart credits authorization. Please try again later.",errorCode:"rate_limit_exceeded"};const o=x.generateUUID();try{return await this.circuitBreaker.execute(async()=>await v(async()=>{const s=await this.routeDiscovery.buildUrl(`/paywall/v1/cart/${encodeURIComponent(r)}/credits/authorize`);l().debug("[CreditsManager] Authorizing cart payment for cart:",r);const c=await A(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,"Idempotency-Key":o},body:JSON.stringify({holdId:a,...i&&{metadata:i}})});if(!c.ok){const m=await c.json().catch(u=>(l().error("[CreditsManager] Failed to parse error response JSON:",u,{cartId:r,status:c.status,statusText:c.statusText}),{}));return{success:!1,error:m.error?.message||"Cart credits authorization failed",errorCode:m.error?.code||"authorization_failed"}}return{success:!0,transactionId:(await c.json()).transactionId}},{...C.STANDARD,name:"credits-cart-authorize"}))}catch(s){return s instanceof p?{success:!1,error:"Credits service is temporarily unavailable. Please try again in a few moments.",errorCode:"service_unavailable"}:{success:!1,error:R(s,"Cart credits authorization failed"),errorCode:"authorization_failed"}}}async releaseHold(e,r){if(e)try{await this.circuitBreaker.execute(async()=>{const a=await this.routeDiscovery.buildUrl(`/paywall/v1/credits/hold/${encodeURIComponent(e)}/release`),n=await A(a,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Idempotency-Key":x.generateUUID()}});if(!n.ok){const i=await w(n,"Failed to release credits hold");throw new Error(i)}})}catch(a){throw a instanceof p?new Error("Credits service is temporarily unavailable. Please try again in a few moments."):a}}async processPayment(e,r,a,n){let i=null;try{i=(await this.createHold({resource:e,couponCode:a,authToken:r})).holdId;const s=await this.authorizePayment({resource:e,holdId:i,couponCode:a,authToken:r,metadata:n});if(!s.success&&i)try{await this.releaseHold(i,r)}catch(c){l().warn("[CreditsManager] Failed to release hold after auth failure:",c)}return{success:s.success,transactionId:s.transactionId,error:s.error}}catch(o){if(i)try{await this.releaseHold(i,r)}catch(s){l().warn("[CreditsManager] Failed to release hold after payment failure:",s)}return{success:!1,error:R(o,"Credits payment failed")}}}async getBalance(e){try{return await this.circuitBreaker.execute(async()=>{const r=await this.routeDiscovery.buildUrl("/paywall/v1/credits/balance"),a=await A(r,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!a.ok){const n=await w(a,"Failed to fetch credits balance");throw new Error(n)}return await a.json()})}catch(r){throw r instanceof p?new Error("Credits service is temporarily unavailable. Please try again in a few moments."):r}}}class bt{serverUrl;getLogger;fetchWithTimeout;routePrefix=null;discoveryPromise=null;failedDiscoveryAt=null;maxRetries=2;baseDelayMs=1e3;discoveryTimeoutMs=2e3;failedDiscoveryTtlMs=3e4;constructor(e,r){this.serverUrl=e.replace(/\/+$/,""),this.getLogger=r.getLogger,this.fetchWithTimeout=r.fetchWithTimeout}async discoverPrefix(){if(this.routePrefix!==null)return this.routePrefix;if(this.discoveryPromise)return this.discoveryPromise;if(this.failedDiscoveryAt!==null&&Date.now()-this.failedDiscoveryAt<this.failedDiscoveryTtlMs)return"";const e=(async()=>{let r=0;for(;r<this.maxRetries;)try{const a=await this.fetchWithTimeout(`${this.serverUrl}/cedros-health`,{},this.discoveryTimeoutMs);if(!a.ok){if(a.status>=400&&a.status<500)return this.getLogger().warn(`Route discovery received ${a.status} - not retrying client error`),this.failedDiscoveryAt=Date.now(),"";throw new Error(`Health check returned ${a.status}`)}const n=await a.json(),i=String(n.routePrefix??"");return this.routePrefix=i,this.failedDiscoveryAt=null,this.getLogger().debug("Route discovery successful, prefix:",i||"(empty)"),i}catch(a){if(r++,r>=this.maxRetries)return this.getLogger().warn(`Route discovery failed after ${r} attempts, using empty prefix for this request:`,a),this.failedDiscoveryAt=Date.now(),"";const n=this.baseDelayMs*Math.pow(2,r-1);this.getLogger().warn(`Route discovery failed (attempt ${r}/${this.maxRetries}), retrying in ${n}ms:`,a),await new Promise(i=>setTimeout(i,n))}return""})();this.discoveryPromise=e;try{return await this.discoveryPromise}finally{this.discoveryPromise===e&&(this.discoveryPromise=null)}}async buildUrl(e){const r=await this.discoverPrefix(),a=e.startsWith("/")?e:`/${e}`;return`${this.serverUrl}${r}${a}`}reset(){this.routePrefix=null,this.discoveryPromise=null,this.failedDiscoveryAt=null}}class vt extends bt{constructor(e){super(e,{getLogger:l,fetchWithTimeout:A})}}let X=null;async function Et(){return X||(X=(await Promise.resolve().then(()=>require("./WalletManager-Bwk3rgr1.js"))).WalletManager),X}const V=new Map,Z=new Map;function Fe(t,e,r,a,n){return JSON.stringify({stripePublicKey:t,serverUrl:e,solanaCluster:r,solanaEndpoint:a||"",dangerouslyAllowUnknownMint:n||!1})}async function Ct(t,e,r,a,n){const i=Fe(t,e,r,a,n);let o=V.get(i);if(o)return o.refCount++,l().debug(`[ManagerCache] Reusing cached managers (refCount: ${o.refCount}):`,{stripePublicKey:t.slice(0,10)+"...",serverUrl:e}),o;const s=Z.get(i);if(s)return o=await s,o.refCount++,l().debug(`[ManagerCache] Reusing in-flight managers (refCount: ${o.refCount}):`,{stripePublicKey:t.slice(0,10)+"...",serverUrl:e}),o;l().debug("[ManagerCache] Creating new manager instances:",{stripePublicKey:t.slice(0,10)+"...",serverUrl:e});const c=(async()=>{const d=new vt(e),m=new it(t,d),u=new At(d),y=await Et(),f=new y(r,a,n??!1),h=new pt(t,d),b=new gt(d),P=new wt(d);return{stripeManager:m,x402Manager:u,walletManager:f,subscriptionManager:h,subscriptionChangeManager:b,creditsManager:P,routeDiscovery:d,refCount:1}})();Z.set(i,c);try{return o=await c,V.set(i,o),o}finally{Z.delete(i)}}function me(t,e,r,a,n){const i=Fe(t,e,r,a,n),o=V.get(i);if(!o){l().warn("[ManagerCache] Attempted to release non-existent managers:",{cacheKey:i});return}o.refCount--,l().debug(`[ManagerCache] Released manager reference (refCount: ${o.refCount}):`,{stripePublicKey:t.slice(0,10)+"...",serverUrl:e}),o.refCount<=0&&(V.delete(i),l().debug("[ManagerCache] Removed managers from cache (refCount reached 0)"))}const Pt="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",xt="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==",Tt="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==",Le={EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v:{symbol:"USDC",decimals:6,icon:Pt},Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB:{symbol:"USDT",decimals:6,icon:St},"2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo":{symbol:"PYUSD",decimals:6,icon:xt},CASHx9KJUStyftLFWGvEVf59SGeG9sh5FfcnZMVPCASH:{symbol:"CASH",decimals:6,icon:Tt}},J=Object.fromEntries(Object.entries(Le).map(([t,e])=>[t,e.symbol]));function kt(t){return t in J}function oe(t,e="token mint",r=!1){if(!t||t.trim().length===0)return{isValid:!0,isKnownStablecoin:!1};const a=t.trim();if(kt(a))return{isValid:!0,isKnownStablecoin:!0,symbol:J[a]};const n=Object.entries(J).map(([i,o])=>` ${o}: ${i}`).join(`
2
- `);return r?{isValid:!0,isKnownStablecoin:!1,warning:[`Warning: Unrecognized token mint address in ${e}`,` Provided: ${a}`,"","This token mint does not match any known stablecoin addresses.","You have set dangerouslyAllowUnknownMint=true, so this will proceed.","If this is a typo, payments will be sent to the wrong token and funds will be PERMANENTLY LOST.","","Known stablecoin mints (mainnet-beta):",n,"","Double-check your token mint address before deploying to production."].join(`
3
- `)}:{isValid:!1,isKnownStablecoin:!1,error:[`SAFETY ERROR: Unrecognized token mint address in ${e}`,` Provided: ${a}`,"","This token mint does not match any known stablecoin addresses.","Using an unknown token mint can result in PERMANENT LOSS OF FUNDS if it's a typo.","","Known stablecoin mints (mainnet-beta):",n,"","If you are CERTAIN this is the correct mint address (custom token, testnet, or new stablecoin),","set dangerouslyAllowUnknownMint={true} in your CedrosProvider config:",""," <CedrosProvider"," config={{"," ...",' tokenMint: "'+a+'",'," dangerouslyAllowUnknownMint: true, // ⚠️ I have verified this mint address"," }}"," />","","⚠️ WARNING: Only enable dangerouslyAllowUnknownMint if you have TRIPLE-CHECKED the mint address."].join(`
4
- `)}}function Rt(t,e="unknown",r=!1){return oe(t,`X402Requirement (resource: ${e})`,r)}const ye=new Set(["mainnet-beta","devnet","testnet"]);function Mt(){if(typeof window<"u"&&window.location)return window.location.origin;throw new Error("serverUrl is required in SSR/Node environments. In browser environments, it defaults to window.location.origin")}function He(t){const e=[];if(t.showCard!==!1){const n=t.stripePublicKey;(typeof n!="string"||n.trim().length===0)&&e.push({field:"stripePublicKey",message:"must be a non-empty string when card payments are enabled (showCard is not false)"})}let a;if(t.serverUrl!==void 0)typeof t.serverUrl!="string"||t.serverUrl.trim().length===0?(e.push({field:"serverUrl",message:"must be a non-empty string when provided"}),a=""):(!t.serverUrl.startsWith("http://")&&!t.serverUrl.startsWith("https://")&&e.push({field:"serverUrl",message:'must start with "http://" or "https://"'}),a=t.serverUrl);else try{a=Mt()}catch(n){e.push({field:"serverUrl",message:n instanceof Error?n.message:"failed to determine default"}),a=""}if(ye.has(t.solanaCluster)||e.push({field:"solanaCluster",message:`must be one of ${Array.from(ye).join(", ")}`}),t.solanaEndpoint!==void 0&&(typeof t.solanaEndpoint!="string"?e.push({field:"solanaEndpoint",message:"must be a string when provided"}):t.solanaEndpoint.trim().length===0?e.push({field:"solanaEndpoint",message:'must be a non-empty string when provided (e.g., "https://api.mainnet-beta.solana.com")'}):!t.solanaEndpoint.startsWith("http://")&&!t.solanaEndpoint.startsWith("https://")&&e.push({field:"solanaEndpoint",message:'must start with "http://" or "https://" (e.g., "https://api.mainnet-beta.solana.com")'})),t.tokenMint&&typeof t.tokenMint!="string"&&e.push({field:"tokenMint",message:"must be a string when provided"}),e.length>0){const n=e.map(i=>`- ${i.field} ${i.message}`).join(`
5
- `);throw new Error(`Invalid Cedros configuration:
6
- ${n}`)}if(t.tokenMint){const n=t.dangerouslyAllowUnknownMint===!0,i=oe(t.tokenMint,"CedrosConfig.tokenMint",n);if(!i.isValid&&i.error)throw new Error(i.error);i.warning&&l().warn(i.warning)}return{...t,serverUrl:a}}const Dt=Object.freeze({surfaceBackground:"rgba(255, 255, 255, 0)",surfaceText:"#111827",surfaceBorder:"rgba(15, 23, 42, 0.08)",stripeBackground:"linear-gradient(135deg, #635bff 0%, #4f46e5 100%)",stripeText:"#ffffff",stripeShadow:"rgba(79, 70, 229, 0.25)",cryptoBackground:"linear-gradient(135deg, #14f195 0%, #9945ff 100%)",cryptoText:"#ffffff",cryptoShadow:"rgba(99, 102, 241, 0.25)",errorBackground:"#fee2e2",errorBorder:"#fca5a5",errorText:"#b91c1c",successBackground:"#dcfce7",successBorder:"#86efac",successText:"#166534",modalOverlay:"rgba(0, 0, 0, 0.5)",modalBackground:"#ffffff",modalBorder:"rgba(15, 23, 42, 0.08)",buttonBorderRadius:"8px",buttonPadding:"0.75rem 1.5rem",buttonFontSize:"1rem",buttonFontWeight:"600"}),Ot=Object.freeze({surfaceBackground:"rgba(17, 24, 39, 0.6)",surfaceText:"#f9fafb",surfaceBorder:"rgba(148, 163, 184, 0.25)",stripeBackground:"linear-gradient(135deg, #4f46e5 0%, #3730a3 100%)",stripeText:"#f5f3ff",stripeShadow:"rgba(99, 102, 241, 0.35)",cryptoBackground:"linear-gradient(135deg, #1dd4a6 0%, #6d28d9 100%)",cryptoText:"#ecfeff",cryptoShadow:"rgba(75, 85, 99, 0.35)",errorBackground:"#7f1d1d",errorBorder:"#fca5a5",errorText:"#fecaca",successBackground:"#14532d",successBorder:"#4ade80",successText:"#bbf7d0",modalOverlay:"rgba(0, 0, 0, 0.75)",modalBackground:"#1f2937",modalBorder:"rgba(148, 163, 184, 0.25)",buttonBorderRadius:"8px",buttonPadding:"0.75rem 1.5rem",buttonFontSize:"1rem",buttonFontWeight:"600"}),It={surfaceBackground:"--cedros-surface-bg",surfaceText:"--cedros-surface-text",surfaceBorder:"--cedros-surface-border",stripeBackground:"--cedros-stripe-bg",stripeText:"--cedros-stripe-text",stripeShadow:"--cedros-stripe-shadow",cryptoBackground:"--cedros-crypto-bg",cryptoText:"--cedros-crypto-text",cryptoShadow:"--cedros-crypto-shadow",errorBackground:"--cedros-error-bg",errorBorder:"--cedros-error-border",errorText:"--cedros-error-text",successBackground:"--cedros-success-bg",successBorder:"--cedros-success-border",successText:"--cedros-success-text",modalOverlay:"--cedros-modal-overlay",modalBackground:"--cedros-modal-bg",modalBorder:"--cedros-modal-border",buttonBorderRadius:"--cedros-button-radius",buttonPadding:"--cedros-button-padding",buttonFontSize:"--cedros-button-font-size",buttonFontWeight:"--cedros-button-font-weight"},se=g.createContext(null);function Ut(t,e){return{...t==="dark"?Ot:Dt,...e}}function Bt(t){const e=Object.entries(t).map(([r,a])=>[It[r],a]);return Object.fromEntries(e)}function _t({initialMode:t="light",overrides:e,unstyled:r=!1,children:a}){const[n,i]=g.useState(t),[o,s]=g.useState(e),c=g.useRef(e);g.useEffect(()=>{if(e===c.current)return;(!e||!c.current?e!==c.current:Object.keys({...e,...c.current}).some(u=>e[u]!==c.current?.[u]))&&(c.current=e,s(e))},[e]);const d=g.useMemo(()=>{const m=Ut(n,o),u=r?{}:Bt(m),y=r?"":`cedros-theme-root cedros-theme cedros-theme--${n}`;return{mode:n,setMode:i,tokens:m,className:y,style:u,unstyled:r}},[n,o,r]);return W.jsx(se.Provider,{value:d,children:a})}function Nt(){const t=g.useContext(se);if(!t)throw new Error("useCedrosTheme must be used within CedrosProvider");return t}function Ft(){return g.useContext(se)}const $={getAdapters:()=>[],cleanup:async()=>{},isInitialized:()=>!1,getId:()=>"stub"};function Lt(){return typeof process<"u"&&process.env.NODE_ENV==="development"?0:2}const qe=g.createContext(null);function Ht({config:t,children:e}){const r=g.useMemo(()=>He(t),[t]),[a,n]=g.useState(null),[i,o]=g.useState($),s=g.useRef($);g.useEffect(()=>{let f=!1;return Promise.resolve().then(()=>require("./walletPool-Ddv33tej.js")).then(({createWalletPool:h})=>{if(f)return;const b=h();s.current=b,o(b)}).catch(h=>{f||(l().error("[CedrosProvider] Wallet pool initialization failed:",h),n("Failed to initialize Cedros provider"))}),()=>{f=!0}},[]);const[c,d]=g.useState(null);g.useEffect(()=>{let f=!1;return Promise.resolve().then(()=>require("./solanaCheck-BS3QTE63.js")).then(({checkSolanaAvailability:h})=>h()).then(h=>{f||(h.available?d(void 0):d(h.error||"Solana dependencies not available"))}).catch(h=>{f||(l().warn("[CedrosProvider] Solana availability check failed:",h),d("Unable to verify Solana availability"))}),()=>{f=!0}},[]),g.useEffect(()=>{const f=r.logLevel??Lt(),h=ve({level:f,prefix:"[CedrosPay]"});Xe(h)},[r.logLevel]),g.useEffect(()=>()=>{const f=s.current;f&&f!==$&&f.cleanup().catch(h=>{l().warn("[CedrosProvider] Wallet pool cleanup failed:",h)})},[]);const[m,u]=g.useState(null);g.useEffect(()=>{let f=!1,h=!1;const b=r.stripePublicKey??"",P=r.serverUrl??"",T=r.solanaCluster,U=r.solanaEndpoint,k=r.dangerouslyAllowUnknownMint;return Ct(b,P,T,U,k).then(I=>{if(f){me(b,P,T,U,k);return}h=!0,u(I)}).catch(I=>{f||(l().error("[CedrosProvider] Manager initialization failed:",I),n("Failed to initialize Cedros provider"))}),()=>{f=!0,h&&me(b,P,T,U,k)}},[r.stripePublicKey,r.serverUrl,r.solanaCluster,r.solanaEndpoint,r.dangerouslyAllowUnknownMint]);const y=g.useMemo(()=>m?{config:r,...m,walletPool:i,solanaError:c}:null,[r,m,i,c]);return a?W.jsx("div",{role:"alert",children:a}):W.jsx(_t,{initialMode:r.theme??"light",overrides:r.themeOverrides,unstyled:r.unstyled??!1,children:y?W.jsx(qe.Provider,{value:y,children:e}):null})}function qt(){const t=g.useContext(qe);if(!t)throw new Error("useCedrosContext must be used within CedrosProvider");return t}exports.CIRCUIT_BREAKER_PRESETS=et;exports.CedrosProvider=Ht;exports.CircuitBreakerOpenError=p;exports.CircuitState=Ee;exports.ERROR_CATEGORIES=Pe;exports.KNOWN_STABLECOINS=J;exports.LogLevel=be;exports.Logger=ae;exports.PaymentError=O;exports.RATE_LIMITER_PRESETS=D;exports.RETRY_PRESETS=C;exports.STABLECOIN_METADATA=Le;exports.createCircuitBreaker=N;exports.createLogger=ve;exports.createRateLimiter=M;exports.fetchWithTimeout=A;exports.formatError=R;exports.gBase64=re;exports.getLogger=l;exports.getUserFriendlyError=Ce;exports.retryWithBackoff=v;exports.useCedrosContext=qt;exports.useCedrosTheme=Nt;exports.useCedrosThemeOptional=Ft;exports.validateConfig=He;exports.validateTokenMint=oe;exports.validateX402Asset=Rt;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),d=require("react"),g=require("./SingleCategorySettings-CRXTMTo5.js"),n=[{id:"logging",label:"Logging",category:"logging",description:"Configure log levels, format, and environment settings."},{id:"metrics",label:"Metrics",category:"metrics",description:"Configure metrics collection and API access for monitoring."},{id:"security",label:"Security",category:"security",description:"Configure CORS, rate limiting, and other security settings."}];function l({serverUrl:r,apiKey:c,authManager:o}){const[s,a]=d.useState("logging"),t=n.find(i=>i.id===s);return e.jsxs("div",{className:"cedros-admin__server-settings",children:[e.jsxs("div",{className:"cedros-admin__page-header",children:[e.jsx("h2",{className:"cedros-admin__page-title",children:"Store Server"}),e.jsx("p",{className:"cedros-admin__page-description",children:"Configure logging, metrics, and security settings."})]}),e.jsx("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:n.map(i=>e.jsx("button",{type:"button",className:`cedros-admin__tab ${s===i.id?"cedros-admin__tab--active":""}`,onClick:()=>a(i.id),children:i.label},i.id))}),e.jsx("div",{style:{marginTop:"1rem"},children:e.jsx(g.SingleCategorySettings,{serverUrl:r,apiKey:c,authManager:o,category:t.category,title:`${t.label} Settings`,description:t.description},t.category)})]})}exports.SettingsSection=l;
@@ -1 +0,0 @@
1
- "use strict";var Se=Object.create;var ue=Object.defineProperty;var Ce=Object.getOwnPropertyDescriptor;var ke=Object.getOwnPropertyNames;var we=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty;var Ae=(t,s,n,i)=>{if(s&&typeof s=="object"||typeof s=="function")for(let r of ke(s))!Te.call(t,r)&&r!==n&&ue(t,r,{get:()=>s[r],enumerable:!(i=Ce(s,r))||i.enumerable});return t};var me=(t,s,n)=>(n=t!=null?Se(we(t)):{},Ae(s||!t||!t.__esModule?ue(n,"default",{value:t,enumerable:!0}):n,t));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),d=require("react"),pe=require("./index-OaWkrl0G.js"),re=require("./configApi-CxEbCAgG.js"),be=[{value:"text",label:"Short Text"},{value:"email",label:"Email"},{value:"phone",label:"Phone"},{value:"address",label:"Address"},{value:"textarea",label:"Long Text"},{value:"dropdown",label:"Dropdown"},{value:"file_upload",label:"File Upload"}],he={fields:[],requiresApproval:!0},E={width:"100%",padding:"0.4rem 0.6rem",border:"1px solid rgba(0,0,0,0.2)",borderRadius:4,fontSize:"0.9rem",boxSizing:"border-box"},O={display:"block",fontSize:"0.8rem",fontWeight:500,marginBottom:4},Y={padding:"0.4rem 1rem",borderRadius:6,border:"1px solid rgba(0,0,0,0.2)",background:"white",cursor:"pointer",fontSize:"0.85rem"};function Ne(){return{id:Math.random().toString(36).slice(2),label:"",fieldType:"text",required:!1,options:[],placeholder:""}}function ge({field:t,onSave:s,onCancel:n}){const[i,r]=d.useState(t),[o,u]=d.useState(""),m=l=>r(h=>({...h,...l})),y=()=>{const l=o.trim();l&&(m({options:[...i.options,l]}),u(""))};return e.jsxs("div",{style:{padding:"0.75rem",border:"1px solid rgba(37,99,235,0.3)",borderRadius:6,background:"#eff6ff",marginTop:6},children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"0.6rem",marginBottom:"0.6rem"},children:[e.jsxs("div",{children:[e.jsx("label",{style:O,children:"Label *"}),e.jsx("input",{style:E,value:i.label,onChange:l=>m({label:l.target.value}),placeholder:"e.g., Full Name"})]}),e.jsxs("div",{children:[e.jsx("label",{style:O,children:"Field Type"}),e.jsx("select",{style:E,value:i.fieldType,onChange:l=>m({fieldType:l.target.value,options:[]}),children:be.map(l=>e.jsx("option",{value:l.value,children:l.label},l.value))})]})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr auto",gap:"0.6rem",alignItems:"end",marginBottom:"0.6rem"},children:[e.jsxs("div",{children:[e.jsx("label",{style:O,children:"Placeholder"}),e.jsx("input",{style:E,value:i.placeholder??"",onChange:l=>m({placeholder:l.target.value}),placeholder:"Optional hint text"})]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:"0.85rem",cursor:"pointer",paddingBottom:2},children:[e.jsx("input",{type:"checkbox",checked:i.required,onChange:l=>m({required:l.target.checked})})," Required"]})]}),i.fieldType==="dropdown"&&e.jsxs("div",{style:{marginBottom:"0.6rem"},children:[e.jsx("label",{style:O,children:"Options"}),i.options.map((l,h)=>e.jsxs("div",{style:{display:"flex",gap:6,marginBottom:4},children:[e.jsx("span",{style:{flex:1,fontSize:"0.85rem",padding:"0.25rem 0.5rem",background:"white",border:"1px solid rgba(0,0,0,0.15)",borderRadius:4},children:l}),e.jsx("button",{type:"button",onClick:()=>m({options:i.options.filter((f,_)=>_!==h)}),style:{padding:"0.2rem 0.5rem",borderRadius:4,border:"1px solid rgba(0,0,0,0.2)",background:"white",cursor:"pointer",fontSize:"0.8rem",color:"#dc2626"},children:"x"})]},h)),e.jsxs("div",{style:{display:"flex",gap:6},children:[e.jsx("input",{style:{...E,flex:1},value:o,onChange:l=>u(l.target.value),onKeyDown:l=>l.key==="Enter"&&(l.preventDefault(),y()),placeholder:"Add option..."}),e.jsx("button",{type:"button",onClick:y,style:Y,children:"Add"})]})]}),e.jsxs("div",{style:{display:"flex",gap:6},children:[e.jsx("button",{type:"button",onClick:()=>s(i),disabled:!i.label.trim(),style:{padding:"0.35rem 1rem",borderRadius:6,border:"none",background:"#2563eb",color:"white",cursor:i.label.trim()?"pointer":"not-allowed",fontSize:"0.85rem",opacity:i.label.trim()?1:.5},children:"Save Field"}),e.jsx("button",{type:"button",onClick:n,style:Y,children:"Cancel"})]})]})}function ze({fields:t,instructions:s}){const n={...E,fontSize:"0.85rem",background:"white",opacity:.6};return e.jsxs("div",{style:{padding:"1rem",border:"1px solid rgba(0,0,0,0.1)",borderRadius:8,background:"rgba(0,0,0,0.02)"},children:[e.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"rgba(0,0,0,0.4)",textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:"0.75rem"},children:"Preview — Redeemer View"}),s&&e.jsx("div",{style:{padding:"0.6rem 0.75rem",background:"#fffbeb",border:"1px solid #fcd34d",borderRadius:6,fontSize:"0.85rem",marginBottom:"0.75rem",color:"#92400e"},children:s}),t.length===0&&e.jsx("div",{style:{fontSize:"0.85rem",color:"rgba(0,0,0,0.35)",fontStyle:"italic"},children:"No fields added yet."}),t.map(i=>e.jsxs("div",{style:{marginBottom:"0.6rem"},children:[e.jsxs("label",{style:{display:"block",fontSize:"0.8rem",fontWeight:500,marginBottom:4},children:[i.label||"Unlabelled field",i.required&&e.jsx("span",{style:{color:"#dc2626",marginLeft:2},children:"*"})]}),i.fieldType==="textarea"&&e.jsx("textarea",{disabled:!0,rows:2,placeholder:i.placeholder??"",style:{...n,resize:"none"}}),i.fieldType==="file_upload"&&e.jsx("div",{style:{padding:"0.5rem",border:"1px dashed rgba(0,0,0,0.25)",borderRadius:4,fontSize:"0.8rem",color:"rgba(0,0,0,0.4)",textAlign:"center"},children:"File upload"}),i.fieldType==="dropdown"&&e.jsxs("select",{disabled:!0,style:n,children:[e.jsx("option",{children:i.placeholder||"Select..."}),i.options.map((r,o)=>e.jsx("option",{children:r},o))]}),!["textarea","file_upload","dropdown"].includes(i.fieldType)&&e.jsx("input",{disabled:!0,type:i.fieldType==="email"?"email":i.fieldType==="phone"?"tel":"text",placeholder:i.placeholder??"",style:n})]},i.id))]})}function Be({value:t,onChange:s}){const n=t!==null,i=t??he,[r,o]=d.useState(null),[u,m]=d.useState(null),[y,l]=d.useState(!1),h=p=>s({...i,...p}),f=()=>{o(null),m(null)},_=p=>{s(p?{...he}:null),f()},b=()=>{const p=Ne();m(p),o("new")},g=p=>{m({...p}),o(p.id)},j=p=>{h({fields:r==="new"?[...i.fields,p]:i.fields.map(C=>C.id===p.id?p:C)}),f()},k=p=>{r===p&&f(),h({fields:i.fields.filter(C=>C.id!==p)})};return e.jsxs("div",{children:[e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer",marginBottom:n?"1rem":4,fontSize:"0.9rem",fontWeight:500},children:[e.jsx("input",{type:"checkbox",checked:n,onChange:p=>_(p.target.checked)}),"Enable Redemption Form"]}),!n&&e.jsx("div",{style:{fontSize:"0.8rem",color:"rgba(0,0,0,0.4)"},children:"No redemption form — token holders cannot request physical redemption."}),n&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:[e.jsxs("div",{children:[e.jsx("label",{style:O,children:"Instructions shown to redeemer"}),e.jsx("textarea",{value:i.instructions??"",onChange:p=>h({instructions:p.target.value||void 0}),placeholder:"Describe requirements, turnaround times, etc.",rows:3,style:{...E,resize:"vertical"}})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"auto 1fr",gap:"1rem",alignItems:"center",padding:"0.6rem 0.75rem",border:"1px solid rgba(0,0,0,0.1)",borderRadius:6,background:"rgba(0,0,0,0.02)"},children:[e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:"0.85rem",cursor:"pointer",whiteSpace:"nowrap"},children:[e.jsx("input",{type:"checkbox",checked:i.requiresApproval,onChange:p=>h({requiresApproval:p.target.checked})})," Requires admin approval"]}),e.jsxs("div",{children:[e.jsx("label",{style:O,children:"Estimated processing days"}),e.jsx("input",{type:"number",min:0,value:i.estimatedProcessingDays??"",onChange:p=>h({estimatedProcessingDays:p.target.value?Number(p.target.value):void 0}),placeholder:"e.g., 5",style:{...E,maxWidth:120}})]})]}),e.jsxs("div",{children:[e.jsxs("div",{style:{fontSize:"0.8rem",fontWeight:500,marginBottom:"0.5rem"},children:["Form Fields (",i.fields.length,")"]}),i.fields.length===0&&r!=="new"&&e.jsx("div",{style:{fontSize:"0.85rem",color:"rgba(0,0,0,0.35)",fontStyle:"italic",marginBottom:"0.5rem"},children:"No fields yet. Add fields below."}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.4rem"},children:[i.fields.map(p=>e.jsxs("div",{children:[e.jsxs("div",{style:{padding:"0.5rem 0.75rem",border:"1px solid rgba(0,0,0,0.1)",borderRadius:6,background:"white",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("span",{style:{fontSize:"0.9rem"},children:p.label||e.jsx("em",{style:{color:"rgba(0,0,0,0.35)"},children:"Unlabelled"})}),e.jsx("span",{style:{padding:"2px 8px",borderRadius:10,background:"#dbeafe",color:"#1d4ed8",fontSize:"0.75rem"},children:be.find(C=>C.value===p.fieldType)?.label??p.fieldType}),p.required&&e.jsx("span",{style:{padding:"2px 8px",borderRadius:10,background:"#fef3c7",color:"#92400e",fontSize:"0.75rem"},children:"required"})]}),e.jsxs("div",{style:{display:"flex",gap:4},children:[e.jsx("button",{type:"button",onClick:()=>g(p),style:{...Y,padding:"0.25rem 0.6rem",fontSize:"0.8rem"},children:"Edit"}),e.jsx("button",{type:"button",onClick:()=>k(p.id),style:{padding:"0.25rem 0.6rem",borderRadius:4,border:"1px solid rgba(220,38,38,0.3)",background:"white",cursor:"pointer",fontSize:"0.8rem",color:"#dc2626"},children:"Delete"})]})]}),r===p.id&&u&&e.jsx(ge,{field:u,onSave:j,onCancel:f})]},p.id)),r==="new"&&u&&e.jsx(ge,{field:u,onSave:j,onCancel:f})]}),r===null&&e.jsx("button",{type:"button",onClick:b,style:{...Y,marginTop:"0.5rem"},children:"+ Add Field"})]}),e.jsxs("div",{children:[e.jsx("button",{type:"button",onClick:()=>l(p=>!p),style:{...Y,background:y?"rgba(0,0,0,0.05)":"white"},children:y?"Hide Preview":"Show Preview"}),y&&e.jsx("div",{style:{marginTop:"0.75rem"},children:e.jsx(ze,{fields:i.fields,instructions:i.instructions})})]})]})]})}const Pe=[{value:"securities",label:"Securities (fungible)"},{value:"commodities",label:"Commodities (fungible)"},{value:"property",label:"Property (non-fungible)"},{value:"collectibles",label:"Collectibles (non-fungible)"}],Me=t=>t==="securities"||t==="commodities";function De({c:t,onDeployPool:s,onEdit:n,onDelete:i}){const r=t.tokenizationConfig,o=Me(r.assetClass);return e.jsxs("div",{style:{padding:"0.75rem 1rem",border:"1px solid rgba(0,0,0,0.1)",borderRadius:8,background:"white"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsxs("div",{children:[e.jsx("strong",{children:t.name}),e.jsx("span",{style:{marginLeft:8,fontSize:"0.8rem",padding:"2px 8px",borderRadius:10,background:o?"#dbeafe":"#fef3c7",color:o?"#1d4ed8":"#92400e"},children:r.assetClass}),r.tokenSymbol&&e.jsx("span",{style:{marginLeft:6,fontSize:"0.8rem",color:"rgba(0,0,0,0.5)"},children:r.tokenSymbol})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:"0.8rem"},children:[r.mintAddress?e.jsx("span",{style:{color:"#16a34a"},children:"Mint initialized"}):e.jsx("span",{style:{color:"rgba(0,0,0,0.4)"},children:"No mint"}),o&&r.mintAddress&&(r.liquidityPoolAddress?e.jsxs("span",{style:{padding:"2px 8px",borderRadius:10,background:"#dcfce7",color:"#15803d",fontSize:"0.75rem"},children:["Pool Active · ",r.liquidityPoolAddress.slice(0,4),"...",r.liquidityPoolAddress.slice(-4)]}):e.jsx("button",{type:"button",onClick:s,style:{padding:0,border:"none",background:"none",color:"#2563eb",cursor:"pointer",fontSize:"0.8rem",textDecoration:"underline"},children:"Deploy Pool"}))]})]}),t.description&&e.jsx("div",{style:{fontSize:"0.85rem",color:"rgba(0,0,0,0.5)",marginTop:4},children:t.description}),e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:6},children:[e.jsxs("div",{style:{display:"flex",gap:"1rem",flexWrap:"wrap",fontSize:"0.8rem",color:"rgba(0,0,0,0.4)"},children:[e.jsxs("span",{children:["Fee: ",r.transferFeeBps," bps"]}),r.treasuryAddress&&e.jsxs("span",{children:["Treasury: ",r.treasuryAddress.slice(0,8),"..."]}),r.allowedJurisdictions?.length>0&&e.jsxs("span",{style:{padding:"1px 7px",borderRadius:10,background:"#f3f4f6",color:"rgba(0,0,0,0.55)"},children:[r.allowedJurisdictions.length," jurisdiction",r.allowedJurisdictions.length!==1?"s":"",": ",r.allowedJurisdictions.join(", ")]})]}),e.jsxs("div",{style:{display:"flex",gap:6},children:[n&&e.jsx("button",{type:"button",onClick:n,style:{padding:"2px 10px",border:"1px solid rgba(0,0,0,0.15)",borderRadius:4,background:"white",cursor:"pointer",fontSize:"0.75rem",color:"#2563eb"},children:"Edit"}),i&&e.jsx("button",{type:"button",onClick:i,style:{padding:"2px 10px",border:"1px solid rgba(0,0,0,0.15)",borderRadius:4,background:"white",cursor:"pointer",fontSize:"0.75rem",color:"#dc2626"},children:"Delete"})]})]})]})}const ne={name:"",description:"",assetClass:"securities",tokenSymbol:"",tokenDecimals:2,transferFeeBps:250,maxTransferFee:500,treasuryAddress:"",regulatoryNotice:"",jurisdictions:"",redemptionConfig:null};function Re({serverUrl:t,apiKey:s,authManager:n,onNavigateToLiquidity:i}){const[r,o]=d.useState([]),[u,m]=d.useState(!0),[y,l]=d.useState(null),[h,f]=d.useState(!1),[_,b]=d.useState(!1),[g,j]=d.useState(ne),[k,p]=d.useState(null),C=d.useCallback(async(c,x)=>{if(n?.isAuthenticated())return n.fetchWithAuth(c,x);const D={"Content-Type":"application/json"};s&&(D["X-API-Key"]=s);const v=await fetch(`${t}${c}`,{...x,headers:{...D,...x?.headers}});if(!v.ok){const N=await v.text().catch(()=>`HTTP ${v.status}`);throw new Error(N)}return v.json()},[t,s,n]),w=d.useCallback(async()=>{try{m(!0),l(null);const c=await C("/admin/collections");o((c.collections||[]).filter(x=>x.tokenizationConfig))}catch(c){l(c instanceof Error?c.message:"Failed to load asset classes")}finally{m(!1)}},[C]);d.useEffect(()=>{w()},[w]);const a=()=>({name:g.name.trim(),description:g.description||void 0,active:!0,productIds:[],tokenizationConfig:{assetClass:g.assetClass,tokenSymbol:g.tokenSymbol||void 0,tokenDecimals:g.tokenDecimals,transferFeeBps:g.transferFeeBps,maxTransferFee:g.maxTransferFee,treasuryAddress:g.treasuryAddress||void 0,regulatoryNotice:g.regulatoryNotice||void 0,allowedJurisdictions:g.jurisdictions?g.jurisdictions.split(",").map(c=>c.trim().toUpperCase()).filter(Boolean):[],redemptionConfig:g.redemptionConfig||void 0}}),S=async()=>{if(g.name.trim()){b(!0),l(null);try{k?await C(`/admin/collections/${encodeURIComponent(k)}`,{method:"PUT",body:JSON.stringify(a())}):await C("/admin/collections",{method:"POST",body:JSON.stringify(a())}),j(ne),f(!1),p(null),await w()}catch(c){l(c instanceof Error?c.message:`Failed to ${k?"update":"create"} asset class`)}finally{b(!1)}}},A=c=>{const x=c.tokenizationConfig;j({name:c.name,description:c.description??"",assetClass:x.assetClass,tokenSymbol:x.tokenSymbol??"",tokenDecimals:x.tokenDecimals,transferFeeBps:x.transferFeeBps,maxTransferFee:x.maxTransferFee,treasuryAddress:x.treasuryAddress??"",regulatoryNotice:x.regulatoryNotice??"",jurisdictions:x.allowedJurisdictions.join(", "),redemptionConfig:null}),p(c.id),f(!0)},T=async c=>{if(window.confirm(`Delete asset class "${c.name}"? This cannot be undone.`)){l(null);try{await C(`/admin/collections/${encodeURIComponent(c.id)}`,{method:"DELETE"}),await w()}catch(x){l(x instanceof Error?x.message:"Failed to delete asset class")}}};return u?e.jsx("div",{style:{padding:"1rem 0",color:"rgba(0,0,0,0.5)"},children:"Loading asset classes..."}):e.jsxs("div",{children:[y&&e.jsx("div",{style:{padding:"0.75rem 1rem",background:"#fef2f2",border:"1px solid #fecaca",borderRadius:6,color:"#dc2626",marginBottom:"1rem",fontSize:"0.9rem"},children:y}),e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1rem"},children:[e.jsxs("h4",{style:{margin:0},children:["Asset Classes (",r.length,")"]}),e.jsx("button",{type:"button",onClick:()=>{f(!h),h&&(p(null),j(ne))},style:{padding:"0.4rem 1rem",borderRadius:6,border:"1px solid rgba(0,0,0,0.2)",background:h?"rgba(0,0,0,0.05)":"white",cursor:"pointer",fontSize:"0.85rem"},children:h?"Cancel":"+ New Asset Class"})]}),h&&e.jsxs("div",{style:{padding:"1rem",border:"1px solid rgba(0,0,0,0.1)",borderRadius:8,marginBottom:"1rem",background:"rgba(0,0,0,0.02)"},children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"0.75rem",marginBottom:"0.75rem"},children:[e.jsxs("div",{children:[e.jsx("label",{style:{display:"block",fontSize:"0.8rem",fontWeight:500,marginBottom:4},children:"Name *"}),e.jsx("input",{type:"text",value:g.name,onChange:c=>j(x=>({...x,name:c.target.value})),placeholder:"e.g., Gold Tokens",style:{width:"100%",padding:"0.4rem 0.6rem",border:"1px solid rgba(0,0,0,0.2)",borderRadius:4,fontSize:"0.9rem"}})]}),e.jsxs("div",{children:[e.jsx("label",{style:{display:"block",fontSize:"0.8rem",fontWeight:500,marginBottom:4},children:"Asset Class *"}),e.jsx("select",{value:g.assetClass,onChange:c=>j(x=>({...x,assetClass:c.target.value})),style:{width:"100%",padding:"0.4rem 0.6rem",border:"1px solid rgba(0,0,0,0.2)",borderRadius:4,fontSize:"0.9rem"},children:Pe.map(c=>e.jsx("option",{value:c.value,children:c.label},c.value))})]})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:"0.75rem",marginBottom:"0.75rem"},children:[e.jsxs("div",{children:[e.jsx("label",{style:{display:"block",fontSize:"0.8rem",fontWeight:500,marginBottom:4},children:"Token Symbol"}),e.jsx("input",{type:"text",value:g.tokenSymbol,onChange:c=>j(x=>({...x,tokenSymbol:c.target.value})),placeholder:"e.g., GOLD",style:{width:"100%",padding:"0.4rem 0.6rem",border:"1px solid rgba(0,0,0,0.2)",borderRadius:4,fontSize:"0.9rem"}})]}),e.jsxs("div",{children:[e.jsx("label",{style:{display:"block",fontSize:"0.8rem",fontWeight:500,marginBottom:4},children:"Transfer Fee (bps)"}),e.jsx("input",{type:"number",value:g.transferFeeBps,onChange:c=>j(x=>({...x,transferFeeBps:Number(c.target.value)})),style:{width:"100%",padding:"0.4rem 0.6rem",border:"1px solid rgba(0,0,0,0.2)",borderRadius:4,fontSize:"0.9rem"}})]}),e.jsxs("div",{children:[e.jsx("label",{style:{display:"block",fontSize:"0.8rem",fontWeight:500,marginBottom:4},children:"Treasury Address"}),e.jsx("input",{type:"text",value:g.treasuryAddress,onChange:c=>j(x=>({...x,treasuryAddress:c.target.value})),placeholder:"Solana address",style:{width:"100%",padding:"0.4rem 0.6rem",border:"1px solid rgba(0,0,0,0.2)",borderRadius:4,fontSize:"0.9rem"}})]})]}),e.jsxs("div",{style:{marginBottom:"0.75rem"},children:[e.jsx("label",{style:{display:"block",fontSize:"0.8rem",fontWeight:500,marginBottom:4},children:"Allowed Jurisdictions"}),e.jsx("input",{type:"text",value:g.jurisdictions,onChange:c=>j(x=>({...x,jurisdictions:c.target.value})),placeholder:"US, CA, GB (comma-separated, leave empty for all)",style:{width:"100%",padding:"0.4rem 0.6rem",border:"1px solid rgba(0,0,0,0.2)",borderRadius:4,fontSize:"0.9rem"}})]}),e.jsxs("div",{style:{marginBottom:"0.75rem"},children:[e.jsx("label",{style:{display:"block",fontSize:"0.8rem",fontWeight:500,marginBottom:4},children:"Regulatory Notice"}),e.jsx("textarea",{value:g.regulatoryNotice,onChange:c=>j(x=>({...x,regulatoryNotice:c.target.value})),placeholder:"Shown to buyers before purchase",rows:2,style:{width:"100%",padding:"0.4rem 0.6rem",border:"1px solid rgba(0,0,0,0.2)",borderRadius:4,fontSize:"0.9rem",resize:"vertical"}})]}),e.jsxs("div",{style:{marginBottom:"0.75rem"},children:[e.jsx("label",{style:{display:"block",fontSize:"0.8rem",fontWeight:600,marginBottom:8},children:"Redemption Form"}),e.jsx(Be,{value:g.redemptionConfig,onChange:c=>j(x=>({...x,redemptionConfig:c}))})]}),e.jsx("button",{type:"button",onClick:S,disabled:_||!g.name.trim(),style:{padding:"0.5rem 1.5rem",borderRadius:6,border:"none",background:"#2563eb",color:"white",cursor:_?"wait":"pointer",fontSize:"0.9rem",opacity:_?.6:1},children:_?"Saving...":k?"Save Changes":"Create Asset Class"})]}),r.length===0?e.jsx("div",{style:{padding:"2rem",textAlign:"center",color:"rgba(0,0,0,0.4)",fontSize:"0.9rem"},children:"No asset classes configured. Create one to start tokenizing off-chain assets."}):e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:r.map(c=>e.jsx(De,{c,onDeployPool:i,onEdit:()=>A(c),onDelete:()=>T(c)},c.id))})]})}const Ie=[{value:"",label:"All statuses"},{value:"pending_info",label:"Pending Info"},{value:"info_submitted",label:"Info Submitted"},{value:"under_review",label:"Under Review"},{value:"approved",label:"Approved"},{value:"completed",label:"Completed"},{value:"rejected",label:"Rejected"}];function Fe(t){switch(t){case"pending_info":return"cedros-admin__badge cedros-admin__badge--muted";case"info_submitted":return"cedros-admin__badge cedros-admin__badge--info";case"under_review":return"cedros-admin__badge cedros-admin__badge--warning";case"approved":return"cedros-admin__badge cedros-admin__badge--success";case"completed":return"cedros-admin__badge cedros-admin__badge--success";case"rejected":return"cedros-admin__badge cedros-admin__badge--failed";default:return"cedros-admin__badge cedros-admin__badge--muted"}}function Le(t){return t.replace(/_/g," ").replace(/\b\w/g,s=>s.toUpperCase())}function Ee(t){return new Date(t).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function q(t){return t.length>12?`${t.slice(0,8)}…`:t}function ye(t){return`https://solscan.io/tx/${t}`}function Oe({redemption:t,onAction:s,onComplete:n,actionBusy:i}){const[r,o]=d.useState(t.adminNotes??""),u=Object.entries(t.formData??{});return e.jsx("div",{style:{padding:"1rem 1.25rem",background:"rgba(0,0,0,0.02)",borderTop:"1px solid rgba(0,0,0,0.08)"},children:e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"1.5rem"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontWeight:600,fontSize:"0.8rem",marginBottom:8,textTransform:"uppercase",letterSpacing:"0.05em",opacity:.6},children:"Form Data"}),u.length===0?e.jsx("div",{style:{fontSize:"0.85rem",opacity:.5},children:"No form data submitted."}):e.jsx("dl",{style:{margin:0,display:"grid",gridTemplateColumns:"auto 1fr",gap:"4px 12px",fontSize:"0.85rem"},children:u.map(([m,y])=>e.jsxs(e.Fragment,{children:[e.jsx("dt",{style:{fontWeight:500,color:"rgba(0,0,0,0.6)",whiteSpace:"nowrap"},children:m},`k-${m}`),e.jsx("dd",{style:{margin:0,wordBreak:"break-word"},children:String(y??"—")},`v-${m}`)]}))}),(t.tokenMintSignature||t.tokenBurnSignature)&&e.jsxs("div",{style:{marginTop:12,fontSize:"0.8rem"},children:[e.jsx("div",{style:{fontWeight:600,marginBottom:4,opacity:.6,textTransform:"uppercase",letterSpacing:"0.05em"},children:"Signatures"}),t.tokenMintSignature&&e.jsxs("div",{children:["Mint:"," ",e.jsx("a",{href:ye(t.tokenMintSignature),target:"_blank",rel:"noopener noreferrer",style:{fontFamily:"monospace",fontSize:"0.75rem"},children:q(t.tokenMintSignature)})]}),t.tokenBurnSignature&&e.jsxs("div",{children:["Burn:"," ",e.jsx("a",{href:ye(t.tokenBurnSignature),target:"_blank",rel:"noopener noreferrer",style:{fontFamily:"monospace",fontSize:"0.75rem"},children:q(t.tokenBurnSignature)})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{style:{display:"block",fontSize:"0.8rem",fontWeight:500,marginBottom:4},children:"Admin Notes"}),e.jsx("textarea",{value:r,onChange:m=>o(m.target.value),rows:4,style:{width:"100%",padding:"0.4rem 0.6rem",border:"1px solid rgba(0,0,0,0.2)",borderRadius:4,fontSize:"0.85rem",resize:"vertical",boxSizing:"border-box"},placeholder:"Internal notes (not shown to user)..."}),e.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginTop:8,flexWrap:"wrap"},children:[t.status==="info_submitted"&&e.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",disabled:i,onClick:()=>s(t.id,"under_review",r),children:i?"Saving...":"Mark Under Review"}),t.status==="under_review"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",disabled:i,onClick:()=>s(t.id,"approved",r),children:i?"Saving...":"Approve"}),e.jsx("button",{className:"cedros-admin__button cedros-admin__button--outline cedros-admin__button--danger cedros-admin__button--sm",disabled:i,onClick:()=>s(t.id,"rejected",r),children:i?"Saving...":"Reject"})]}),t.status==="approved"&&e.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",disabled:i,onClick:()=>n(t.id),children:i?"Processing...":"Complete"})]})]})]})})}function qe({serverUrl:t,apiKey:s,authManager:n}){const[i,r]=d.useState([]),[o,u]=d.useState(!0),[m,y]=d.useState(null),[l,h]=d.useState(""),[f,_]=d.useState(null),[b,g]=d.useState(null),j=d.useCallback(async(a,S)=>{if(n?.isAuthenticated())return n.fetchWithAuth(a,S);const A={"Content-Type":"application/json"};s&&(A["X-API-Key"]=s);const T=await fetch(`${t}${a}`,{...S,headers:{...A,...S?.headers}});if(!T.ok){const c=await T.text().catch(()=>`HTTP ${T.status}`);throw new Error(c)}return T.json()},[t,s,n]),k=d.useCallback(async()=>{u(!0),y(null);try{const a=l?`?status=${encodeURIComponent(l)}&limit=50&offset=0`:"?limit=50&offset=0",S=await j(`/admin/asset-redemptions${a}`);r(S.redemptions??[])}catch(a){y(a instanceof Error?a.message:"Failed to load redemptions")}finally{u(!1)}},[j,l]);d.useEffect(()=>{k()},[k]);const p=d.useCallback(async(a,S,A)=>{g(a),y(null);try{await j(`/admin/asset-redemptions/${a}/status`,{method:"PATCH",body:JSON.stringify({status:S,adminNotes:A})}),_(null),await k()}catch(T){y(T instanceof Error?T.message:"Failed to update status")}finally{g(null)}},[j,k]),C=d.useCallback(async a=>{g(a),y(null);try{await j(`/admin/asset-redemptions/${a}/complete`,{method:"POST"}),_(null),await k()}catch(S){y(S instanceof Error?S.message:"Failed to complete redemption")}finally{g(null)}},[j,k]),w=a=>{_(S=>S===a?null:a)};return e.jsxs("div",{className:"cedros-admin__page",children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",marginBottom:"1rem",flexWrap:"wrap"},children:[e.jsxs("div",{children:[e.jsx("label",{style:{display:"block",fontSize:"0.8rem",fontWeight:500,marginBottom:4},children:"Status"}),e.jsx("select",{value:l,onChange:a=>{h(a.target.value),_(null)},style:{padding:"0.4rem 0.6rem",border:"1px solid rgba(0,0,0,0.2)",borderRadius:4,fontSize:"0.9rem",minWidth:160},children:Ie.map(a=>e.jsx("option",{value:a.value,children:a.label},a.value))})]}),e.jsx("div",{style:{alignSelf:"flex-end"},children:e.jsx("button",{className:"cedros-admin__button cedros-admin__button--outline",onClick:k,disabled:o,children:o?"Loading...":"Refresh"})})]}),m&&e.jsx("div",{style:{padding:"0.75rem 1rem",background:"#fef2f2",border:"1px solid #fecaca",borderRadius:6,color:"#dc2626",marginBottom:"1rem",fontSize:"0.9rem"},children:m}),o?e.jsx("div",{className:"cedros-admin__loading",children:"Loading redemptions..."}):i.length===0?e.jsx("div",{className:"cedros-admin__empty",children:"No redemption requests found."}):e.jsx("div",{className:"cedros-admin__table-container",children:e.jsxs("table",{className:"cedros-admin__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Order"}),e.jsx("th",{children:"Product"}),e.jsx("th",{children:"Collection"}),e.jsx("th",{children:"User"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Actions"})]})}),e.jsx("tbody",{children:i.map(a=>e.jsxs(e.Fragment,{children:[e.jsxs("tr",{style:{cursor:"pointer"},onClick:()=>w(a.id),children:[e.jsx("td",{children:Ee(a.createdAt)}),e.jsx("td",{children:e.jsx("code",{title:a.orderId,children:q(a.orderId)})}),e.jsx("td",{children:e.jsx("code",{title:a.productId,children:q(a.productId)})}),e.jsx("td",{children:e.jsx("code",{title:a.collectionId,children:q(a.collectionId)})}),e.jsx("td",{children:a.userId?e.jsx("code",{title:a.userId,children:q(a.userId)}):e.jsx("span",{style:{opacity:.4},children:"—"})}),e.jsx("td",{children:e.jsx("span",{className:Fe(a.status),children:Le(a.status)})}),e.jsx("td",{onClick:S=>S.stopPropagation(),children:e.jsxs("div",{style:{display:"flex",gap:"0.4rem",flexWrap:"wrap"},children:[(a.status==="info_submitted"||a.status==="under_review"||a.status==="approved")&&e.jsx("button",{className:"cedros-admin__button cedros-admin__button--outline cedros-admin__button--sm",onClick:()=>w(a.id),children:f===a.id?"Close":"Review"}),a.status==="under_review"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",disabled:b===a.id,onClick:()=>p(a.id,"approved",a.adminNotes??""),children:"Approve"}),e.jsx("button",{className:"cedros-admin__button cedros-admin__button--outline cedros-admin__button--danger cedros-admin__button--sm",disabled:b===a.id,onClick:()=>p(a.id,"rejected",a.adminNotes??""),children:"Reject"})]}),a.status==="approved"&&e.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary cedros-admin__button--sm",disabled:b===a.id,onClick:()=>C(a.id),children:b===a.id?"Processing...":"Complete"})]})})]},a.id),f===a.id&&e.jsx("tr",{children:e.jsx("td",{colSpan:7,style:{padding:0},children:e.jsx(Oe,{redemption:a,onAction:p,onComplete:C,actionBusy:b===a.id})})},`${a.id}-detail`)]}))})]})})]})}const $e={CA:{cashOutCents:1500,expirationProhibited:!0,escheatmentYears:3,notes:"Cash-out threshold increases to $15 on April 1, 2026."},CO:{cashOutCents:500,escheatmentYears:5},CT:{cashOutCents:300,escheatmentYears:3},FL:{expirationProhibited:!0,escheatmentYears:5},ME:{cashOutCents:500,escheatmentYears:3},MA:{cashOutCents:500,escheatmentYears:3,notes:"Cash-out also required when 90% of value is used."},MT:{cashOutCents:500,escheatmentYears:5},NJ:{cashOutCents:500,escheatmentYears:3},OR:{cashOutCents:500,escheatmentYears:3,notes:"May require at least one prior transaction."},RI:{cashOutCents:100,escheatmentYears:3},TX:{cashOutCents:250,escheatmentYears:3},VT:{cashOutCents:100,escheatmentYears:3},WA:{cashOutCents:500,escheatmentYears:5},PR:{cashOutCents:500,escheatmentYears:5}},ae={escheatmentYears:5},V=1e6,We={AL:"Alabama",AK:"Alaska",AZ:"Arizona",AR:"Arkansas",CA:"California",CO:"Colorado",CT:"Connecticut",DE:"Delaware",FL:"Florida",GA:"Georgia",HI:"Hawaii",ID:"Idaho",IL:"Illinois",IN:"Indiana",IA:"Iowa",KS:"Kansas",KY:"Kentucky",LA:"Louisiana",ME:"Maine",MD:"Maryland",MA:"Massachusetts",MI:"Michigan",MN:"Minnesota",MS:"Mississippi",MO:"Missouri",MT:"Montana",NE:"Nebraska",NV:"Nevada",NH:"New Hampshire",NJ:"New Jersey",NM:"New Mexico",NY:"New York",NC:"North Carolina",ND:"North Dakota",OH:"Ohio",OK:"Oklahoma",OR:"Oregon",PA:"Pennsylvania",RI:"Rhode Island",SC:"South Carolina",SD:"South Dakota",TN:"Tennessee",TX:"Texas",UT:"Utah",VT:"Vermont",VA:"Virginia",WA:"Washington",WV:"West Virginia",WI:"Wisconsin",WY:"Wyoming",DC:"District of Columbia",PR:"Puerto Rico"};function Ye({serverUrl:t,authManager:s}){const[n,i]=d.useState(null),[r,o]=d.useState(null),[u,m]=d.useState(null),[y,l]=d.useState(!0),h=d.useCallback(async()=>{try{const j=(await new re.ConfigApiClient(t,void 0,s).getConfig("gift_cards")).config??{};i(j.business_state||null),o(j.min_gift_card_value_cents!=null?Number(j.min_gift_card_value_cents):null),m(j.max_gift_card_value_cents!=null?Number(j.max_gift_card_value_cents):null)}catch{}finally{l(!1)}},[t,s]);if(d.useEffect(()=>{h()},[h]),y)return e.jsx("div",{style:{padding:"2rem",textAlign:"center",opacity:.6},children:"Loading compliance data..."});const f=n?$e[n]??ae:null,_=n?We[n]??n:null;return e.jsx("div",{children:n?e.jsxs(e.Fragment,{children:[e.jsxs("h3",{className:"cedros-admin__section-title",style:{marginBottom:"1rem"},children:["Compliance Guidance — ",_]}),e.jsxs("div",{style:{display:"grid",gap:"1rem",maxWidth:720},children:[e.jsx(Ke,{reg:f,minValueCents:r}),e.jsx(He,{reg:f}),e.jsx(Ge,{reg:f}),e.jsx(Je,{maxValueCents:u})]}),e.jsx(Ve,{reg:f,minValueCents:r,maxValueCents:u})]}):e.jsx(Ue,{})})}function Ue(){return e.jsxs("div",{style:{padding:"2rem",textAlign:"center"},children:[e.jsx("p",{style:{fontSize:15,opacity:.7,marginBottom:"0.5rem"},children:"No business state configured."}),e.jsxs("p",{style:{fontSize:13,opacity:.5},children:["Set your ",e.jsx("strong",{children:"business_state"})," in the Gift Cards config category to see state-specific compliance guidance."]})]})}function U({title:t,children:s}){return e.jsxs("div",{style:{border:"1px solid rgba(0,0,0,0.1)",borderRadius:8,padding:"1rem 1.25rem"},children:[e.jsx("h4",{style:{margin:"0 0 0.5rem",fontSize:14,fontWeight:600},children:t}),e.jsx("div",{style:{fontSize:13,lineHeight:1.6},children:s})]})}function Ke({reg:t,minValueCents:s}){if(!t.cashOutCents)return e.jsx(U,{title:"Cash-Out Threshold",children:e.jsx("p",{style:{margin:0},children:"Your state does not have a specific cash-out threshold for gift cards. Federal law does not require cash redemption."})});const n=(t.cashOutCents/100).toFixed(2),i=s!=null&&s>t.cashOutCents;return e.jsxs(U,{title:"Cash-Out Threshold",children:[e.jsxs("p",{style:{margin:"0 0 0.5rem"},children:["Your state requires cash redemption for gift cards with a remaining balance of ",e.jsxs("strong",{children:["$",n]})," or less."]}),e.jsxs("p",{style:{margin:"0 0 0.5rem"},children:["Since this system uses ",e.jsx("strong",{children:"one-shot full redemption"})," (entire gift card value is converted to credits at once), cash-out is avoided by setting the minimum gift card face value above the threshold."]}),i?e.jsxs(X,{ok:!0,children:["Min value ($",((s??0)/100).toFixed(2),") exceeds threshold"]}):e.jsxs(X,{ok:!1,children:["Set ",e.jsx("code",{children:"min_gift_card_value_cents"})," above ",t.cashOutCents," to avoid cash-out obligations"]}),t.notes&&e.jsx("p",{style:{margin:"0.5rem 0 0",opacity:.7,fontStyle:"italic"},children:t.notes})]})}function He({reg:t}){return e.jsx(U,{title:"Expiration Rules",children:t.expirationProhibited?e.jsxs("p",{style:{margin:0},children:["Your state ",e.jsx("strong",{children:"prohibits"})," gift card expiration. Do not set expiration dates on gift cards."]}):e.jsxs("p",{style:{margin:0},children:["Federal law (CARD Act) requires gift cards to remain valid for at least ",e.jsx("strong",{children:"5 years"})," from purchase or last reload. Your state follows the federal minimum."]})})}function Ge({reg:t}){const s=t.escheatmentYears??ae.escheatmentYears;return e.jsxs(U,{title:"Escheatment (Unclaimed Property)",children:[e.jsxs("p",{style:{margin:"0 0 0.5rem"},children:["Gift card balances unredeemed for ",e.jsxs("strong",{children:[s," years"]})," may need to be reported and remitted to the state as unclaimed property."]}),e.jsxs("p",{style:{margin:0,opacity:.7},children:["The system tracks ",e.jsx("code",{children:"last_activity_at"})," on gift card redemptions to help identify dormant balances approaching the escheatment window."]})]})}function Je({maxValueCents:t}){const s=t??V,n=s<=V;return e.jsxs(U,{title:"Anti-Money Laundering (AML)",children:[e.jsxs("p",{style:{margin:"0 0 0.5rem"},children:["FinCEN requires closed-loop prepaid cards to stay at or below ",e.jsx("strong",{children:"$10,000"})," per card. The server enforces this cap on product creation."]}),n?e.jsxs(X,{ok:!0,children:["Max value ($",(s/100).toFixed(2),") within AML limit"]}):e.jsxs(X,{ok:!1,children:[e.jsx("code",{children:"max_gift_card_value_cents"})," exceeds $10,000 AML cap"]})]})}function X({ok:t,children:s}){return e.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:6,padding:"4px 10px",borderRadius:6,fontSize:13,fontWeight:500,background:t?"rgba(34,197,94,0.1)":"rgba(234,179,8,0.15)",color:t?"#16a34a":"#a16207"},children:[e.jsx("span",{children:t?"✓":"⚠"}),s]})}function Ve({reg:t,minValueCents:s,maxValueCents:n}){const r=[{label:"AML: Max card value ≤ $10,000",ok:(n??V)<=V},...t.cashOutCents?[{label:`Cash-out: Min value > $${(t.cashOutCents/100).toFixed(2)} threshold`,ok:s!=null&&s>t.cashOutCents}]:[],{label:t.expirationProhibited?"Expiration: State prohibits expiration (no action needed)":"Expiration: Federal 5-year minimum applies",ok:!0},{label:`Escheatment: ${t.escheatmentYears??ae.escheatmentYears}-year dormancy tracking enabled`,ok:!0}];return e.jsxs("div",{style:{marginTop:"1.5rem"},children:[e.jsx("h4",{style:{fontSize:14,fontWeight:600,marginBottom:"0.75rem"},children:"Compliance Checklist"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:r.map((o,u)=>e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13},children:[e.jsx("span",{style:{color:o.ok?"#16a34a":"#d97706",fontWeight:600},children:o.ok?"✓":"⚠"}),e.jsx("span",{children:o.label})]},u))})]})}const Xe=0;class Ze{dlmmModule=null;bnClass=null;keypairClass=null;async loadDLMM(){if(this.dlmmModule)return this.dlmmModule;try{const s=await Promise.resolve().then(()=>require("./pay-react_false-DaeIe3_l.js"));return this.dlmmModule=s.default??s,this.dlmmModule}catch{throw new Error("Install @meteora-ag/dlmm to enable pool deployment: npm install @meteora-ag/dlmm")}}async loadBN(){if(this.bnClass)return this.bnClass;const s=await Promise.resolve().then(()=>require("./bn-CHyy7EgJ.js")).then(n=>n.bn);return this.bnClass=s.default??s,this.bnClass}async loadKeypair(){if(this.keypairClass)return this.keypairClass;const{Keypair:s}=await import("@solana/web3.js");return this.keypairClass=s,this.keypairClass}async computeBinId(s,n,i,r=1){const o=await this.loadDLMM(),u=o.getPricePerLamport(n,i,s);return o.getBinIdFromPrice(u,r,!0)}async findPresetParameter(s,n,i){const r=await this.loadDLMM(),o=i?{cluster:i}:void 0,{presetParameter2:u}=await r.getAllPresetParameters(s,o),m=u.find(y=>y.account.binStep===n);if(!m)throw new Error(`No PresetParameter2 found for binStep=${n}. Available: ${u.map(y=>y.account.binStep).join(", ")}`);return m.publicKey}async createPool(s,n,i,r,o,u=1,m){const y=await this.loadDLMM(),l=await this.loadBN(),h=m?{cluster:m}:void 0,f=await this.findPresetParameter(s,u,m),_=await y.createLbPair2(s,n,i,r,f,new l(o),h),b=_.instructions[0]?.keys?.[1]?.pubkey;if(!b)throw new Error("Failed to extract pool address from transaction");return{transaction:_,poolAddress:b}}async addBuybackLiquidity(s,n,i,r,o,u){const m=await this.loadDLMM(),y=await this.loadBN(),l=await this.loadKeypair(),h=u?{cluster:u}:void 0,f=await m.create(s,i,h),_=l.generate(),b=o-1,g=o;return{transaction:await f.initializePositionAndAddLiquidityByStrategy({positionPubKey:_.publicKey,totalXAmount:new y(0),totalYAmount:new y(r),strategy:{maxBinId:g,minBinId:b,strategyType:Xe},user:n,slippage:1}),positionKeypair:_}}async getPoolStatus(s,n,i){const r=await this.loadDLMM(),o=i?{cluster:i}:void 0,u=await r.create(s,n,o),m=await u.getActiveBin();return{address:n.toBase58(),activeBinId:m.binId,activeBinPrice:m.price,binStep:u.lbPair.binStep}}}const W=6,ie=1,Qe="https://solscan.io/account",et="https://app.meteora.ag/dlmm";function tt({serverUrl:t,authManager:s,mintConfigured:n,mintAddress:i,tokenDecimals:r=2}){const[o,u]=d.useState({liquidityPoolAddress:null,buybackRateBps:null,rpcUrl:null,usdcMint:null,usdcAmount:null,deployedAt:null}),[m,y]=d.useState(!0),[l,h]=d.useState(80),[f,_]=d.useState(250),[b,g]=d.useState("idle"),[j,k]=d.useState(null),[p,C]=d.useState(null),[w,a]=d.useState(null),S=d.useRef(new Ze),A=d.useCallback(async()=>{try{const z=new re.ConfigApiClient(t,void 0,s),[R,F]=await Promise.all([z.getConfig("gift_cards"),z.getConfig("x402")]),B=R.config??{},P=F.config??{},M=B.liquidity_pool_address||null;u({liquidityPoolAddress:M,buybackRateBps:B.buyback_rate_bps!=null?Number(B.buyback_rate_bps):null,rpcUrl:P.rpc_url||null,usdcMint:P.token_mint||null,usdcAmount:B.liquidity_usdc_amount!=null?Number(B.liquidity_usdc_amount):null,deployedAt:B.liquidity_deployed_at||null}),M&&C(M),B.buyback_rate_bps!=null&&h(Number(B.buyback_rate_bps)/100)}catch{}finally{y(!1)}},[t,s]);d.useEffect(()=>{A()},[A]);const T=typeof window<"u"&&!!window.solana?.publicKey,c=!!o.rpcUrl,x=!!o.usdcMint,D=n&&T&&c&&x&&b==="idle",v=async z=>{if(!(!i||!o.rpcUrl||!o.usdcMint)){g(z),k(null),a(null);try{const{Connection:R,PublicKey:F,Keypair:B}=await import("@solana/web3.js"),P=new R(o.rpcUrl,"confirmed"),M=window.solana;if(!M?.publicKey||!M.signTransaction)throw new Error("Wallet not connected");const H=S.current,oe=new F(M.publicKey.toBase58()),je=l/100,ve=await H.computeBinId(je,r,W,ie);let L=p;if(z==="creating_pool"){const $=new F(i),Z=new F(o.usdcMint),G=await H.computeBinId(1,r,W,ie),{transaction:Q,poolAddress:ee}=await H.createPool(P,oe,$,Z,G,ie),te=await M.signTransaction(Q),se=await P.sendRawTransaction(te.serialize());await P.confirmTransaction(se,"confirmed"),L=ee.toBase58(),C(L)}if(z==="creating_pool"||z==="adding_liquidity"){if(g("adding_liquidity"),!L)throw new Error("Pool address not available");const $=new F(L),Z=Math.round(f*10**W),{transaction:G,positionKeypair:Q}=await H.addBuybackLiquidity(P,oe,$,Z,ve),ee=B.fromSecretKey(Q.secretKey);G.partialSign(ee);const te=await M.signTransaction(G),se=await P.sendRawTransaction(te.serialize());await P.confirmTransaction(se,"confirmed")}if(g("saving_config"),!L)throw new Error("Pool address not available");const _e=new re.ConfigApiClient(t,void 0,s),le=Math.round(l*100),de=Math.round(f*10**W),ce=new Date().toISOString();await _e.patchConfig("gift_cards",{liquidity_pool_address:L,buyback_rate_bps:le,liquidity_usdc_amount:de,liquidity_deployed_at:ce},"Meteora DLMM pool deployed for gift card buyback"),u($=>({...$,liquidityPoolAddress:L,buybackRateBps:le,usdcAmount:de,deployedAt:ce})),g("done")}catch(R){a(b==="idle"?z:b),k(R instanceof Error?R.message:"Deployment failed"),g("error")}}},N=()=>{D&&v("creating_pool")},K=()=>{!w||w==="idle"||w==="done"||w==="error"||v(w)};return m?e.jsx("div",{style:{padding:"2rem",textAlign:"center",opacity:.6},children:"Loading pool configuration..."}):o.liquidityPoolAddress?e.jsx(it,{poolAddress:o.liquidityPoolAddress,buybackRateBps:o.buybackRateBps,usdcAmount:o.usdcAmount,deployedAt:o.deployedAt}):b!=="idle"&&b!=="error"?e.jsx(nt,{step:b,poolAddress:p}):e.jsx(st,{buybackCents:l,setBuybackCents:h,usdcAmount:f,setUsdcAmount:_,mintConfigured:n,walletConnected:T,hasRpcUrl:c,hasUsdcMint:x,canDeploy:D,onDeploy:N,errorMessage:j,canRetry:!!w&&w!=="creating_pool",onRetry:K})}function st({buybackCents:t,setBuybackCents:s,usdcAmount:n,setUsdcAmount:i,mintConfigured:r,walletConnected:o,hasRpcUrl:u,hasUsdcMint:m,canDeploy:y,onDeploy:l,errorMessage:h,canRetry:f,onRetry:_}){const b=((100-t)/100).toFixed(2);return e.jsxs("div",{children:[e.jsx("h3",{className:"cedros-admin__section-title",style:{marginBottom:"0.5rem"},children:"Deploy Buyback Liquidity Pool"}),e.jsx("p",{style:{opacity:.7,marginBottom:"1rem",fontSize:14},children:"Create a Meteora DLMM pool to buy back gift card tokens at a discount. You earn the spread when tokens are resold at face value."}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Buyback rate (cents per $1.00)"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:t,onChange:g=>s(Math.max(1,Math.min(99,parseInt(g.target.value)||80))),min:"1",max:"99"}),e.jsxs("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:["You earn $",b," profit per gift card redeemed"]})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"USDC amount"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:n,onChange:g=>i(Math.max(1,parseFloat(g.target.value)||250)),min:"1",step:"1"}),e.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"Minimum recommended: $250"})]})]}),e.jsxs("div",{style:{margin:"1rem 0",display:"flex",flexDirection:"column",gap:6},children:[e.jsx(J,{label:"Token-22 mint initialized",met:r}),e.jsx(J,{label:"Wallet connected",met:o}),e.jsx(J,{label:"RPC URL configured",met:u}),e.jsx(J,{label:"USDC mint configured",met:m})]}),h&&e.jsx("div",{style:{padding:"0.5rem 0.75rem",marginBottom:"0.75rem",borderRadius:6,background:"rgba(239,68,68,0.1)",color:"#dc2626",fontSize:13},children:h}),e.jsx("div",{style:{display:"flex",gap:"0.75rem",alignItems:"center"},children:f?e.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary",onClick:_,children:"Retry (Resume from Failed Step)"}):e.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary",onClick:l,disabled:!y,children:"Deploy Liquidity Pool"})})]})}const xe=[{key:"creating_pool",label:"Creating DLMM pool..."},{key:"adding_liquidity",label:"Depositing USDC liquidity..."},{key:"saving_config",label:"Saving configuration..."},{key:"done",label:"Complete"}];function nt({step:t,poolAddress:s}){return e.jsxs("div",{children:[e.jsx("h3",{className:"cedros-admin__section-title",style:{marginBottom:"1rem"},children:"Deploying Pool..."}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10},children:xe.map((n,i)=>{const r=xe.findIndex(y=>y.key===t),o=i,u=o<r||t==="done",m=o===r&&t!=="done";return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:14},children:[e.jsx("span",{style:{width:20,textAlign:"center",fontWeight:600},children:u?"✓":m?"▶":"○"}),e.jsx("span",{style:{opacity:u||m?1:.4},children:n.label})]},n.key)})}),s&&e.jsxs("div",{style:{marginTop:"1rem",fontSize:13,opacity:.7},children:["Pool: ",e.jsx("code",{style:{fontSize:12},children:s})]})]})}function it({poolAddress:t,buybackRateBps:s,usdcAmount:n,deployedAt:i}){const r=s!=null?`$${(s/1e4).toFixed(2)}`:"Unknown",o=n!=null?`$${(n/10**W).toFixed(2)}`:null,u=i?new Date(i).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"}):null,m=t.length>16?`${t.slice(0,8)}...${t.slice(-8)}`:t;return e.jsxs("div",{children:[e.jsx("h3",{className:"cedros-admin__section-title",style:{marginBottom:"1rem"},children:"Liquidity Pool Active"}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"0.75rem",maxWidth:600},children:[e.jsx("div",{style:{fontWeight:500,fontSize:13},children:"Pool Address"}),e.jsxs("div",{style:{fontSize:13,fontFamily:"monospace",wordBreak:"break-all"},children:[m,e.jsxs("span",{style:{marginLeft:8,display:"inline-flex",gap:6},children:[e.jsx(rt,{text:t}),e.jsx(fe,{href:`${Qe}/${t}`,label:"Solscan"}),e.jsx(fe,{href:`${et}/${t}`,label:"Meteora"})]})]}),e.jsx("div",{style:{fontWeight:500,fontSize:13},children:"Buyback Rate"}),e.jsxs("div",{style:{fontSize:13},children:[r," per $1.00"]}),o&&e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{fontWeight:500,fontSize:13},children:"USDC Deposited"}),e.jsx("div",{style:{fontSize:13},children:o})]}),u&&e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{fontWeight:500,fontSize:13},children:"Deployed"}),e.jsx("div",{style:{fontSize:13},children:u})]})]})]})}function J({label:t,met:s}){return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13},children:[e.jsx("span",{style:{color:s?"#16a34a":"#dc2626",fontWeight:600},children:s?"✓":"✗"}),e.jsx("span",{style:{opacity:s?.8:.5},children:t})]})}function rt({text:t}){const[s,n]=d.useState(!1),i=()=>{navigator.clipboard.writeText(t).then(()=>{n(!0),setTimeout(()=>n(!1),1500)})};return e.jsx("button",{type:"button",onClick:i,style:{background:"none",border:"none",cursor:"pointer",fontSize:12,opacity:.7,padding:0},children:s?"Copied":"Copy"})}function fe({href:t,label:s}){return e.jsx("a",{href:t,target:"_blank",rel:"noopener noreferrer",style:{fontSize:12,opacity:.7},children:s})}function at({serverUrl:t,apiKey:s,authManager:n}){const[i,r]=d.useState(null),[o,u]=d.useState([]),[m,y]=d.useState(!0),[l,h]=d.useState(null),[f,_]=d.useState("mint"),[b,g]=d.useState({treasuryAddress:"",tokenSymbol:"storeUSD",tokenDecimals:2,transferFeeBps:250,maxTransferFee:500}),[j,k]=d.useState(!1),[p,C]=d.useState(!1),[w,a]=d.useState(null),S=d.useCallback(async(v,N)=>{if(n?.isAuthenticated())return n.fetchWithAuth(v,N);const K={"Content-Type":"application/json"};s&&(K["X-API-Key"]=s);const z=await fetch(`${t}${v}`,{...N,headers:{...K,...N?.headers}});if(!z.ok){const R=await z.text().catch(()=>`HTTP ${z.status}`);throw new Error(R)}return z.json()},[t,s,n]),A=d.useCallback(async()=>{try{h(null);const v=await S("/admin/token22/status");r(v)}catch{h("Failed to load Token-22 status")}finally{y(!1)}},[S]),T=d.useCallback(async()=>{try{const v=await S("/admin/gift-card-redemptions?limit=50");u(v.redemptions||[])}catch{u([])}},[S]);d.useEffect(()=>{A(),T()},[A,T]);const c=async v=>{if(v.preventDefault(),!!b.treasuryAddress){k(!0),a(null);try{const N=await S("/admin/token22/initialize",{method:"POST",body:JSON.stringify({treasuryAddress:b.treasuryAddress,tokenSymbol:b.tokenSymbol,tokenDecimals:b.tokenDecimals,transferFeeBps:b.transferFeeBps,maxTransferFee:b.maxTransferFee})});a(`Mint created: ${N.mintAddress}`),A()}catch(N){a(`Error: ${N instanceof Error?N.message:"Failed to initialize"}`)}finally{k(!1)}}},x=async()=>{C(!0),a(null);try{const v=await S("/admin/token22/harvest-fees",{method:"POST"});a(v.message)}catch(v){a(`Error: ${v instanceof Error?v.message:"Failed to harvest"}`)}finally{C(!1)}},D=v=>{try{return new Date(v).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return v}};return e.jsxs("div",{className:"cedros-admin__page",children:[e.jsx(pe.ErrorBanner,{message:l,onRetry:A}),e.jsx("div",{style:{display:"flex",gap:0,borderBottom:"1px solid rgba(0,0,0,0.1)",marginBottom:"1rem"},children:["mint","redemptions","compliance","liquidity","asset-classes","asset-redemptions"].map(v=>{const N={mint:"Token-22 Mint",redemptions:"Gift Card Redemptions",compliance:"Compliance",liquidity:"Liquidity","asset-classes":"Asset Classes","asset-redemptions":"Asset Redemptions"};return e.jsx("button",{type:"button",onClick:()=>_(v),style:{padding:"0.5rem 1rem",background:"none",border:"none",borderBottom:f===v?"2px solid currentColor":"2px solid transparent",fontWeight:f===v?600:400,cursor:"pointer",opacity:f===v?1:.6},children:N[v]},v)})}),m?e.jsxs("div",{className:"cedros-admin__loading",children:[pe.Icons.loading," Loading..."]}):f==="mint"?e.jsx(ot,{mintStatus:i,initForm:b,setInitForm:g,isInitializing:j,isHarvesting:p,actionMessage:w,onInitialize:c,onHarvestFees:x,formatDate:D}):f==="redemptions"?e.jsx(lt,{redemptions:o,formatDate:D}):f==="compliance"?e.jsx(Ye,{serverUrl:t,apiKey:s,authManager:n}):f==="liquidity"?e.jsx(tt,{serverUrl:t,authManager:n,mintConfigured:!!i?.configured,mintAddress:i?.mintAddress,tokenDecimals:i?.tokenDecimals}):f==="asset-classes"?e.jsx(Re,{serverUrl:t,apiKey:s,authManager:n,onNavigateToLiquidity:()=>_("liquidity")}):e.jsx(qe,{serverUrl:t,apiKey:s,authManager:n})]})}function ot({mintStatus:t,initForm:s,setInitForm:n,isInitializing:i,isHarvesting:r,actionMessage:o,onInitialize:u,onHarvestFees:m,formatDate:y}){return t?.configured?e.jsxs("div",{children:[e.jsx("h3",{className:"cedros-admin__section-title",style:{marginBottom:"1rem"},children:"Token-22 Mint Status"}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"0.75rem",maxWidth:600},children:[e.jsx(I,{label:"Mint Address",value:t.mintAddress,mono:!0}),e.jsx(I,{label:"Token Symbol",value:t.tokenSymbol}),e.jsx(I,{label:"Decimals",value:String(t.tokenDecimals)}),e.jsx(I,{label:"Transfer Fee",value:`${t.transferFeeBps} bps (${((t.transferFeeBps??0)/100).toFixed(2)}%)`}),e.jsx(I,{label:"Max Transfer Fee",value:String(t.maxTransferFee)}),e.jsx(I,{label:"Treasury",value:t.treasuryAddress,mono:!0}),e.jsx(I,{label:"Authority",value:t.mintAuthority,mono:!0}),e.jsx(I,{label:"Created",value:t.createdAt?y(t.createdAt):"—"})]}),e.jsxs("div",{style:{marginTop:"1.5rem",display:"flex",gap:"0.75rem",alignItems:"center"},children:[e.jsx("button",{className:"cedros-admin__button cedros-admin__button--primary",onClick:m,disabled:r,children:r?"Harvesting...":"Harvest Transfer Fees"}),o&&e.jsx("span",{style:{fontSize:13,opacity:.8},children:o})]})]}):e.jsxs("div",{children:[e.jsx("h3",{className:"cedros-admin__section-title",style:{marginBottom:"0.5rem"},children:"Initialize Token-22 Mint"}),e.jsx("p",{style:{opacity:.7,marginBottom:"1rem",fontSize:14},children:"Create a Token-22 mint with transfer fee extension for the secondary market. This is a one-time operation per tenant."}),e.jsxs("form",{onSubmit:u,children:[e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Treasury address (Solana)"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.treasuryAddress,onChange:l=>n(h=>({...h,treasuryAddress:l.target.value})),placeholder:"e.g., 7xKX...",required:!0})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Token symbol"}),e.jsx("input",{type:"text",className:"cedros-admin__input",value:s.tokenSymbol,onChange:l=>n(h=>({...h,tokenSymbol:l.target.value})),placeholder:"storeUSD"})]})]}),e.jsxs("div",{className:"cedros-admin__form-row",children:[e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Token decimals"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:s.tokenDecimals,onChange:l=>n(h=>({...h,tokenDecimals:parseInt(l.target.value)||2})),min:"0",max:"9"})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Transfer fee (basis points)"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:s.transferFeeBps,onChange:l=>n(h=>({...h,transferFeeBps:parseInt(l.target.value)||0})),min:"0",max:"10000"}),e.jsx("div",{style:{marginTop:4,fontSize:12,opacity:.75},children:"e.g., 250 = 2.5% fee on secondary market transfers"})]}),e.jsxs("div",{className:"cedros-admin__field",children:[e.jsx("label",{className:"cedros-admin__field-label",children:"Max transfer fee (atomic)"}),e.jsx("input",{type:"number",className:"cedros-admin__input",value:s.maxTransferFee,onChange:l=>n(h=>({...h,maxTransferFee:parseInt(l.target.value)||0})),min:"0"})]})]}),e.jsxs("div",{className:"cedros-admin__form-actions",style:{marginTop:"1rem"},children:[e.jsx("button",{type:"submit",className:"cedros-admin__button cedros-admin__button--primary",disabled:i,children:i?"Creating Mint...":"Initialize Mint"}),o&&e.jsx("span",{style:{marginLeft:"0.75rem",fontSize:13,opacity:.8},children:o})]})]})]})}function I({label:t,value:s,mono:n}){return e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{fontWeight:500,fontSize:13},children:t}),e.jsx("div",{style:{fontSize:13,fontFamily:n?"monospace":"inherit",wordBreak:n?"break-all":"normal",opacity:s?1:.5},children:s||"—"})]})}function lt({redemptions:t,formatDate:s}){return t.length?e.jsx("div",{className:"cedros-admin__table-container",children:e.jsxs("table",{className:"cedros-admin__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Order"}),e.jsx("th",{children:"Product"}),e.jsx("th",{children:"Buyer"}),e.jsx("th",{children:"Recipient"}),e.jsx("th",{children:"Value"}),e.jsx("th",{children:"Token Minted"})]})}),e.jsx("tbody",{children:t.map(n=>e.jsxs("tr",{children:[e.jsx("td",{style:{whiteSpace:"nowrap"},children:s(n.createdAt)}),e.jsx("td",{children:e.jsxs("code",{style:{fontSize:12},children:[n.orderId.slice(0,8),"..."]})}),e.jsx("td",{children:e.jsx("code",{style:{fontSize:12},children:n.productId})}),e.jsx("td",{children:e.jsxs("code",{style:{fontSize:12},children:[n.buyerUserId.slice(0,8),"..."]})}),e.jsx("td",{children:e.jsxs("code",{style:{fontSize:12},children:[n.recipientUserId.slice(0,8),"..."]})}),e.jsxs("td",{children:["$",(n.faceValueCents/100).toFixed(2)," ",n.currency.toUpperCase()]}),e.jsx("td",{children:e.jsx("span",{className:`cedros-admin__badge ${n.tokenMinted?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:n.tokenMinted?"Yes":"No"})})]},n.id))})]})}):e.jsx("div",{style:{padding:"2rem",textAlign:"center",opacity:.6},children:"No gift card redemptions yet."})}exports.Token22Section=at;