@cedros/pay-react 1.1.10 → 1.1.11
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.
- package/dist/components/admin/AdminAuthManager.d.ts +2 -3
- package/dist/components/admin/AdminAuthManager.d.ts.map +1 -1
- package/dist/crypto-only.js +1 -1
- package/dist/crypto-only.mjs +2 -2
- package/dist/{index-DYo2l9pp.mjs → index-9OMDKaoz.mjs} +7 -8
- package/dist/{index-Cw-f8RN3.js → index-Dhf-hhsE.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{sections-DxzkNp5I.js → sections-B7ONQqXM.js} +1 -1
- package/dist/{sections-DJa_VfWh.mjs → sections-CEm-cWUI.mjs} +1 -1
- package/dist/stripe-only.js +1 -1
- package/dist/stripe-only.mjs +1 -1
- package/package.json +1 -1
|
@@ -44,7 +44,7 @@ export interface IAdminAuthManager {
|
|
|
44
44
|
/** Set wallet signer for wallet-based auth */
|
|
45
45
|
setWalletSigner(signer: WalletSigner | null): void;
|
|
46
46
|
/** Set cedros-login JWT for JWT-based auth */
|
|
47
|
-
setCedrosLoginAuth(token: string | null, isAdmin
|
|
47
|
+
setCedrosLoginAuth(token: string | null, isAdmin?: boolean): void;
|
|
48
48
|
/** Create auth headers for admin request */
|
|
49
49
|
createAuthHeaders(purpose: string): Promise<AdminAuthHeaders | JwtAuthHeaders>;
|
|
50
50
|
/** Fetch with admin auth headers */
|
|
@@ -60,12 +60,11 @@ export declare class AdminAuthManager implements IAdminAuthManager {
|
|
|
60
60
|
private readonly serverUrl;
|
|
61
61
|
private walletSigner;
|
|
62
62
|
private jwtToken;
|
|
63
|
-
private isAdmin;
|
|
64
63
|
constructor(serverUrl: string);
|
|
65
64
|
getAuthMethod(): AdminAuthMethod;
|
|
66
65
|
isAuthenticated(): boolean;
|
|
67
66
|
setWalletSigner(signer: WalletSigner | null): void;
|
|
68
|
-
setCedrosLoginAuth(token: string | null,
|
|
67
|
+
setCedrosLoginAuth(token: string | null, _isAdmin?: boolean): void;
|
|
69
68
|
createAuthHeaders(purpose: string): Promise<AdminAuthHeaders | JwtAuthHeaders>;
|
|
70
69
|
private createWalletAuthHeaders;
|
|
71
70
|
private createJwtAuthHeaders;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AdminAuthManager.d.ts","sourceRoot":"","sources":["../../../src/components/admin/AdminAuthManager.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAMH,uBAAuB;AACvB,MAAM,MAAM,eAAe,GAAG,QAAQ,GAAG,cAAc,GAAG,MAAM,CAAC;AAQjE,6BAA6B;AAC7B,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,eAAe,CAAC;IACxB,iDAAiD;IACjD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,uCAAuC;IACvC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,yDAAyD;IACzD,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,yDAAyD;AACzD,MAAM,WAAW,YAAY;IAC3B,SAAS,EAAE;QAAE,OAAO,IAAI,UAAU,CAAA;KAAE,GAAG,IAAI,CAAC;IAC5C,WAAW,CAAC,CAAC,OAAO,EAAE,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;CACxD;AAED,0CAA0C;AAC1C,MAAM,WAAW,gBAAgB;IAC/B,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,EAAE,MAAM,CAAC;CACvB;AAED,wCAAwC;AACxC,MAAM,WAAW,cAAc;IAC7B,eAAe,EAAE,MAAM,CAAC;CACzB;AAED,iDAAiD;AACjD,MAAM,WAAW,iBAAiB;IAChC,8BAA8B;IAC9B,aAAa,IAAI,eAAe,CAAC;IAEjC,6BAA6B;IAC7B,eAAe,IAAI,OAAO,CAAC;IAE3B,8CAA8C;IAC9C,eAAe,CAAC,MAAM,EAAE,YAAY,GAAG,IAAI,GAAG,IAAI,CAAC;IAEnD,8CAA8C;IAC9C,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"AdminAuthManager.d.ts","sourceRoot":"","sources":["../../../src/components/admin/AdminAuthManager.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAMH,uBAAuB;AACvB,MAAM,MAAM,eAAe,GAAG,QAAQ,GAAG,cAAc,GAAG,MAAM,CAAC;AAQjE,6BAA6B;AAC7B,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,eAAe,CAAC;IACxB,iDAAiD;IACjD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,uCAAuC;IACvC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,yDAAyD;IACzD,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,yDAAyD;AACzD,MAAM,WAAW,YAAY;IAC3B,SAAS,EAAE;QAAE,OAAO,IAAI,UAAU,CAAA;KAAE,GAAG,IAAI,CAAC;IAC5C,WAAW,CAAC,CAAC,OAAO,EAAE,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;CACxD;AAED,0CAA0C;AAC1C,MAAM,WAAW,gBAAgB;IAC/B,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,EAAE,MAAM,CAAC;CACvB;AAED,wCAAwC;AACxC,MAAM,WAAW,cAAc;IAC7B,eAAe,EAAE,MAAM,CAAC;CACzB;AAED,iDAAiD;AACjD,MAAM,WAAW,iBAAiB;IAChC,8BAA8B;IAC9B,aAAa,IAAI,eAAe,CAAC;IAEjC,6BAA6B;IAC7B,eAAe,IAAI,OAAO,CAAC;IAE3B,8CAA8C;IAC9C,eAAe,CAAC,MAAM,EAAE,YAAY,GAAG,IAAI,GAAG,IAAI,CAAC;IAEnD,8CAA8C;IAC9C,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,EAAE,OAAO,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC;IAElE,4CAA4C;IAC5C,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,GAAG,cAAc,CAAC,CAAC;IAE/E,oCAAoC;IACpC,aAAa,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CACnE;AAED;;;;;GAKG;AACH,qBAAa,gBAAiB,YAAW,iBAAiB;IACxD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,YAAY,CAA6B;IACjD,OAAO,CAAC,QAAQ,CAAuB;gBAE3B,SAAS,EAAE,MAAM;IAI7B,aAAa,IAAI,eAAe;IAUhC,eAAe,IAAI,OAAO;IAI1B,eAAe,CAAC,MAAM,EAAE,YAAY,GAAG,IAAI,GAAG,IAAI;IAKlD,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,EAAE,QAAQ,CAAC,EAAE,OAAO,GAAG,IAAI;IAK5D,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,GAAG,cAAc,CAAC;YActE,uBAAuB;IAuBrC,OAAO,CAAC,oBAAoB;YAUd,UAAU;IAkBlB,aAAa,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,WAAgB,GAAG,OAAO,CAAC,CAAC,CAAC;IA8B3E,OAAO,CAAC,kBAAkB;CA4C3B;AAED,yCAAyC;AACzC,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;;;;;CAiBvB,CAAC"}
|
package/dist/crypto-only.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-Cw-f8RN3.js"),C=require("react/jsx-runtime"),i=require("react"),t=require("./CedrosContext-C2v_s8cc.js");require("@solana/web3.js");require("./index-WcOlBYZJ.js");const Q=require("@solana/wallet-adapter-react"),ne=require("@solana/wallet-adapter-base"),be=require("@solana/wallet-adapter-react-ui"),ae=require("./walletPool-BZyAG4YS.js");function se(){const{subscriptionManager:n,x402Manager:d,walletManager:f}=t.useCedrosContext(),{publicKey:c,signTransaction:T}=Q.useWallet(),[h,m]=i.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),[x,E]=i.useState(null),R=i.useCallback(()=>{if(!c){const l="Wallet not connected";return m(o=>({...o,status:"error",error:l})),{valid:!1,error:l}}if(!T){const l="Wallet does not support signing";return m(o=>({...o,status:"error",error:l})),{valid:!1,error:l}}return{valid:!0}},[c,T]),W=i.useCallback(async l=>{if(!c)return m(o=>({...o,status:"error",error:"Wallet not connected"})),null;m(o=>({...o,status:"checking",error:null}));try{const o=await n.checkSubscriptionStatus({resource:l,userId:c.toString()});return m(a=>({...a,status:o.active?"success":"idle",subscriptionStatus:o.status,expiresAt:o.expiresAt||o.currentPeriodEnd||null})),o}catch(o){const a=t.formatError(o,"Failed to check subscription status");return m(u=>({...u,status:"error",error:a})),null}},[c,n]),k=i.useCallback(async(l,o,a)=>{m(u=>({...u,status:"loading",error:null}));try{const u=await n.requestSubscriptionQuote(l,o,a);return E(u),m(b=>({...b,status:"idle"})),u}catch(u){const b=t.formatError(u,"Failed to get subscription quote");return m(s=>({...s,status:"error",error:b})),null}},[n]),I=i.useCallback(async(l,o,a)=>{const u=R();if(!u.valid)return{success:!1,error:u.error};m(b=>({...b,status:"loading",error:null}));try{const b=await n.requestSubscriptionQuote(l,o,a);E(b);const s=b.requirement;if(!d.validateRequirement(s))throw new Error("Invalid subscription quote received from server");const w=!!s.extra?.feePayer;let P;if(w){const{transaction:y,blockhash:v}=await d.buildGaslessTransaction({resourceId:l,userWallet:c.toString(),feePayer:s.extra.feePayer,couponCode:a?.couponCode}),_=f.deserializeTransaction(y),j=await f.partiallySignTransaction({transaction:_,signTransaction:T,blockhash:v});P=await d.submitGaslessTransaction({resource:l,partialTx:j,couponCode:a?.couponCode,resourceType:"regular",requirement:s})}else{const y=await f.buildTransaction({requirement:s,payerPublicKey:c}),v=await f.signTransaction({transaction:y,signTransaction:T}),_=f.buildPaymentPayload({requirement:s,signedTx:v,payerPublicKey:c});P=await d.submitPayment({resource:l,payload:_,couponCode:a?.couponCode,resourceType:"regular"})}if(P.success){const y=await n.checkSubscriptionStatus({resource:l,userId:c.toString()});m({status:"success",error:null,sessionId:P.transactionId||null,subscriptionStatus:y.status,expiresAt:y.expiresAt||y.currentPeriodEnd||null})}else m(y=>({...y,status:"error",error:P.error||"Subscription payment failed"}));return P}catch(b){const s=t.formatError(b,"Subscription payment failed");return m(w=>({...w,status:"error",error:s})),{success:!1,error:s}}},[R,n,d,f,c,T]),S=i.useCallback(()=>{m({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),E(null)},[]);return{...h,quote:x,checkStatus:W,requestQuote:k,processPayment:I,reset:S}}function Ce({resource:n,interval:d,intervalDays:f,couponCode:c,label:T,disabled:h=!1,onAttempt:m,onSuccess:x,onError:E,className:R="",testPageUrl:W,hideMessages:k=!1,autoCheckStatus:I=!0}){const{connected:S,connecting:l,connect:o,disconnect:a,select:u,wallets:b,wallet:s,publicKey:w}=Q.useWallet(),{status:P,error:y,subscriptionStatus:v,expiresAt:_,checkStatus:j,processPayment:O}=se(),g=t.useCedrosTheme(),{solanaError:L}=t.useCedrosContext(),{t:B,translations:F}=e.useTranslation(),ie=T||B("ui.subscribe_with_crypto"),U=i.useRef(O),G=i.useRef(j);i.useEffect(()=>{U.current=O,G.current=j},[O,j]);const le=y&&typeof y!="string"?y?.code??null:null,ce=L&&typeof L!="string"?L?.code??null:null,V=r=>{if(!r||!F)return"";const p=F.errors[r];return p?p.action?`${p.message} ${p.action}`:p.message:""},Y=y?typeof y=="string"?y:V(le):null,X=L?typeof L=="string"?L:V(ce):null,ue=i.useMemo(()=>b.map(r=>`${r.adapter.name}-${r.readyState}`).join(","),[b]),z=i.useMemo(()=>b.filter(({readyState:r})=>r===ne.WalletReadyState.Installed||r===ne.WalletReadyState.Loadable),[ue]);i.useEffect(()=>{I&&S&&w&&(t.getLogger().debug("[CryptoSubscribeButton] Auto-checking subscription status"),G.current(n))},[I,S,w,n]),i.useEffect(()=>{P==="success"&&v==="active"&&(e.emitPaymentSuccess("crypto","subscription-active",n),x&&x("subscription-active"))},[P,v,n,x]),i.useEffect(()=>{P==="error"&&y&&(e.emitPaymentError("crypto",y,n),E&&E(y))},[P,y,n,E]);const H=typeof window<"u"&&window.top!==window.self,[J,M]=i.useState(!1),[Z,K]=i.useState(!1),[ee,q]=i.useState(!1),A=L;i.useEffect(()=>{let r=!1;return r||(async()=>{if(Z&&s&&!S&&!l){t.getLogger().debug("[CryptoSubscribeButton] Wallet detected, attempting auto-connect:",s.adapter.name),K(!1),e.emitWalletConnect(s.adapter.name);try{await o(),r||t.getLogger().debug("[CryptoSubscribeButton] Auto-connect successful")}catch($){if(!r){t.getLogger().error("[CryptoSubscribeButton] Auto-connect failed:",$);const fe=$ instanceof Error?$.message:"Failed to connect wallet";e.emitWalletError(fe,s.adapter.name),q(!1)}}}})(),()=>{r=!0}},[s,Z,S,l,o]),i.useEffect(()=>{S&&ee&&w&&s&&(e.emitWalletConnected(s.adapter.name,w.toString()),t.getLogger().debug("[CryptoSubscribeButton] Processing pending subscription payment"),q(!1),M(!1),e.emitPaymentProcessing("crypto",n),U.current(n,d,{couponCode:c,intervalDays:f}))},[S,ee,w,s,n,d,c,f]);const te=i.useCallback(async()=>{if(t.getLogger().debug("[CryptoSubscribeButton] executeSubscriptionFlow called",{connected:S,wallet:s?.adapter.name,resource:n,interval:d}),e.emitPaymentStart("crypto",n),m&&m("crypto"),A){t.getLogger().error("[CryptoSubscribeButton] Solana dependencies missing:",A),e.emitPaymentError("crypto",A,n),E&&E(A);return}if(H){const r=W||window.location.href;try{if(new URL(r,window.location.origin).origin!==window.location.origin)throw t.getLogger().error("[CryptoSubscribeButton] Blocked attempt to open external URL:",r),new Error("Cannot open external URLs from embedded context");window.open(r,"_blank","noopener,noreferrer")}catch(p){throw t.getLogger().error("[CryptoSubscribeButton] URL validation failed:",p),p}return}if(S)e.emitPaymentProcessing("crypto",n),await O(n,d,{couponCode:c,intervalDays:f});else{q(!0);try{if(s)t.getLogger().debug("[CryptoSubscribeButton] Wallet already selected, connecting:",s.adapter.name),e.emitWalletConnect(s.adapter.name),await o();else{if(t.getLogger().debug("[CryptoSubscribeButton] No wallet selected, showing selector"),z.length===0){q(!1);const r="No wallets available";throw e.emitWalletError(r),new Error(r)}M(!0)}}catch(r){q(!1);const p=r instanceof Error?r.message:"Failed to connect wallet";t.getLogger().error("[CryptoSubscribeButton] Connection error:",p),e.emitWalletError(p,s?.adapter.name)}}},[S,s,n,d,c,f,H,W,z,o,O,A,m,E]),re=i.useMemo(()=>`crypto-subscribe-${n}-${d}`,[n,d]),de=i.useMemo(()=>e.createDedupedClickHandler(re,te,{cooldownMs:200,deduplicationWindowMs:0}),[re,te]),oe=P==="loading"||P==="checking",N=v==="active"||v==="trialing",ge=h||oe||l||!!A||N;let D=ie;if(oe)D=B("ui.processing");else if(N&&_){const r=new Date(_).toLocaleDateString();D=`${B("ui.subscribed_until")} ${r}`}else N&&(D=B("ui.subscribed"));const pe=i.useCallback(async()=>{try{K(!1),S&&await a(),u(null),M(!0)}catch(r){t.getLogger().error("Failed to change wallet:",r)}},[S,a,u]),me=i.useCallback(r=>{t.getLogger().debug("[CryptoSubscribeButton] Wallet clicked:",r),M(!1),u(r),K(!0)},[u]),ye=i.useCallback(async()=>{try{if(await a(),q(!1),typeof window<"u"&&window.localStorage)try{window.localStorage.removeItem("walletName")}catch(r){r instanceof Error&&r.name==="QuotaExceededError"?t.getLogger().warn("localStorage quota exceeded when removing wallet preference"):t.getLogger().error("Failed to clear wallet preference from localStorage:",r)}}catch(r){t.getLogger().error("Failed to disconnect wallet:",r)}},[a]);return C.jsxs("div",{className:g.unstyled?R:`${g.className} cedros-theme__crypto-button ${R||""}`,style:g.unstyled?{}:g.style,children:[C.jsx("button",{onClick:de,disabled:ge,className:g.unstyled?R:"cedros-theme__button cedros-theme__crypto",type:"button",children:D}),J&&!k&&C.jsx("div",{className:"cedros-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:g.tokens.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,padding:"1rem"},onClick:()=>M(!1),children:C.jsxs("div",{className:"cedros-modal-content",style:{backgroundColor:g.tokens.modalBackground,borderRadius:"12px",padding:"2rem",maxWidth:"400px",width:"100%",boxShadow:"0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)",border:`1px solid ${g.tokens.modalBorder}`},onClick:r=>r.stopPropagation(),children:[C.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},children:[C.jsx("h3",{style:{margin:0,fontSize:"1.25rem",fontWeight:600,color:g.tokens.surfaceText},children:B("wallet.select_wallet")}),C.jsx("button",{onClick:()=>M(!1),style:e.getModalCloseButtonStyles(g.tokens.surfaceText),"aria-label":"Close modal",type:"button",children:"×"})]}),C.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:z.map(r=>C.jsxs("button",{onClick:()=>me(r.adapter.name),style:{width:"100%",padding:"1rem",backgroundColor:g.tokens.surfaceBackground,border:`1px solid ${g.tokens.surfaceBorder}`,borderRadius:"0.5rem",cursor:"pointer",fontSize:"1rem",textAlign:"left",color:g.tokens.surfaceText,display:"flex",alignItems:"center",gap:"1rem",transition:"all 0.2s ease"},onMouseEnter:p=>{p.currentTarget.style.backgroundColor=g.tokens.modalBackground,p.currentTarget.style.borderColor=g.tokens.surfaceText,p.currentTarget.style.transform="translateY(-2px)"},onMouseLeave:p=>{p.currentTarget.style.backgroundColor=g.tokens.surfaceBackground,p.currentTarget.style.borderColor=g.tokens.surfaceBorder,p.currentTarget.style.transform="translateY(0)"},type:"button",children:[C.jsx(be.WalletIcon,{wallet:r,style:{width:"24px",height:"24px"}}),C.jsx("span",{style:{fontWeight:500},children:r.adapter.name})]},r.adapter.name))})]})}),S&&!k&&!J&&C.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"0.5rem",fontSize:"0.75rem",color:g.tokens.surfaceText,opacity:.7},children:[C.jsx("button",{onClick:pe,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:B("wallet.change")}),C.jsx("button",{onClick:ye,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:B("ui.disconnect")})]}),!k&&X&&C.jsx("div",{className:g.unstyled?"":"cedros-theme__error",children:X}),!k&&Y&&C.jsx("div",{className:g.unstyled?"":"cedros-theme__error",children:Y}),!k&&N&&C.jsx("div",{className:g.unstyled?"":"cedros-theme__success",children:B("ui.subscription_active")})]})}function Se(){const{x402Manager:n,walletManager:d}=t.useCedrosContext(),{publicKey:f,signTransaction:c}=Q.useWallet(),[T,h]=i.useState({status:"idle",error:null,transactionId:null}),[m,x]=i.useState(null),[E,R]=i.useState(null),W=i.useCallback(async l=>{try{h(a=>({...a,status:"loading"}));const o=await n.requestQuote({resource:l});if(!n.validateRequirement(o))throw new Error("Invalid refund requirement received from server");return x(o),h(a=>({...a,status:"idle"})),o}catch(o){const a=t.formatError(o,"Failed to fetch refund requirement");throw h({status:"error",error:a,transactionId:null}),o}},[n]),k=i.useCallback(async(l,o)=>{if(!f||!c)throw new Error("Wallet not connected");try{h({status:"loading",error:null,transactionId:null});const a=await n.requestQuote({resource:l,couponCode:o});if(!n.validateRequirement(a))throw new Error("Invalid refund requirement received");x(a);const u=await d.buildTransaction({requirement:a,payerPublicKey:f}),b=await d.signTransaction({transaction:u,signTransaction:c}),s=d.buildPaymentPayload({requirement:a,signedTx:b,payerPublicKey:f}),w=await n.submitPayment({resource:l,payload:s,couponCode:o,metadata:void 0,resourceType:"refund"});return w.settlement&&R(w.settlement),h({status:"success",error:null,transactionId:w.transactionId||b.signature}),w}catch(a){const u=t.formatError(a,"Refund payment failed");throw h({status:"error",error:u,transactionId:null}),a}},[f,c,n,d]),I=i.useCallback(async l=>{if(!f||!c)throw new Error("Wallet not connected");try{h({status:"loading",error:null,transactionId:null});const o=await n.requestQuote({resource:l});if(!n.validateRequirement(o))throw new Error("Invalid refund requirement received");x(o);const{transaction:a}=await n.buildGaslessTransaction({resourceId:l,userWallet:f.toString(),feePayer:o.extra.feePayer}),u=d.deserializeTransaction(a),b=await d.partiallySignTransaction({transaction:u,signTransaction:c}),s=await n.submitGaslessTransaction({resource:l,partialTx:b,couponCode:void 0,metadata:void 0,resourceType:"refund",requirement:o});return s.settlement&&R(s.settlement),h({status:"success",error:null,transactionId:s.transactionId||"gasless-refund-tx"}),s}catch(o){const a=t.formatError(o,"Gasless refund payment failed");throw h({status:"error",error:a,transactionId:null}),o}},[f,c,n,d]),S=i.useCallback(()=>{h({status:"idle",error:null,transactionId:null}),x(null),R(null)},[]);return{state:T,requirement:m,settlement:E,fetchRefundQuote:W,processRefund:k,processGaslessRefund:I,reset:S}}exports.CEDROS_EVENTS=e.CEDROS_EVENTS;exports.CSP_PRESETS=e.CSP_PRESETS;exports.CedrosPay=e.CedrosPay;exports.CedrosPayAdminDashboard=e.CedrosPayAdminDashboard;exports.CreditsButton=e.CreditsButton;exports.CreditsSubscribeButton=e.CreditsSubscribeButton;exports.CryptoButton=e.CryptoButton;exports.ERROR_CATEGORIES=e.ERROR_CATEGORIES;exports.PaymentMethodBadge=e.PaymentMethodBadge;exports.PaymentModal=e.PaymentModal;exports.ProductPrice=e.ProductPrice;exports.PurchaseButton=e.PurchaseButton;exports.RPC_PROVIDERS=e.RPC_PROVIDERS;exports.SECURITY_RECOMMENDATIONS=e.SECURITY_RECOMMENDATIONS;exports.StripeButton=e.StripeButton;exports.SubscribeButton=e.SubscribeButton;exports.SubscriptionManagementPanel=e.SubscriptionManagementPanel;exports.calculateDiscountPercentage=e.calculateDiscountPercentage;exports.cedrosPayPlugin=e.cedrosPayPlugin;exports.createTranslator=e.createTranslator;exports.detectLocale=e.detectLocale;exports.ecommerce=e.index;exports.emitPaymentError=e.emitPaymentError;exports.emitPaymentProcessing=e.emitPaymentProcessing;exports.emitPaymentStart=e.emitPaymentStart;exports.emitPaymentSuccess=e.emitPaymentSuccess;exports.emitWalletConnect=e.emitWalletConnect;exports.emitWalletConnected=e.emitWalletConnected;exports.emitWalletError=e.emitWalletError;exports.formatCSP=e.formatCSP;exports.formatCouponCodes=e.formatCouponCodes;exports.generateCSP=e.generateCSP;exports.generateCSPDirectives=e.generateCSPDirectives;exports.getAvailableLocales=e.getAvailableLocales;exports.getLocalizedError=e.getLocalizedError;exports.getUserErrorMessage=e.getUserErrorMessage;exports.isRetryableError=e.isRetryableError;exports.loadLocale=e.loadLocale;exports.logSecurityReport=e.logSecurityReport;exports.parseCouponCodes=e.parseCouponCodes;exports.stackCheckoutCoupons=e.stackCheckoutCoupons;exports.useCreditsPayment=e.useCreditsPayment;exports.useCreditsSubscription=e.useCreditsSubscription;exports.useLocalizedError=e.useLocalizedError;exports.usePaymentMode=e.usePaymentMode;exports.useStripeCheckout=e.useStripeCheckout;exports.useSubscription=e.useSubscription;exports.useSubscriptionManagement=e.useSubscriptionManagement;exports.useTranslation=e.useTranslation;exports.useX402Payment=e.useX402Payment;exports.validateSecurity=e.validateSecurity;exports.CIRCUIT_BREAKER_PRESETS=t.CIRCUIT_BREAKER_PRESETS;exports.CedrosProvider=t.CedrosProvider;exports.CircuitBreakerOpenError=t.CircuitBreakerOpenError;exports.CircuitState=t.CircuitState;exports.KNOWN_STABLECOINS=t.KNOWN_STABLECOINS;exports.LogLevel=t.LogLevel;exports.Logger=t.Logger;exports.RATE_LIMITER_PRESETS=t.RATE_LIMITER_PRESETS;exports.RETRY_PRESETS=t.RETRY_PRESETS;exports.createCircuitBreaker=t.createCircuitBreaker;exports.createLogger=t.createLogger;exports.createRateLimiter=t.createRateLimiter;exports.getLogger=t.getLogger;exports.retryWithBackoff=t.retryWithBackoff;exports.useCedrosContext=t.useCedrosContext;exports.useCedrosTheme=t.useCedrosTheme;exports.validateConfig=t.validateConfig;exports.validateTokenMint=t.validateTokenMint;exports.WalletPool=ae.WalletPool;exports.createWalletPool=ae.createWalletPool;exports.CryptoSubscribeButton=Ce;exports.useCryptoSubscription=se;exports.useRefundVerification=Se;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-Dhf-hhsE.js"),C=require("react/jsx-runtime"),i=require("react"),t=require("./CedrosContext-C2v_s8cc.js");require("@solana/web3.js");require("./index-WcOlBYZJ.js");const Q=require("@solana/wallet-adapter-react"),ne=require("@solana/wallet-adapter-base"),be=require("@solana/wallet-adapter-react-ui"),ae=require("./walletPool-BZyAG4YS.js");function se(){const{subscriptionManager:n,x402Manager:d,walletManager:f}=t.useCedrosContext(),{publicKey:c,signTransaction:T}=Q.useWallet(),[h,m]=i.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),[x,E]=i.useState(null),R=i.useCallback(()=>{if(!c){const l="Wallet not connected";return m(o=>({...o,status:"error",error:l})),{valid:!1,error:l}}if(!T){const l="Wallet does not support signing";return m(o=>({...o,status:"error",error:l})),{valid:!1,error:l}}return{valid:!0}},[c,T]),W=i.useCallback(async l=>{if(!c)return m(o=>({...o,status:"error",error:"Wallet not connected"})),null;m(o=>({...o,status:"checking",error:null}));try{const o=await n.checkSubscriptionStatus({resource:l,userId:c.toString()});return m(a=>({...a,status:o.active?"success":"idle",subscriptionStatus:o.status,expiresAt:o.expiresAt||o.currentPeriodEnd||null})),o}catch(o){const a=t.formatError(o,"Failed to check subscription status");return m(u=>({...u,status:"error",error:a})),null}},[c,n]),k=i.useCallback(async(l,o,a)=>{m(u=>({...u,status:"loading",error:null}));try{const u=await n.requestSubscriptionQuote(l,o,a);return E(u),m(b=>({...b,status:"idle"})),u}catch(u){const b=t.formatError(u,"Failed to get subscription quote");return m(s=>({...s,status:"error",error:b})),null}},[n]),I=i.useCallback(async(l,o,a)=>{const u=R();if(!u.valid)return{success:!1,error:u.error};m(b=>({...b,status:"loading",error:null}));try{const b=await n.requestSubscriptionQuote(l,o,a);E(b);const s=b.requirement;if(!d.validateRequirement(s))throw new Error("Invalid subscription quote received from server");const w=!!s.extra?.feePayer;let P;if(w){const{transaction:y,blockhash:v}=await d.buildGaslessTransaction({resourceId:l,userWallet:c.toString(),feePayer:s.extra.feePayer,couponCode:a?.couponCode}),_=f.deserializeTransaction(y),j=await f.partiallySignTransaction({transaction:_,signTransaction:T,blockhash:v});P=await d.submitGaslessTransaction({resource:l,partialTx:j,couponCode:a?.couponCode,resourceType:"regular",requirement:s})}else{const y=await f.buildTransaction({requirement:s,payerPublicKey:c}),v=await f.signTransaction({transaction:y,signTransaction:T}),_=f.buildPaymentPayload({requirement:s,signedTx:v,payerPublicKey:c});P=await d.submitPayment({resource:l,payload:_,couponCode:a?.couponCode,resourceType:"regular"})}if(P.success){const y=await n.checkSubscriptionStatus({resource:l,userId:c.toString()});m({status:"success",error:null,sessionId:P.transactionId||null,subscriptionStatus:y.status,expiresAt:y.expiresAt||y.currentPeriodEnd||null})}else m(y=>({...y,status:"error",error:P.error||"Subscription payment failed"}));return P}catch(b){const s=t.formatError(b,"Subscription payment failed");return m(w=>({...w,status:"error",error:s})),{success:!1,error:s}}},[R,n,d,f,c,T]),S=i.useCallback(()=>{m({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),E(null)},[]);return{...h,quote:x,checkStatus:W,requestQuote:k,processPayment:I,reset:S}}function Ce({resource:n,interval:d,intervalDays:f,couponCode:c,label:T,disabled:h=!1,onAttempt:m,onSuccess:x,onError:E,className:R="",testPageUrl:W,hideMessages:k=!1,autoCheckStatus:I=!0}){const{connected:S,connecting:l,connect:o,disconnect:a,select:u,wallets:b,wallet:s,publicKey:w}=Q.useWallet(),{status:P,error:y,subscriptionStatus:v,expiresAt:_,checkStatus:j,processPayment:O}=se(),g=t.useCedrosTheme(),{solanaError:L}=t.useCedrosContext(),{t:B,translations:F}=e.useTranslation(),ie=T||B("ui.subscribe_with_crypto"),U=i.useRef(O),G=i.useRef(j);i.useEffect(()=>{U.current=O,G.current=j},[O,j]);const le=y&&typeof y!="string"?y?.code??null:null,ce=L&&typeof L!="string"?L?.code??null:null,V=r=>{if(!r||!F)return"";const p=F.errors[r];return p?p.action?`${p.message} ${p.action}`:p.message:""},Y=y?typeof y=="string"?y:V(le):null,X=L?typeof L=="string"?L:V(ce):null,ue=i.useMemo(()=>b.map(r=>`${r.adapter.name}-${r.readyState}`).join(","),[b]),z=i.useMemo(()=>b.filter(({readyState:r})=>r===ne.WalletReadyState.Installed||r===ne.WalletReadyState.Loadable),[ue]);i.useEffect(()=>{I&&S&&w&&(t.getLogger().debug("[CryptoSubscribeButton] Auto-checking subscription status"),G.current(n))},[I,S,w,n]),i.useEffect(()=>{P==="success"&&v==="active"&&(e.emitPaymentSuccess("crypto","subscription-active",n),x&&x("subscription-active"))},[P,v,n,x]),i.useEffect(()=>{P==="error"&&y&&(e.emitPaymentError("crypto",y,n),E&&E(y))},[P,y,n,E]);const H=typeof window<"u"&&window.top!==window.self,[J,M]=i.useState(!1),[Z,K]=i.useState(!1),[ee,q]=i.useState(!1),A=L;i.useEffect(()=>{let r=!1;return r||(async()=>{if(Z&&s&&!S&&!l){t.getLogger().debug("[CryptoSubscribeButton] Wallet detected, attempting auto-connect:",s.adapter.name),K(!1),e.emitWalletConnect(s.adapter.name);try{await o(),r||t.getLogger().debug("[CryptoSubscribeButton] Auto-connect successful")}catch($){if(!r){t.getLogger().error("[CryptoSubscribeButton] Auto-connect failed:",$);const fe=$ instanceof Error?$.message:"Failed to connect wallet";e.emitWalletError(fe,s.adapter.name),q(!1)}}}})(),()=>{r=!0}},[s,Z,S,l,o]),i.useEffect(()=>{S&&ee&&w&&s&&(e.emitWalletConnected(s.adapter.name,w.toString()),t.getLogger().debug("[CryptoSubscribeButton] Processing pending subscription payment"),q(!1),M(!1),e.emitPaymentProcessing("crypto",n),U.current(n,d,{couponCode:c,intervalDays:f}))},[S,ee,w,s,n,d,c,f]);const te=i.useCallback(async()=>{if(t.getLogger().debug("[CryptoSubscribeButton] executeSubscriptionFlow called",{connected:S,wallet:s?.adapter.name,resource:n,interval:d}),e.emitPaymentStart("crypto",n),m&&m("crypto"),A){t.getLogger().error("[CryptoSubscribeButton] Solana dependencies missing:",A),e.emitPaymentError("crypto",A,n),E&&E(A);return}if(H){const r=W||window.location.href;try{if(new URL(r,window.location.origin).origin!==window.location.origin)throw t.getLogger().error("[CryptoSubscribeButton] Blocked attempt to open external URL:",r),new Error("Cannot open external URLs from embedded context");window.open(r,"_blank","noopener,noreferrer")}catch(p){throw t.getLogger().error("[CryptoSubscribeButton] URL validation failed:",p),p}return}if(S)e.emitPaymentProcessing("crypto",n),await O(n,d,{couponCode:c,intervalDays:f});else{q(!0);try{if(s)t.getLogger().debug("[CryptoSubscribeButton] Wallet already selected, connecting:",s.adapter.name),e.emitWalletConnect(s.adapter.name),await o();else{if(t.getLogger().debug("[CryptoSubscribeButton] No wallet selected, showing selector"),z.length===0){q(!1);const r="No wallets available";throw e.emitWalletError(r),new Error(r)}M(!0)}}catch(r){q(!1);const p=r instanceof Error?r.message:"Failed to connect wallet";t.getLogger().error("[CryptoSubscribeButton] Connection error:",p),e.emitWalletError(p,s?.adapter.name)}}},[S,s,n,d,c,f,H,W,z,o,O,A,m,E]),re=i.useMemo(()=>`crypto-subscribe-${n}-${d}`,[n,d]),de=i.useMemo(()=>e.createDedupedClickHandler(re,te,{cooldownMs:200,deduplicationWindowMs:0}),[re,te]),oe=P==="loading"||P==="checking",N=v==="active"||v==="trialing",ge=h||oe||l||!!A||N;let D=ie;if(oe)D=B("ui.processing");else if(N&&_){const r=new Date(_).toLocaleDateString();D=`${B("ui.subscribed_until")} ${r}`}else N&&(D=B("ui.subscribed"));const pe=i.useCallback(async()=>{try{K(!1),S&&await a(),u(null),M(!0)}catch(r){t.getLogger().error("Failed to change wallet:",r)}},[S,a,u]),me=i.useCallback(r=>{t.getLogger().debug("[CryptoSubscribeButton] Wallet clicked:",r),M(!1),u(r),K(!0)},[u]),ye=i.useCallback(async()=>{try{if(await a(),q(!1),typeof window<"u"&&window.localStorage)try{window.localStorage.removeItem("walletName")}catch(r){r instanceof Error&&r.name==="QuotaExceededError"?t.getLogger().warn("localStorage quota exceeded when removing wallet preference"):t.getLogger().error("Failed to clear wallet preference from localStorage:",r)}}catch(r){t.getLogger().error("Failed to disconnect wallet:",r)}},[a]);return C.jsxs("div",{className:g.unstyled?R:`${g.className} cedros-theme__crypto-button ${R||""}`,style:g.unstyled?{}:g.style,children:[C.jsx("button",{onClick:de,disabled:ge,className:g.unstyled?R:"cedros-theme__button cedros-theme__crypto",type:"button",children:D}),J&&!k&&C.jsx("div",{className:"cedros-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:g.tokens.modalOverlay,display:"flex",alignItems:"center",justifyContent:"center",zIndex:9999,padding:"1rem"},onClick:()=>M(!1),children:C.jsxs("div",{className:"cedros-modal-content",style:{backgroundColor:g.tokens.modalBackground,borderRadius:"12px",padding:"2rem",maxWidth:"400px",width:"100%",boxShadow:"0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)",border:`1px solid ${g.tokens.modalBorder}`},onClick:r=>r.stopPropagation(),children:[C.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"1.5rem"},children:[C.jsx("h3",{style:{margin:0,fontSize:"1.25rem",fontWeight:600,color:g.tokens.surfaceText},children:B("wallet.select_wallet")}),C.jsx("button",{onClick:()=>M(!1),style:e.getModalCloseButtonStyles(g.tokens.surfaceText),"aria-label":"Close modal",type:"button",children:"×"})]}),C.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:z.map(r=>C.jsxs("button",{onClick:()=>me(r.adapter.name),style:{width:"100%",padding:"1rem",backgroundColor:g.tokens.surfaceBackground,border:`1px solid ${g.tokens.surfaceBorder}`,borderRadius:"0.5rem",cursor:"pointer",fontSize:"1rem",textAlign:"left",color:g.tokens.surfaceText,display:"flex",alignItems:"center",gap:"1rem",transition:"all 0.2s ease"},onMouseEnter:p=>{p.currentTarget.style.backgroundColor=g.tokens.modalBackground,p.currentTarget.style.borderColor=g.tokens.surfaceText,p.currentTarget.style.transform="translateY(-2px)"},onMouseLeave:p=>{p.currentTarget.style.backgroundColor=g.tokens.surfaceBackground,p.currentTarget.style.borderColor=g.tokens.surfaceBorder,p.currentTarget.style.transform="translateY(0)"},type:"button",children:[C.jsx(be.WalletIcon,{wallet:r,style:{width:"24px",height:"24px"}}),C.jsx("span",{style:{fontWeight:500},children:r.adapter.name})]},r.adapter.name))})]})}),S&&!k&&!J&&C.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"0.5rem",fontSize:"0.75rem",color:g.tokens.surfaceText,opacity:.7},children:[C.jsx("button",{onClick:pe,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:B("wallet.change")}),C.jsx("button",{onClick:ye,style:{background:"none",border:"none",padding:0,color:"inherit",textDecoration:"none",cursor:"pointer",fontSize:"inherit"},type:"button",children:B("ui.disconnect")})]}),!k&&X&&C.jsx("div",{className:g.unstyled?"":"cedros-theme__error",children:X}),!k&&Y&&C.jsx("div",{className:g.unstyled?"":"cedros-theme__error",children:Y}),!k&&N&&C.jsx("div",{className:g.unstyled?"":"cedros-theme__success",children:B("ui.subscription_active")})]})}function Se(){const{x402Manager:n,walletManager:d}=t.useCedrosContext(),{publicKey:f,signTransaction:c}=Q.useWallet(),[T,h]=i.useState({status:"idle",error:null,transactionId:null}),[m,x]=i.useState(null),[E,R]=i.useState(null),W=i.useCallback(async l=>{try{h(a=>({...a,status:"loading"}));const o=await n.requestQuote({resource:l});if(!n.validateRequirement(o))throw new Error("Invalid refund requirement received from server");return x(o),h(a=>({...a,status:"idle"})),o}catch(o){const a=t.formatError(o,"Failed to fetch refund requirement");throw h({status:"error",error:a,transactionId:null}),o}},[n]),k=i.useCallback(async(l,o)=>{if(!f||!c)throw new Error("Wallet not connected");try{h({status:"loading",error:null,transactionId:null});const a=await n.requestQuote({resource:l,couponCode:o});if(!n.validateRequirement(a))throw new Error("Invalid refund requirement received");x(a);const u=await d.buildTransaction({requirement:a,payerPublicKey:f}),b=await d.signTransaction({transaction:u,signTransaction:c}),s=d.buildPaymentPayload({requirement:a,signedTx:b,payerPublicKey:f}),w=await n.submitPayment({resource:l,payload:s,couponCode:o,metadata:void 0,resourceType:"refund"});return w.settlement&&R(w.settlement),h({status:"success",error:null,transactionId:w.transactionId||b.signature}),w}catch(a){const u=t.formatError(a,"Refund payment failed");throw h({status:"error",error:u,transactionId:null}),a}},[f,c,n,d]),I=i.useCallback(async l=>{if(!f||!c)throw new Error("Wallet not connected");try{h({status:"loading",error:null,transactionId:null});const o=await n.requestQuote({resource:l});if(!n.validateRequirement(o))throw new Error("Invalid refund requirement received");x(o);const{transaction:a}=await n.buildGaslessTransaction({resourceId:l,userWallet:f.toString(),feePayer:o.extra.feePayer}),u=d.deserializeTransaction(a),b=await d.partiallySignTransaction({transaction:u,signTransaction:c}),s=await n.submitGaslessTransaction({resource:l,partialTx:b,couponCode:void 0,metadata:void 0,resourceType:"refund",requirement:o});return s.settlement&&R(s.settlement),h({status:"success",error:null,transactionId:s.transactionId||"gasless-refund-tx"}),s}catch(o){const a=t.formatError(o,"Gasless refund payment failed");throw h({status:"error",error:a,transactionId:null}),o}},[f,c,n,d]),S=i.useCallback(()=>{h({status:"idle",error:null,transactionId:null}),x(null),R(null)},[]);return{state:T,requirement:m,settlement:E,fetchRefundQuote:W,processRefund:k,processGaslessRefund:I,reset:S}}exports.CEDROS_EVENTS=e.CEDROS_EVENTS;exports.CSP_PRESETS=e.CSP_PRESETS;exports.CedrosPay=e.CedrosPay;exports.CedrosPayAdminDashboard=e.CedrosPayAdminDashboard;exports.CreditsButton=e.CreditsButton;exports.CreditsSubscribeButton=e.CreditsSubscribeButton;exports.CryptoButton=e.CryptoButton;exports.ERROR_CATEGORIES=e.ERROR_CATEGORIES;exports.PaymentMethodBadge=e.PaymentMethodBadge;exports.PaymentModal=e.PaymentModal;exports.ProductPrice=e.ProductPrice;exports.PurchaseButton=e.PurchaseButton;exports.RPC_PROVIDERS=e.RPC_PROVIDERS;exports.SECURITY_RECOMMENDATIONS=e.SECURITY_RECOMMENDATIONS;exports.StripeButton=e.StripeButton;exports.SubscribeButton=e.SubscribeButton;exports.SubscriptionManagementPanel=e.SubscriptionManagementPanel;exports.calculateDiscountPercentage=e.calculateDiscountPercentage;exports.cedrosPayPlugin=e.cedrosPayPlugin;exports.createTranslator=e.createTranslator;exports.detectLocale=e.detectLocale;exports.ecommerce=e.index;exports.emitPaymentError=e.emitPaymentError;exports.emitPaymentProcessing=e.emitPaymentProcessing;exports.emitPaymentStart=e.emitPaymentStart;exports.emitPaymentSuccess=e.emitPaymentSuccess;exports.emitWalletConnect=e.emitWalletConnect;exports.emitWalletConnected=e.emitWalletConnected;exports.emitWalletError=e.emitWalletError;exports.formatCSP=e.formatCSP;exports.formatCouponCodes=e.formatCouponCodes;exports.generateCSP=e.generateCSP;exports.generateCSPDirectives=e.generateCSPDirectives;exports.getAvailableLocales=e.getAvailableLocales;exports.getLocalizedError=e.getLocalizedError;exports.getUserErrorMessage=e.getUserErrorMessage;exports.isRetryableError=e.isRetryableError;exports.loadLocale=e.loadLocale;exports.logSecurityReport=e.logSecurityReport;exports.parseCouponCodes=e.parseCouponCodes;exports.stackCheckoutCoupons=e.stackCheckoutCoupons;exports.useCreditsPayment=e.useCreditsPayment;exports.useCreditsSubscription=e.useCreditsSubscription;exports.useLocalizedError=e.useLocalizedError;exports.usePaymentMode=e.usePaymentMode;exports.useStripeCheckout=e.useStripeCheckout;exports.useSubscription=e.useSubscription;exports.useSubscriptionManagement=e.useSubscriptionManagement;exports.useTranslation=e.useTranslation;exports.useX402Payment=e.useX402Payment;exports.validateSecurity=e.validateSecurity;exports.CIRCUIT_BREAKER_PRESETS=t.CIRCUIT_BREAKER_PRESETS;exports.CedrosProvider=t.CedrosProvider;exports.CircuitBreakerOpenError=t.CircuitBreakerOpenError;exports.CircuitState=t.CircuitState;exports.KNOWN_STABLECOINS=t.KNOWN_STABLECOINS;exports.LogLevel=t.LogLevel;exports.Logger=t.Logger;exports.RATE_LIMITER_PRESETS=t.RATE_LIMITER_PRESETS;exports.RETRY_PRESETS=t.RETRY_PRESETS;exports.createCircuitBreaker=t.createCircuitBreaker;exports.createLogger=t.createLogger;exports.createRateLimiter=t.createRateLimiter;exports.getLogger=t.getLogger;exports.retryWithBackoff=t.retryWithBackoff;exports.useCedrosContext=t.useCedrosContext;exports.useCedrosTheme=t.useCedrosTheme;exports.validateConfig=t.validateConfig;exports.validateTokenMint=t.validateTokenMint;exports.WalletPool=ae.WalletPool;exports.createWalletPool=ae.createWalletPool;exports.CryptoSubscribeButton=Ce;exports.useCryptoSubscription=se;exports.useRefundVerification=Se;
|
package/dist/crypto-only.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { U as ke, F as Te, G as ue, A as Re, D as de, y as ve, z as pe, B as V, a0 as Be, a1 as Ie } from "./index-
|
|
2
|
-
import { x as Ue, w as Ve, C as Ye, a as He, b as Je, h as Xe, a2 as Ze, E as et, f as tt, d as rt, e as at, P as nt, R as st, L as ot, S as it, g as ct, i as lt, q as ut, c as dt, Q as pt, M as mt, W as ft, v as yt, o as bt, r as gt, t as wt, O as St, T as ht, I as Ct, H as xt, N as Pt, K as Et, p as kt, s as Tt, j as Rt, m as vt, V as Bt, k as It, u as Wt, l as qt, n as _t, a3 as Mt, J as Lt } from "./index-
|
|
1
|
+
import { U as ke, F as Te, G as ue, A as Re, D as de, y as ve, z as pe, B as V, a0 as Be, a1 as Ie } from "./index-9OMDKaoz.mjs";
|
|
2
|
+
import { x as Ue, w as Ve, C as Ye, a as He, b as Je, h as Xe, a2 as Ze, E as et, f as tt, d as rt, e as at, P as nt, R as st, L as ot, S as it, g as ct, i as lt, q as ut, c as dt, Q as pt, M as mt, W as ft, v as yt, o as bt, r as gt, t as wt, O as St, T as ht, I as Ct, H as xt, N as Pt, K as Et, p as kt, s as Tt, j as Rt, m as vt, V as Bt, k as It, u as Wt, l as qt, n as _t, a3 as Mt, J as Lt } from "./index-9OMDKaoz.mjs";
|
|
3
3
|
import { jsxs as O, jsx as x } from "react/jsx-runtime";
|
|
4
4
|
import { useState as B, useCallback as h, useRef as me, useEffect as N, useMemo as F } from "react";
|
|
5
5
|
import { u as Y, m as D, a as We, i as y } from "./CedrosContext-D7nh5-Zh.mjs";
|
|
@@ -9236,12 +9236,11 @@ class nh {
|
|
|
9236
9236
|
serverUrl;
|
|
9237
9237
|
walletSigner = null;
|
|
9238
9238
|
jwtToken = null;
|
|
9239
|
-
isAdmin = !1;
|
|
9240
9239
|
constructor(t) {
|
|
9241
9240
|
this.serverUrl = t;
|
|
9242
9241
|
}
|
|
9243
9242
|
getAuthMethod() {
|
|
9244
|
-
return this.walletSigner?.publicKey && this.walletSigner.signMessage ? "wallet" : this.jwtToken
|
|
9243
|
+
return this.walletSigner?.publicKey && this.walletSigner.signMessage ? "wallet" : this.jwtToken ? "cedros-login" : "none";
|
|
9245
9244
|
}
|
|
9246
9245
|
isAuthenticated() {
|
|
9247
9246
|
return this.getAuthMethod() !== "none";
|
|
@@ -9250,7 +9249,7 @@ class nh {
|
|
|
9250
9249
|
this.walletSigner = t, fe().debug("[AdminAuthManager] Wallet signer updated:", !!t?.publicKey);
|
|
9251
9250
|
}
|
|
9252
9251
|
setCedrosLoginAuth(t, n) {
|
|
9253
|
-
this.jwtToken = t,
|
|
9252
|
+
this.jwtToken = t, fe().debug("[AdminAuthManager] Cedros-login auth updated:", { hasToken: !!t });
|
|
9254
9253
|
}
|
|
9255
9254
|
async createAuthHeaders(t) {
|
|
9256
9255
|
const n = this.getAuthMethod();
|
|
@@ -9358,7 +9357,7 @@ function rh({
|
|
|
9358
9357
|
signMessage: r.signMessage
|
|
9359
9358
|
}) : a.setWalletSigner(null);
|
|
9360
9359
|
}, [a, r.publicKey, r.signMessage]);
|
|
9361
|
-
const s = a.getAuthMethod(), i = a.isAuthenticated(), c = !!(r.publicKey && r.signMessage), l = !!
|
|
9360
|
+
const s = a.getAuthMethod(), i = a.isAuthenticated(), c = !!(r.publicKey && r.signMessage), l = !!t, u = Se(() => {
|
|
9362
9361
|
if (!r.publicKey) return null;
|
|
9363
9362
|
const m = r.publicKey.toBase58();
|
|
9364
9363
|
return `${m.slice(0, 4)}...${m.slice(-4)}`;
|
|
@@ -9623,11 +9622,11 @@ const Mt = (e) => Wp(async () => {
|
|
|
9623
9622
|
{ id: "Configuration", label: "Configuration", order: 2, defaultCollapsed: !0 }
|
|
9624
9623
|
],
|
|
9625
9624
|
components: {
|
|
9626
|
-
products: Mt(() => import("./sections-
|
|
9625
|
+
products: Mt(() => import("./sections-CEm-cWUI.mjs").then((e) => ({ default: e.ProductsSection }))),
|
|
9627
9626
|
subscriptions: Mt(() => Promise.resolve().then(() => Wf).then((e) => ({ default: e.SubscriptionsSection }))),
|
|
9628
|
-
transactions: Mt(() => import("./sections-
|
|
9629
|
-
coupons: Mt(() => import("./sections-
|
|
9630
|
-
refunds: Mt(() => import("./sections-
|
|
9627
|
+
transactions: Mt(() => import("./sections-CEm-cWUI.mjs").then((e) => ({ default: e.TransactionsSection }))),
|
|
9628
|
+
coupons: Mt(() => import("./sections-CEm-cWUI.mjs").then((e) => ({ default: e.CouponsSection }))),
|
|
9629
|
+
refunds: Mt(() => import("./sections-CEm-cWUI.mjs").then((e) => ({ default: e.RefundsSection }))),
|
|
9631
9630
|
storefront: Mt(() => Promise.resolve().then(() => Zf).then((e) => ({ default: e.StorefrontSection }))),
|
|
9632
9631
|
"ai-settings": Mt(() => Promise.resolve().then(() => Kf).then((e) => ({ default: e.AISettingsSection }))),
|
|
9633
9632
|
faqs: Mt(() => Promise.resolve().then(() => th).then((e) => ({ default: e.FAQSection }))),
|
|
@@ -50,7 +50,7 @@ Guidelines:
|
|
|
50
50
|
- Use sensory language when appropriate
|
|
51
51
|
- Keep descriptions scannable with short paragraphs
|
|
52
52
|
- Avoid superlatives and unverifiable claims
|
|
53
|
-
- Include relevant keywords naturally for SEO`}],sh=[{id:"gemini",label:"Google Gemini API",placeholder:"AIza..."},{id:"openai",label:"OpenAI API",placeholder:"sk-..."}],Ji={apiKeys:[{provider:"gemini",isConfigured:!1},{provider:"openai",isConfigured:!1}],taskAssignments:Jo.map(e=>({task:e.task,label:e.label,description:e.description,assignedModel:"not_set",systemPrompt:e.defaultPrompt}))};function ql({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("api-keys"),[a,i]=y.useState(Ji),[c,l]=y.useState(!0),[d,m]=y.useState(!1),[u,p]=y.useState(null),[h,_]=y.useState(!1),[g,f]=y.useState(null),w=y.useRef(null),[j,b]=y.useState({gemini:"",openai:""}),[v,k]=y.useState({gemini:!1,openai:!1}),R=y.useCallback(async()=>{try{let A;if(r?.isAuthenticated())A=await r.fetchWithAuth("/admin/config/ai");else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const B=await fetch(`${e}/admin/config/ai`,{headers:I});if(!B.ok)throw new Error(`Failed to fetch: ${B.status}`);A=await B.json()}A.settings&&i(A.settings)}catch{i(Ji),f("Could not load saved AI settings. Showing defaults.")}finally{l(!1)}},[e,t,r]);y.useEffect(()=>{R()},[R]);const N=y.useCallback(async A=>{const I=j[A];if(I.trim()){m(!0),p(null);try{const B={provider:A,apiKey:I};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/api-key",{method:"PUT",body:JSON.stringify(B)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const E=await fetch(`${e}/admin/config/ai/api-key`,{method:"PUT",headers:D,body:JSON.stringify(B)});if(!E.ok)throw new Error(`Failed to save: ${E.status}`)}i(D=>({...D,apiKeys:D.apiKeys.map(E=>E.provider===A?{...E,isConfigured:!0,maskedKey:`${I.slice(0,4)}...${I.slice(-4)}`,updatedAt:new Date().toISOString()}:E)})),b(D=>({...D,[A]:""})),_(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>_(!1),3e3)}catch(B){p(B instanceof Error?B.message:"Failed to save API key")}finally{m(!1)}}},[j,e,t,r]),C=y.useCallback(async A=>{if(confirm(`Are you sure you want to delete the ${A==="gemini"?"Google Gemini":"OpenAI"} API key?`)){m(!0),p(null);try{if(r?.isAuthenticated())await r.fetchWithAuth(`/admin/config/ai/api-key/${A}`,{method:"DELETE"});else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const B=await fetch(`${e}/admin/config/ai/api-key/${A}`,{method:"DELETE",headers:I});if(!B.ok)throw new Error(`Failed to delete: ${B.status}`)}i(I=>({...I,apiKeys:I.apiKeys.map(B=>B.provider===A?{provider:A,isConfigured:!1}:B)}))}catch(I){p(I instanceof Error?I.message:"Failed to delete API key")}finally{m(!1)}}},[e,t,r]),T=y.useCallback(async(A,I)=>{m(!0),p(null);try{const B={task:A,model:I};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/assignment",{method:"PUT",body:JSON.stringify(B)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const E=await fetch(`${e}/admin/config/ai/assignment`,{method:"PUT",headers:D,body:JSON.stringify(B)});if(!E.ok)throw new Error(`Failed to save: ${E.status}`)}i(D=>({...D,taskAssignments:D.taskAssignments.map(E=>E.task===A?{...E,assignedModel:I}:E)})),_(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>_(!1),3e3)}catch(B){p(B instanceof Error?B.message:"Failed to save assignment")}finally{m(!1)}},[e,t,r]),O=y.useCallback(A=>{if(A==="not_set")return!0;const I=jo.find(D=>D.id===A);return I?.provider?a.apiKeys.find(D=>D.provider===I.provider)?.isConfigured??!1:!0},[a.apiKeys]),$=y.useMemo(()=>jo.map(A=>{const I=O(A.id);return{value:A.id,label:I?A.label:`${A.label} (API key required)`,disabled:!I}}),[O]),S=y.useCallback(async(A,I)=>{m(!0),p(null);try{const B={task:A,systemPrompt:I};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/prompt",{method:"PUT",body:JSON.stringify(B)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const E=await fetch(`${e}/admin/config/ai/prompt`,{method:"PUT",headers:D,body:JSON.stringify(B)});if(!E.ok)throw new Error(`Failed to save: ${E.status}`)}i(D=>({...D,taskAssignments:D.taskAssignments.map(E=>E.task===A?{...E,systemPrompt:I}:E)})),_(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>_(!1),3e3)}catch(B){p(B instanceof Error?B.message:"Failed to save prompt")}finally{m(!1)}},[e,t,r]);return y.useEffect(()=>()=>{w.current&&clearTimeout(w.current)},[]),c?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading AI settings..."]})}):n.jsxs("div",{className:"cedros-admin__ai-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store AI"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure AI providers, model assignments, and system prompts."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="api-keys"?"cedros-admin__tab--active":""}`,onClick:()=>o("api-keys"),children:"API Keys"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="assignments"?"cedros-admin__tab--active":""}`,onClick:()=>o("assignments"),children:"Model Assignments"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="prompts"?"cedros-admin__tab--active":""}`,onClick:()=>o("prompts"),children:"Prompts"})]}),u&&n.jsx("div",{className:"cedros-admin__error-banner",style:{marginTop:"1rem"},children:u}),n.jsx(Yt,{message:g,onRetry:R}),h&&n.jsxs("div",{className:"cedros-admin__success-banner",style:{marginTop:"1rem"},children:[Q.check," Settings saved successfully"]}),s==="api-keys"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"API Keys"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure API keys for AI providers. Keys are stored securely and never exposed."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:sh.map(A=>{const I=a.apiKeys.find(D=>D.provider===A.id),B=I?.isConfigured??!1;return n.jsxs("div",{className:"cedros-admin__api-key-card",style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:A.label}),B&&I?.maskedKey&&n.jsxs("div",{style:{fontSize:12,opacity:.6,marginTop:2},children:["Current key: ",I.maskedKey,I.updatedAt&&n.jsxs("span",{children:[" (updated ",new Date(I.updatedAt).toLocaleDateString(),")"]})]})]}),n.jsx("span",{className:`cedros-admin__badge ${B?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:B?"Configured":"Not Set"})]}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:n.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[n.jsx("input",{type:v[A.id]?"text":"password",className:"cedros-admin__input",placeholder:B?"Enter new key to replace":A.placeholder,value:j[A.id],onChange:D=>b(E=>({...E,[A.id]:D.target.value})),onBlur:()=>{j[A.id].trim()&&N(A.id)},style:{flex:1}}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>k(D=>({...D,[A.id]:!D[A.id]})),title:v[A.id]?"Hide key":"Show key",style:{padding:"0.5rem"},children:v[A.id]?Q.eyeOff:Q.eye}),B&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>C(A.id),disabled:d,title:"Remove API key",style:{padding:"0.5rem"},children:Q.trash})]})})]},A.id)})})]}),s==="assignments"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"Model Assignments"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Assign AI models to specific tasks. Models require their provider's API key to be configured."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:a.taskAssignments.map(A=>{const I=Jo.find(D=>D.task===A.task),B=jo.find(D=>D.id===A.assignedModel);return n.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{marginBottom:"0.75rem"},children:[n.jsx("div",{style:{fontWeight:600},children:I?.label??A.task}),n.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:I?.description})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(ot,{value:A.assignedModel,onChange:D=>T(A.task,D),options:$,label:"",disabled:d,style:{flex:1,maxWidth:280}}),B&&B.provider&&n.jsx("span",{className:`cedros-admin__badge ${O(B.id)?"cedros-admin__badge--success":"cedros-admin__badge--warning"}`,children:O(B.id)?"Ready":"Missing API Key"})]})]},A.task)})})]}),s==="prompts"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"System Prompts"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure the default system prompts for each AI task. These prompts guide the AI's behavior and responses."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:a.taskAssignments.map(A=>{const I=Jo.find(B=>B.task===A.task);return n.jsx(oh,{task:A.task,label:I?.label??A.task,description:I?.description??"",initialPrompt:A.systemPrompt??"",onSave:S},A.task)})})]})]})}function oh({task:e,label:t,description:r,initialPrompt:s,onSave:o}){const[a,i]=y.useState(s),[c,l]=y.useState("idle"),d=y.useRef(null),m=y.useRef(null),u=y.useRef(!0);return y.useEffect(()=>{if(u.current){u.current=!1;return}return d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current),l("pending"),d.current=setTimeout(async()=>{l("saving");try{await o(e,a),l("saved"),m.current=setTimeout(()=>l("idle"),2e3)}catch{l("error")}},1500),()=>{d.current&&clearTimeout(d.current)}},[a,e,o]),y.useEffect(()=>()=>{d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current)},[]),n.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{marginBottom:"0.75rem",display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:t}),n.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:r})]}),n.jsx(ah,{status:c})]}),n.jsx("textarea",{className:"cedros-admin__input",value:a,onChange:p=>i(p.target.value),placeholder:"Enter system prompt...",rows:4,style:{width:"100%",resize:"vertical",fontFamily:"inherit",minHeight:100}})]})}function ah({status:e}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.75rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved"}),e==="saving"&&n.jsxs(n.Fragment,{children:[Q.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[Q.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsx("span",{children:"Failed"})]})}const ih=Object.freeze(Object.defineProperty({__proto__:null,AISettingsSection:ql},Symbol.toStringTag,{value:"Module"}));function qn({href:e,children:t}){return n.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"underline"},children:t})}const ec=[{id:"stripe",label:"Stripe",category:"stripe",description:n.jsxs(n.Fragment,{children:["Configure your Stripe integration for card payments. Get your API keys from the"," ",n.jsx(qn,{href:"https://dashboard.stripe.com/apikeys",children:"Stripe Dashboard"}),"."]})},{id:"crypto",label:"Crypto",category:"x402",description:n.jsxs(n.Fragment,{children:["Configure Solana wallet and token settings for crypto payments. Get a fast RPC endpoint from"," ",n.jsx(qn,{href:"https://www.helius.dev",children:"Helius"})," or"," ",n.jsx(qn,{href:"https://www.quicknode.com/chains/sol",children:"QuickNode"}),". Set up a payment address using"," ",n.jsx(qn,{href:"https://phantom.app",children:"Phantom"})," or"," ",n.jsx(qn,{href:"https://solflare.com",children:"Solflare"})," wallet."]})},{id:"credits",label:"Credits",category:"cedros_login",description:n.jsxs(n.Fragment,{children:["Configure Cedros Login integration for credits payments. See the"," ",n.jsx(qn,{href:"https://docs.cedros.dev/credits",children:"Credits API documentation"}),"."]})}];function Hl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("stripe"),a=ec.find(i=>i.id===s);return n.jsxs("div",{className:"cedros-admin__payment-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Payment Options"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure payment methods including Stripe, crypto, and credits."})]}),n.jsx("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:ec.map(i=>n.jsx("button",{type:"button",className:`cedros-admin__tab ${s===i.id?"cedros-admin__tab--active":""}`,onClick:()=>o(i.id),children:i.label},i.id))}),n.jsx("div",{style:{marginTop:"1rem"},children:n.jsx(Ul,{serverUrl:e,apiKey:t,authManager:r,category:a.category,title:`${a.label} Settings`,description:a.description,showEnabledToggle:!0},a.category)})]})}const ch=Object.freeze(Object.defineProperty({__proto__:null,PaymentSettingsSection:Hl},Symbol.toStringTag,{value:"Module"})),ko={email_enabled:!1,smtp_host:"",smtp_port:587,smtp_username:"",smtp_password:"",from_email:"",from_name:"",webhook_enabled:!1,webhook_url:"",webhook_secret:"",webhook_timeout:30};function Zl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("messages"),[a,i]=y.useState(ko),[c,l]=y.useState(!0),[d,m]=y.useState(!0),[u,p]=y.useState(null),[h,_]=y.useState(new Set),g=y.useCallback(async()=>{try{p(null);let v;const k="/admin/config/messaging";if(r?.isAuthenticated())v=await r.fetchWithAuth(k);else{const R={"Content-Type":"application/json"};t&&(R["X-API-Key"]=t);const N=await fetch(`${e}${k}`,{headers:R});if(!N.ok)throw new Error(`Failed to fetch: ${N.status}`);v=await N.json()}i({...ko,...v.config})}catch{i(ko),p("Could not load saved settings. Showing defaults.")}finally{l(!1),setTimeout(()=>m(!1),100)}},[e,t,r]);y.useEffect(()=>{g()},[g]);const f=y.useCallback(async v=>{const k="/admin/config/messaging",R={...v};h.has("smtp_password")||delete R.smtp_password,h.has("webhook_secret")||delete R.webhook_secret;const N=JSON.stringify({config:R});try{if(r?.isAuthenticated())await r.fetchWithAuth(k,{method:"PUT",body:N});else{const C={"Content-Type":"application/json"};t&&(C["X-API-Key"]=t);const T=await fetch(`${e}${k}`,{method:"PUT",headers:C,body:N});if(!T.ok)throw new Error(`Failed to save: ${T.status}`)}}catch{throw p("Failed to save messaging settings"),new Error("Save failed")}},[e,t,r,h]),{status:w,error:j}=Ta({data:a,onSave:f,debounceMs:1500,enabled:!d}),b=(v,k)=>{(v==="smtp_password"||v==="webhook_secret")&&_(R=>new Set(R).add(v)),i(R=>({...R,[v]:k}))};return c?n.jsxs("div",{className:"cedros-admin__messaging-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),n.jsxs("div",{className:"cedros-admin__loading",style:{marginTop:"1rem"},children:[Q.loading," Loading message settings..."]})]}):n.jsxs("div",{className:"cedros-admin__messaging-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="messages"?"cedros-admin__tab--active":""}`,onClick:()=>o("messages"),children:"Messages"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="email"?"cedros-admin__tab--active":""}`,onClick:()=>o("email"),children:"Email"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="webhooks"?"cedros-admin__tab--active":""}`,onClick:()=>o("webhooks"),children:"Webhooks"}),n.jsx("div",{style:{flex:1}}),n.jsx(lh,{status:w,error:j})]}),n.jsx(Yt,{message:u,onRetry:g}),n.jsxs("div",{className:"cedros-admin__tab-content",style:{marginTop:"1rem"},children:[s==="messages"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Enable or disable notification types. Configure the delivery settings in the Email or Webhooks tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[n.jsx(tc,{checked:a.email_enabled,onChange:()=>b("email_enabled",!a.email_enabled)}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:500},children:"Email Confirmation"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send order confirmation emails to customers after successful purchase."}),n.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Email configuration"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[n.jsx(tc,{checked:a.webhook_enabled,onChange:()=>b("webhook_enabled",!a.webhook_enabled)}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:500},children:"Admin Purchase Notification"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send webhook notifications to your server when a purchase is completed."}),n.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Webhook configuration"})]})]})]})]}),s==="email"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Configure your email provider for sending customer notifications."}),!a.email_enabled&&n.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Email notifications are disabled. Enable them in the Messages tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.email_enabled?1:.5},children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Host"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_host,onChange:v=>b("smtp_host",v.target.value),placeholder:"smtp.example.com",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Port"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.smtp_port,onChange:v=>b("smtp_port",parseInt(v.target.value)||587),placeholder:"587",disabled:!a.email_enabled,style:{maxWidth:120}})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Username"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_username,onChange:v=>b("smtp_username",v.target.value),placeholder:"username or API key",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Password"}),n.jsx("input",{type:"password",className:"cedros-admin__input",value:h.has("smtp_password")?a.smtp_password:"",onChange:v=>b("smtp_password",v.target.value),placeholder:a.smtp_password?"••••••••":"Enter password",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"From Email"}),n.jsx("input",{type:"email",className:"cedros-admin__input",value:a.from_email,onChange:v=>b("from_email",v.target.value),placeholder:"orders@yourstore.com",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"From Name"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.from_name,onChange:v=>b("from_name",v.target.value),placeholder:"Your Store",disabled:!a.email_enabled})]})]})]}),s==="webhooks"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Configure webhook endpoint for receiving purchase notifications."}),!a.webhook_enabled&&n.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Webhook notifications are disabled. Enable them in the Messages tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.webhook_enabled?1:.5},children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Webhook URL"}),n.jsx("input",{type:"url",className:"cedros-admin__input",value:a.webhook_url,onChange:v=>b("webhook_url",v.target.value),placeholder:"https://api.yoursite.com/webhooks/orders",disabled:!a.webhook_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Webhook Secret"}),n.jsx("input",{type:"password",className:"cedros-admin__input",value:h.has("webhook_secret")?a.webhook_secret:"",onChange:v=>b("webhook_secret",v.target.value),placeholder:a.webhook_secret?"••••••••":"Enter secret for HMAC-SHA256",disabled:!a.webhook_enabled}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.75rem",opacity:.6},children:"Used for HMAC-SHA256 signature verification"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Timeout (seconds)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.webhook_timeout,onChange:v=>b("webhook_timeout",parseInt(v.target.value)||30),placeholder:"30",disabled:!a.webhook_enabled,style:{maxWidth:120}})]})]})]})]})]})}function lh({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"}),e==="saving"&&n.jsxs(n.Fragment,{children:[Q.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[Q.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})]})}function tc({checked:e,onChange:t,disabled:r=!1}){return n.jsx("button",{type:"button",role:"switch","aria-checked":e,disabled:r,onClick:t,style:{position:"relative",width:44,height:24,borderRadius:12,border:"none",backgroundColor:e?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:r?"not-allowed":"pointer",transition:"background-color 0.2s",flexShrink:0,opacity:r?.5:1},children:n.jsx("span",{style:{position:"absolute",top:2,left:e?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"white",boxShadow:"0 1px 3px rgba(0,0,0,0.2)",transition:"left 0.2s"}})})}const dh=Object.freeze(Object.defineProperty({__proto__:null,MessagingSection:Zl},Symbol.toStringTag,{value:"Module"}));function Gl({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(!0),[l,d]=y.useState(!1),[m,u]=y.useState(null),[p,h]=y.useState(!1),[_,g]=y.useState(""),[f,w]=y.useState("all"),[j,b]=y.useState(null),[v,k]=y.useState(null),[R,N]=y.useState({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),C=y.useCallback(async()=>{c(!0);try{k(null);let z;const Z=`/admin/faqs?limit=${r}`;if(s?.isAuthenticated())z=await s.fetchWithAuth(Z);else{const K={"Content-Type":"application/json"};t&&(K["X-API-Key"]=t);const L=await fetch(`${e}${Z}`,{headers:K});if(!L.ok)throw new Error(`Failed to fetch FAQs: ${L.status}`);z=await L.json()}a(z.faqs||[])}catch{a([]),k("Failed to load FAQs")}finally{c(!1)}},[e,t,r,s]);y.useEffect(()=>{C()},[C]);const T=async z=>{if(z.preventDefault(),!(!R.question.trim()||!R.answer.trim())){h(!0);try{const Z=R.keywordsCsv.split(",").map(L=>L.trim().toLowerCase()).filter(Boolean),K={question:R.question.trim(),answer:R.answer.trim(),keywords:Z,active:R.active,useInChat:R.useInChat,displayOnPage:R.displayOnPage};if(m){const L=`/admin/faqs/${m.id}`;if(s?.isAuthenticated())await s.fetchWithAuth(L,{method:"PUT",body:JSON.stringify(K)});else{const W={"Content-Type":"application/json"};t&&(W["X-API-Key"]=t);const Y=await fetch(`${e}${L}`,{method:"PUT",headers:W,body:JSON.stringify(K)});if(!Y.ok)throw new Error(`Failed to update FAQ: ${Y.status}`)}}else if(s?.isAuthenticated())await s.fetchWithAuth("/admin/faqs",{method:"POST",body:JSON.stringify(K)});else{const L={"Content-Type":"application/json"};t&&(L["X-API-Key"]=t);const W=await fetch(`${e}/admin/faqs`,{method:"POST",headers:L,body:JSON.stringify(K)});if(!W.ok)throw new Error(`Failed to create FAQ: ${W.status}`)}S(),C()}catch{k(m?"Failed to update FAQ":"Failed to create FAQ")}finally{h(!1)}}},O=async z=>{try{const Z=`/admin/faqs/${z}`;if(s?.isAuthenticated())await s.fetchWithAuth(Z,{method:"DELETE"});else{const K={"Content-Type":"application/json"};t&&(K["X-API-Key"]=t);const L=await fetch(`${e}${Z}`,{method:"DELETE",headers:K});if(!L.ok)throw new Error(`Failed to delete FAQ: ${L.status}`)}C()}catch{k("Failed to delete FAQ")}b(null)},$=async z=>{try{const Z=`/admin/faqs/${z.id}`,K={...z,active:!z.active};if(s?.isAuthenticated())await s.fetchWithAuth(Z,{method:"PUT",body:JSON.stringify(K)});else{const L={"Content-Type":"application/json"};t&&(L["X-API-Key"]=t);const W=await fetch(`${e}${Z}`,{method:"PUT",headers:L,body:JSON.stringify(K)});if(!W.ok)throw new Error(`Failed to update FAQ: ${W.status}`)}C()}catch{k("Failed to update FAQ status")}},S=()=>{N({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),u(null),d(!1)},A=z=>{N({question:z.question,answer:z.answer,keywordsCsv:z.keywords.join(", "),active:z.active,useInChat:z.useInChat??!0,displayOnPage:z.displayOnPage??!0}),u(z),d(!0)},I=o.length,B=o.filter(z=>z.active).length,D=o.filter(z=>z.active&&z.useInChat).length,E=o.filter(z=>z.active&&z.displayOnPage).length,P=y.useMemo(()=>o.filter(z=>{if(f==="active"&&!z.active||f==="inactive"&&z.active)return!1;if(_){const Z=_.toLowerCase();return z.question.toLowerCase().includes(Z)||z.answer.toLowerCase().includes(Z)||z.keywords.some(K=>K.includes(Z))}return!0}),[o,f,_]);return n.jsxs("div",{className:"cedros-admin__faqs",children:[n.jsx(Yt,{message:v,onRetry:C}),n.jsx(rr,{stats:[{label:"Total FAQs",value:I},{label:"Active",value:B,variant:"success"},{label:"In Chat",value:D},{label:"On Page",value:E}]}),n.jsxs("div",{className:"cedros-admin__section",children:[n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsxs("div",{className:"cedros-admin__section-header-left",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Knowledge Base"}),n.jsx("p",{className:"cedros-admin__section-subtitle",children:"Manage FAQs for the AI chat assistant and public FAQ page."})]}),n.jsx("div",{className:"cedros-admin__section-header-right",children:n.jsxs("button",{className:"cedros-admin__btn cedros-admin__btn--primary",onClick:()=>{S(),d(!0)},children:[Q.plus," Add FAQ"]})})]}),n.jsxs("div",{className:"cedros-admin__filters",style:{display:"flex",gap:"1rem",marginBottom:"1rem"},children:[n.jsx("input",{type:"text",placeholder:"Search FAQs...",value:_,onChange:z=>g(z.target.value),className:"cedros-admin__input",style:{flex:1,maxWidth:300}}),n.jsxs("select",{value:f,onChange:z=>w(z.target.value),className:"cedros-admin__select",children:[n.jsx("option",{value:"all",children:"All Status"}),n.jsx("option",{value:"active",children:"Active Only"}),n.jsx("option",{value:"inactive",children:"Inactive Only"})]})]}),l&&n.jsx("div",{className:"cedros-admin__form-container",style:{marginBottom:"1.5rem"},children:n.jsxs("form",{onSubmit:T,className:"cedros-admin__form",children:[n.jsxs("div",{className:"cedros-admin__form-header",children:[n.jsx("h4",{children:m?"Edit FAQ":"Add New FAQ"}),n.jsx("button",{type:"button",className:"cedros-admin__btn--icon",onClick:S,children:Q.close})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Question *"}),n.jsx("input",{type:"text",value:R.question,onChange:z=>N(Z=>({...Z,question:z.target.value})),className:"cedros-admin__input",placeholder:"What is your return policy?",required:!0})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Answer *"}),n.jsx("textarea",{value:R.answer,onChange:z=>N(Z=>({...Z,answer:z.target.value})),className:"cedros-admin__textarea",placeholder:"We accept returns within 30 days...",rows:4,required:!0}),n.jsx("span",{className:"cedros-admin__hint",children:"Supports markdown formatting."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Keywords"}),n.jsx("input",{type:"text",value:R.keywordsCsv,onChange:z=>N(Z=>({...Z,keywordsCsv:z.target.value})),className:"cedros-admin__input",placeholder:"returns, refund, policy"}),n.jsx("span",{className:"cedros-admin__hint",children:"Comma-separated keywords to help AI find this FAQ."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:R.active,onChange:z=>N(Z=>({...Z,active:z.target.checked}))}),n.jsx("span",{children:"Active"})]}),n.jsx("span",{className:"cedros-admin__hint",children:"Inactive FAQs won't appear anywhere."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Visibility"}),n.jsxs("div",{className:"cedros-admin__checkbox-group",children:[n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:R.useInChat,onChange:z=>N(Z=>({...Z,useInChat:z.target.checked}))}),n.jsx("span",{children:"Use in AI Chat"})]}),n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:R.displayOnPage,onChange:z=>N(Z=>({...Z,displayOnPage:z.target.checked}))}),n.jsx("span",{children:"Display on FAQ Page"})]})]}),n.jsx("span",{className:"cedros-admin__hint",children:"Choose where this FAQ should appear."})]}),n.jsxs("div",{className:"cedros-admin__form-actions",children:[n.jsx("button",{type:"button",className:"cedros-admin__btn",onClick:S,children:"Cancel"}),n.jsx("button",{type:"submit",className:"cedros-admin__btn cedros-admin__btn--primary",disabled:p||!R.question.trim()||!R.answer.trim(),children:p?Q.loading:m?"Update FAQ":"Create FAQ"})]})]})}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading,n.jsx("span",{children:"Loading FAQs..."})]}):P.length===0?n.jsx("div",{className:"cedros-admin__empty",children:n.jsx("p",{children:_||f!=="all"?"No FAQs match your filters.":"No FAQs yet. Add one to get started."})}):n.jsx("div",{className:"cedros-admin__faq-list",children:P.map(z=>n.jsxs("div",{className:`cedros-admin__faq-item ${z.active?"":"cedros-admin__faq-item--inactive"}`,children:[n.jsxs("div",{className:"cedros-admin__faq-content",children:[n.jsxs("div",{className:"cedros-admin__faq-question",children:[n.jsx("span",{className:`cedros-admin__status-dot ${z.active?"cedros-admin__status-dot--active":"cedros-admin__status-dot--inactive"}`}),z.question]}),n.jsx("div",{className:"cedros-admin__faq-answer",children:z.answer}),n.jsxs("div",{className:"cedros-admin__faq-meta",children:[z.keywords.length>0&&n.jsx("div",{className:"cedros-admin__faq-keywords",children:z.keywords.map(Z=>n.jsx("span",{className:"cedros-admin__tag",children:Z},Z))}),n.jsxs("div",{className:"cedros-admin__faq-visibility",children:[z.useInChat&&n.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--chat",title:"Used in AI Chat",children:[Q.chat," Chat"]}),z.displayOnPage&&n.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--page",title:"Displayed on FAQ Page",children:[Q.globe," Page"]})]})]})]}),n.jsxs("div",{className:"cedros-admin__faq-actions",children:[n.jsx("button",{className:"cedros-admin__btn--icon",onClick:()=>$(z),title:z.active?"Deactivate":"Activate",children:z.active?Q.eyeOff:Q.eye}),n.jsx("button",{className:"cedros-admin__btn--icon",onClick:()=>A(z),title:"Edit",children:Q.edit}),n.jsx("button",{className:"cedros-admin__btn--icon cedros-admin__btn--danger",onClick:()=>b(z.id),title:"Delete",children:Q.trash})]}),j===z.id&&n.jsx("div",{className:"cedros-admin__confirm-overlay",children:n.jsxs("div",{className:"cedros-admin__confirm-dialog",children:[n.jsx("p",{children:"Delete this FAQ?"}),n.jsxs("div",{className:"cedros-admin__confirm-actions",children:[n.jsx("button",{className:"cedros-admin__btn",onClick:()=>b(null),children:"Cancel"}),n.jsx("button",{className:"cedros-admin__btn cedros-admin__btn--danger",onClick:()=>O(z.id),children:"Delete"})]})]})})]},z.id))})]})]})}const uh=Object.freeze(Object.defineProperty({__proto__:null,FAQSection:Gl},Symbol.toStringTag,{value:"Module"}));class mh{serverUrl;walletSigner=null;jwtToken=null;isAdmin=!1;constructor(t){this.serverUrl=t}getAuthMethod(){return this.walletSigner?.publicKey&&this.walletSigner.signMessage?"wallet":this.jwtToken&&this.isAdmin?"cedros-login":"none"}isAuthenticated(){return this.getAuthMethod()!=="none"}setWalletSigner(t){this.walletSigner=t,J.getLogger().debug("[AdminAuthManager] Wallet signer updated:",!!t?.publicKey)}setCedrosLoginAuth(t,r){this.jwtToken=t,this.isAdmin=r,J.getLogger().debug("[AdminAuthManager] Cedros-login auth updated:",{hasToken:!!t,isAdmin:r})}async createAuthHeaders(t){const r=this.getAuthMethod();if(r==="wallet")return this.createWalletAuthHeaders(t);if(r==="cedros-login")return this.createJwtAuthHeaders();throw new Error("No admin authentication configured. Connect a wallet or sign in as admin.")}async createWalletAuthHeaders(t){if(!this.walletSigner?.publicKey||!this.walletSigner.signMessage)throw new Error("Wallet not connected or does not support message signing");const r=await this.fetchNonce(t),s=new TextEncoder().encode(r.nonce_id),o=await this.walletSigner.signMessage(s),a=Zi.bs58.encode(this.walletSigner.publicKey.toBytes()),i=Zi.bs58.encode(o);return{"X-Signer":a,"X-Message":r.nonce_id,"X-Signature":i}}createJwtAuthHeaders(){if(!this.jwtToken)throw new Error("No JWT token available");return{Authorization:`Bearer ${this.jwtToken}`}}async fetchNonce(t){const r=`${this.serverUrl}/paywall/v1/nonce`;J.getLogger().debug("[AdminAuthManager] Fetching nonce for purpose:",t);const s=await J.fetchWithTimeout(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({purpose:t})});if(!s.ok){const o=await s.text();throw new Error(`Failed to fetch nonce: ${s.status} ${o}`)}return await s.json()}async fetchWithAuth(t,r={}){if(this.getAuthMethod()==="none")throw new Error("No admin authentication configured");const o=this.getPurposeFromPath(t,r.method||"GET"),a=await this.createAuthHeaders(o),i={"Content-Type":"application/json",...r.headers||{},...a},c=await J.fetchWithTimeout(`${this.serverUrl}${t}`,{...r,headers:i});if(!c.ok){const l=await c.text();throw new Error(`Admin API error ${c.status}: ${l}`)}return await c.json()}getPurposeFromPath(t,r){const o={"/admin/stats":{GET:"admin_stats"},"/admin/products":{GET:"admin_products_list",POST:"admin_products_create"},"/admin/transactions":{GET:"admin_transactions_list"},"/admin/coupons":{GET:"admin_coupons_list",POST:"admin_coupons_create"},"/admin/refunds":{GET:"admin_refunds_list"},"/admin/config":{GET:"admin_config_list"}}[t];if(o?.[r])return o[r];if(t.startsWith("/admin/products/")){if(r==="PUT")return"admin_products_update";if(r==="DELETE")return"admin_products_delete"}if(t.startsWith("/admin/coupons/")){if(r==="PUT")return"admin_coupons_update";if(r==="DELETE")return"admin_coupons_delete"}if(t.startsWith("/admin/refunds/")&&t.includes("/process"))return"admin_refunds_process";if(t.startsWith("/admin/config/")){if(r==="GET")return"admin_config_get";if(r==="PUT")return"admin_config_update";if(r==="PATCH")return"admin_config_patch"}return`admin_${r.toLowerCase()}`}}function ph({serverUrl:e,cedrosLoginToken:t,isAdmin:r=!1}){const s=ja.useWallet(),o=y.useMemo(()=>{const u=new mh(e);return u.setCedrosLoginAuth(t??null,r),u},[e,t,r]);y.useEffect(()=>{s.publicKey&&s.signMessage?o.setWalletSigner({publicKey:s.publicKey,signMessage:s.signMessage}):o.setWalletSigner(null)},[o,s.publicKey,s.signMessage]);const a=o.getAuthMethod(),i=o.isAuthenticated(),c=!!(s.publicKey&&s.signMessage),l=!!(t&&r),d=y.useMemo(()=>{if(!s.publicKey)return null;const u=s.publicKey.toBase58();return`${u.slice(0,4)}...${u.slice(-4)}`},[s.publicKey]),m=y.useCallback((u,p)=>o.fetchWithAuth(u,p),[o]);return{authMethod:a,isAuthenticated:i,walletConnected:c,walletAddress:d,cedrosLoginAvailable:l,authManager:o,fetchWithAuth:m}}const Ql=[{label:"Menu",sections:[{id:"transactions",label:"Transactions",icon:Q.transactions},{id:"products",label:"Products",icon:Q.products},{id:"subscriptions",label:"Subscriptions",icon:Q.calendarRepeat},{id:"coupons",label:"Coupons",icon:Q.coupons},{id:"refunds",label:"Refunds",icon:Q.refunds}]},{label:"Configuration",collapsible:!0,sections:[{id:"storefront",label:"Storefront",icon:Q.storefront},{id:"ai-settings",label:"Store AI",icon:Q.brain},{id:"faqs",label:"Knowledge Base",icon:Q.faq},{id:"payment-settings",label:"Payment Options",icon:Q.creditCard},{id:"messaging",label:"Store Messages",icon:Q.mail},{id:"settings",label:"Store Server",icon:Q.server}]}],fh=Ql.flatMap(e=>e.sections);function hh(){const[e,t]=y.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");return y.useEffect(()=>{const r=window.matchMedia("(prefers-color-scheme: dark)"),s=o=>t(o.matches?"dark":"light");return r.addEventListener("change",s),()=>r.removeEventListener("change",s)},[]),e}function gh(e,t,r){return e!=="system"?e:t||r}function xh({serverUrl:e,apiKey:t,title:r="Cedros Pay",sections:s=["transactions","products","subscriptions","coupons","refunds","storefront","ai-settings","faqs","payment-settings","messaging","settings"],defaultSection:o="transactions",refreshInterval:a=3e4,pageSize:i=20,onSectionChange:c,className:l="",cedrosLoginToken:d,isAdmin:m=!1,theme:u="system"}){const[p,h]=y.useState(o),[_,g]=y.useState(!0),[f,w]=y.useState(new Set),j=y.useCallback($=>{w(S=>{const A=new Set(S);return A.has($)?A.delete($):A.add($),A})},[]),b=J.useCedrosThemeOptional(),v=hh(),R=gh(u,b?.mode??null,v)==="dark"?"cedros-admin--dark":"",{authManager:N}=ph({serverUrl:e,cedrosLoginToken:d,isAdmin:m}),C=y.useCallback($=>{h($),c?.($)},[c]),O=fh.filter($=>s.includes($.id)).find($=>$.id===p);return y.useEffect(()=>{const $=setTimeout(()=>g(!1),500);return()=>clearTimeout($)},[]),_?n.jsxs("div",{className:`cedros-admin cedros-admin--loading ${R} ${l}`,children:[Q.loading,n.jsx("span",{className:"cedros-admin__loading-text",children:"Loading dashboard..."})]}):n.jsxs("div",{className:`cedros-admin ${R} ${l}`,children:[n.jsxs("aside",{className:"cedros-admin__sidebar",children:[n.jsx("div",{className:"cedros-admin__sidebar-header",children:n.jsxs("div",{className:"cedros-admin__logo",children:[Q.wallet,n.jsx("span",{className:"cedros-admin__logo-text",children:r})]})}),n.jsx("nav",{className:"cedros-admin__nav",children:Ql.map($=>{const S=$.sections.filter(I=>s.includes(I.id));if(S.length===0)return null;const A=$.collapsible&&f.has($.label);return n.jsxs("div",{className:"cedros-admin__nav-group",children:[$.collapsible?n.jsxs("button",{type:"button",className:"cedros-admin__nav-label cedros-admin__nav-label--collapsible",onClick:()=>j($.label),"aria-expanded":!A,children:[$.label,n.jsx("span",{className:`cedros-admin__nav-label-icon ${A?"":"cedros-admin__nav-label-icon--expanded"}`,children:Q.chevronRight})]}):n.jsx("span",{className:"cedros-admin__nav-label",children:$.label}),!A&&S.map(I=>n.jsxs("button",{type:"button",className:`cedros-admin__nav-item ${p===I.id?"cedros-admin__nav-item--active":""}`,onClick:()=>C(I.id),"aria-current":p===I.id?"page":void 0,children:[n.jsx("span",{className:"cedros-admin__nav-icon",children:I.icon}),n.jsx("span",{className:"cedros-admin__nav-text",children:I.label})]},I.id))]},$.label)})})]}),n.jsxs("main",{className:"cedros-admin__main",children:[n.jsx("header",{className:"cedros-admin__header",children:n.jsxs("div",{className:"cedros-admin__breadcrumb",children:[n.jsx("span",{className:"cedros-admin__breadcrumb-root",children:r}),n.jsx("span",{className:"cedros-admin__breadcrumb-sep",children:Q.chevronRight}),n.jsx("span",{className:"cedros-admin__breadcrumb-current",children:O?.label})]})}),n.jsxs("div",{className:"cedros-admin__content",children:[p==="products"&&n.jsx(Ll,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="subscriptions"&&n.jsx(Wl,{serverUrl:e,apiKey:t,authManager:N}),p==="transactions"&&n.jsx($l,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="coupons"&&n.jsx(zl,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="refunds"&&n.jsx(Fl,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="storefront"&&n.jsx(Vl,{serverUrl:e,apiKey:t,authManager:N}),p==="ai-settings"&&n.jsx(ql,{serverUrl:e,apiKey:t,authManager:N}),p==="faqs"&&n.jsx(Gl,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="payment-settings"&&n.jsx(Hl,{serverUrl:e,apiKey:t,authManager:N}),p==="messaging"&&n.jsx(Zl,{serverUrl:e,apiKey:t,authManager:N}),p==="settings"&&n.jsx(Ia,{serverUrl:e,apiKey:t,authManager:N})]})]})]})}const Pt=e=>y.lazy(async()=>{const s=(await e()).default;return{default:({pluginContext:a})=>{const i={serverUrl:a.serverUrl};return n.jsx(s,{...i})}}}),yh={id:"cedros-pay",name:"Cedros Pay",version:"1.0.0",sections:[{id:"transactions",label:"Transactions",icon:Q.transactions,group:"Store",order:0},{id:"products",label:"Products",icon:Q.products,group:"Store",order:1},{id:"subscriptions",label:"Subscriptions",icon:Q.subscriptions,group:"Store",order:2},{id:"coupons",label:"Coupons",icon:Q.coupons,group:"Store",order:3},{id:"refunds",label:"Refunds",icon:Q.refunds,group:"Store",order:4},{id:"storefront",label:"Storefront",icon:Q.storefront,group:"Configuration",order:10},{id:"ai-settings",label:"Store AI",icon:Q.ai,group:"Configuration",order:11},{id:"faqs",label:"Knowledge Base",icon:Q.faq,group:"Configuration",order:12},{id:"payment-settings",label:"Payment Options",icon:Q.wallet,group:"Configuration",order:13},{id:"messaging",label:"Store Messages",icon:Q.notifications,group:"Configuration",order:14},{id:"settings",label:"Store Server",icon:Q.settings,group:"Configuration",order:15}],groups:[{id:"Store",label:"Store",order:1},{id:"Configuration",label:"Configuration",order:2,defaultCollapsed:!0}],components:{products:Pt(()=>Promise.resolve().then(()=>require("./sections-DxzkNp5I.js")).then(e=>({default:e.ProductsSection}))),subscriptions:Pt(()=>Promise.resolve().then(()=>Jf).then(e=>({default:e.SubscriptionsSection}))),transactions:Pt(()=>Promise.resolve().then(()=>require("./sections-DxzkNp5I.js")).then(e=>({default:e.TransactionsSection}))),coupons:Pt(()=>Promise.resolve().then(()=>require("./sections-DxzkNp5I.js")).then(e=>({default:e.CouponsSection}))),refunds:Pt(()=>Promise.resolve().then(()=>require("./sections-DxzkNp5I.js")).then(e=>({default:e.RefundsSection}))),storefront:Pt(()=>Promise.resolve().then(()=>rh).then(e=>({default:e.StorefrontSection}))),"ai-settings":Pt(()=>Promise.resolve().then(()=>ih).then(e=>({default:e.AISettingsSection}))),faqs:Pt(()=>Promise.resolve().then(()=>uh).then(e=>({default:e.FAQSection}))),"payment-settings":Pt(()=>Promise.resolve().then(()=>ch).then(e=>({default:e.PaymentSettingsSection}))),messaging:Pt(()=>Promise.resolve().then(()=>dh).then(e=>({default:e.MessagingSection}))),settings:Pt(()=>Promise.resolve().then(()=>Yf).then(e=>({default:e.SettingsSection})))},createPluginContext(e){const t=e.cedrosPay,r=e.cedrosLogin;return{serverUrl:t?.serverUrl||r?.serverUrl||"",userId:r?.user?.id,getAccessToken:()=>r?.getAccessToken?.()||t?.jwtToken||null,hasPermission:o=>this.checkPermission(o,e),orgId:e.org?.orgId,pluginData:{walletAddress:t?.walletAddress}}},checkPermission(e,t){return t.org?.permissions?t.org.permissions.includes(e):!!(t.cedrosLogin?.user||t.cedrosPay?.jwtToken||t.cedrosPay?.walletAddress)},cssNamespace:"cedros-dashboard"};function vh({product:e,paymentMethod:t,showOriginalPrice:r=!1,className:s="",style:o={}}){const a=t==="stripe",i=a?e.fiatAmount:e.cryptoAmount,c=a?e.effectiveFiatAmount:e.effectiveCryptoAmount,l=a?e.fiatCurrency.toUpperCase():e.cryptoToken,d=a?e.hasStripeCoupon:e.hasCryptoCoupon,m=a?e.stripeDiscountPercent:e.cryptoDiscountPercent;return n.jsxs("div",{className:s,style:o,children:[r&&d&&n.jsxs("span",{style:{textDecoration:"line-through",opacity:.6,marginRight:"0.5rem",fontSize:"0.875em"},children:[i.toFixed(2)," ",l]}),n.jsxs("span",{style:{fontWeight:600},children:[c.toFixed(2)," ",l]}),d&&m>0&&n.jsxs("span",{style:{marginLeft:"0.5rem",padding:"0.125rem 0.375rem",backgroundColor:"#10b981",color:"white",borderRadius:"0.25rem",fontSize:"0.75em",fontWeight:600},children:[m,"% OFF"]})]})}function bh({product:e,paymentMethod:t,className:r="",style:s={}}){const o=t==="stripe",a=o?e.hasStripeCoupon:e.hasCryptoCoupon,i=o?e.stripeDiscountPercent:e.cryptoDiscountPercent,c=o?e.stripeCouponCode:e.cryptoCouponCode;if(!a||i===0)return null;const l=o?`${i}% off with card!`:`${i}% off with crypto!`;return n.jsxs("div",{className:r,style:{display:"inline-flex",alignItems:"center",padding:"0.5rem 0.75rem",backgroundColor:o?"#6366f1":"#10b981",color:"white",borderRadius:"0.375rem",fontSize:"0.875rem",fontWeight:600,...s},children:[l,c&&n.jsxs("span",{style:{marginLeft:"0.5rem",opacity:.8,fontSize:"0.75em",fontWeight:400},children:["(",c,")"]})]})}function Yl(){const{subscriptionManager:e}=J.useCedrosContext(),[t,r]=y.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),s=y.useCallback(async c=>{r(d=>({...d,status:"loading",error:null}));const l=await e.processSubscription(c);return r(d=>({...d,status:l.success?"success":"error",error:l.success?null:l.error||"Subscription failed",sessionId:l.success&&l.transactionId||null})),l},[e]),o=y.useCallback(async c=>{r(l=>({...l,status:"checking",error:null}));try{const l=await e.checkSubscriptionStatus(c);return r(d=>({...d,status:l.active?"success":"idle",subscriptionStatus:l.status,expiresAt:l.expiresAt||l.currentPeriodEnd||null})),l}catch(l){const d=l instanceof Error?l.message:"Failed to check subscription status";throw r(m=>({...m,status:"error",error:d})),l}},[e]),a=y.useCallback(async(c,l,d)=>{r(m=>({...m,status:"loading",error:null}));try{const m=await e.requestSubscriptionQuote(c,l,d);return r(u=>({...u,status:"idle"})),m}catch(m){const u=m instanceof Error?m.message:"Failed to get subscription quote";throw r(p=>({...p,status:"error",error:u})),m}},[e]),i=y.useCallback(()=>{r({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null})},[]);return{...t,processSubscription:s,checkStatus:o,requestQuote:a,reset:i}}function wh({resource:e,interval:t,intervalDays:r,trialDays:s,successUrl:o,cancelUrl:a,metadata:i,customerEmail:c,couponCode:l,label:d,disabled:m=!1,onAttempt:u,onSuccess:p,onError:h,className:_=""}){const{status:g,error:f,sessionId:w,processSubscription:j}=Yl(),b=J.useCedrosTheme(),{t:v,translations:k}=xn(),R=d||v("ui.subscribe"),N=b.unstyled?_:`${b.className} cedros-theme__stripe-button ${_}`.trim(),C=f&&typeof f!="string"?f?.code??null:null,O=f?typeof f=="string"?f:(D=>{if(!D||!k)return"";const E=k.errors[D];return E?E.action?`${E.message} ${E.action}`:E.message:""})(C):null,$=y.useCallback(async()=>{J.getLogger().debug("[SubscribeButton] executeSubscription:",{resource:e,interval:t,intervalDays:r,trialDays:s,couponCode:l}),Ln("stripe",e),u&&u("stripe"),un("stripe",e);const D=await j({resource:e,interval:t,intervalDays:r,trialDays:s,customerEmail:c,metadata:i,couponCode:l,successUrl:o,cancelUrl:a});D.success&&D.transactionId?($n("stripe",D.transactionId,e),p&&p(D.transactionId)):!D.success&&D.error&&(kt("stripe",D.error,e),h&&h(D.error))},[e,t,r,s,c,i,l,o,a,j,u,p,h]),S=y.useMemo(()=>`subscribe-${e}-${t}`,[e,t]),A=y.useMemo(()=>Mn(S,$),[S,$]),I=g==="loading",B=m||I;return n.jsxs("div",{className:N,style:b.unstyled?{}:b.style,children:[n.jsx("button",{onClick:A,disabled:B,className:b.unstyled?_:"cedros-theme__button cedros-theme__stripe",type:"button",children:I?v("ui.processing"):R}),O&&n.jsx("div",{className:b.unstyled?"":"cedros-theme__error",children:O}),w&&n.jsx("div",{className:b.unstyled?"":"cedros-theme__success",children:v("ui.redirecting_to_checkout")})]})}function Kl(){const{subscriptionManager:e,creditsManager:t}=J.useCedrosContext(),[r,s]=y.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null}),o=y.useCallback(async(l,d)=>{s(m=>({...m,status:"checking",error:null}));try{const m=await e.checkSubscriptionStatus({resource:l,userId:d});return s(u=>({...u,status:m.active?"success":"idle",subscriptionStatus:m.status,expiresAt:m.expiresAt||m.currentPeriodEnd||null})),m}catch(m){const u=J.formatError(m,"Failed to check subscription status");return s(p=>({...p,status:"error",error:u})),null}},[e]),a=y.useCallback(async(l,d,m)=>{s(u=>({...u,status:"loading",error:null}));try{const u=await t.requestQuote(l,m?.couponCode);return s(p=>({...p,status:"idle",creditsRequirement:u})),u}catch(u){const p=J.formatError(u,"Failed to get subscription quote");return s(h=>({...h,status:"error",error:p})),null}},[t]),i=y.useCallback(async(l,d,m,u)=>{if(!m){const p="Authentication required for credits payment";return s(h=>({...h,status:"error",error:p})),{success:!1,error:p}}s(p=>({...p,status:"loading",error:null}));try{const p=await t.processPayment(l,m,u?.couponCode,{interval:d,...u?.intervalDays&&{intervalDays:String(u.intervalDays)}});return p.success?s({status:"success",error:null,sessionId:p.transactionId||null,subscriptionStatus:"active",expiresAt:null,creditsRequirement:null}):s(h=>({...h,status:"error",error:p.error||"Credits subscription payment failed"})),p}catch(p){const h=J.formatError(p,"Credits subscription payment failed");return s(_=>({..._,status:"error",error:h})),{success:!1,error:h}}},[t]),c=y.useCallback(()=>{s({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null})},[]);return{...r,checkStatus:o,requestQuote:a,processPayment:i,reset:c}}function _h({resource:e,interval:t,intervalDays:r,authToken:s,userId:o,couponCode:a,label:i,disabled:c=!1,onAttempt:l,onSuccess:d,onError:m,className:u="",hideMessages:p=!1,autoCheckStatus:h=!1}){const{status:_,error:g,subscriptionStatus:f,expiresAt:w,checkStatus:j,processPayment:b}=Kl(),v=J.useCedrosTheme(),{t:k,translations:R}=xn(),N=y.useRef(j);y.useEffect(()=>{N.current=j},[j]),y.useEffect(()=>{h&&o&&(J.getLogger().debug("[CreditsSubscribeButton] Auto-checking subscription status",{resource:e,userId:o}),N.current(e,o))},[h,o,e]);const C=i||k("ui.subscribe_with_credits")||"Subscribe with Credits",T=g&&typeof g!="string"?g?.code??null:null,$=g?typeof g=="string"?g:(Z=>{if(!Z||!R)return"";const K=R.errors[Z];return K?K.action?`${K.message} ${K.action}`:K.message:""})(T):null,S=y.useCallback(async()=>{if(J.getLogger().debug("[CreditsSubscribeButton] executeSubscriptionFlow",{resource:e,interval:t,intervalDays:r,hasAuthToken:!!s}),Ln("credits",e),l&&l("credits"),!s){const K="Authentication required: please log in to subscribe with credits";J.getLogger().error("[CreditsSubscribeButton]",K),kt("credits",K,e),m&&m(K);return}un("credits",e);const Z=await b(e,t,s,{couponCode:a,intervalDays:r});Z.success&&Z.transactionId?($n("credits",Z.transactionId,e),d&&d(Z.transactionId)):!Z.success&&Z.error&&(kt("credits",Z.error,e),m&&m(Z.error))},[e,t,r,s,a,b,l,d,m]),A=y.useMemo(()=>`credits-subscribe-${e}-${t}`,[e,t]),I=y.useMemo(()=>Mn(A,S,{cooldownMs:200,deduplicationWindowMs:0}),[A,S]),B=_==="loading"||_==="checking",D=f==="active"||f==="trialing",E=c||B||D;let P=C;if(B)P=k("ui.processing");else if(D&&w){const Z=new Date(w).toLocaleDateString();P=`${k("ui.subscribed_until")} ${Z}`}else D&&(P=k("ui.subscribed"));const z=v.unstyled?u:`${v.className} cedros-theme__credits-button ${u}`.trim();return n.jsxs("div",{className:z,style:v.unstyled?{}:v.style,children:[n.jsx("button",{onClick:I,disabled:E,className:v.unstyled?u:"cedros-theme__button cedros-theme__credits",type:"button",children:P}),!p&&$&&n.jsx("div",{className:v.unstyled?"":"cedros-theme__error",children:$}),!p&&D&&n.jsx("div",{className:v.unstyled?"":"cedros-theme__success",children:k("ui.subscription_active")})]})}function Xl(){const{subscriptionChangeManager:e}=J.useCedrosContext(),[t,r]=y.useState({status:"idle",error:null,subscription:null,changePreview:null,userId:null}),s=y.useRef(t);s.current=t;const o=y.useCallback(async(u,p)=>{r(h=>({...h,status:"loading",error:null}));try{const h=await e.getDetails(u,p);return r(_=>({..._,status:"success",subscription:h,userId:p})),h}catch(h){const _=h instanceof Error?h.message:"Failed to load subscription";return r(g=>({...g,status:"error",error:_})),null}},[e]),a=y.useCallback(async(u,p,h,_)=>{r(g=>({...g,status:"loading",error:null}));try{const g={currentResource:u,newResource:p,userId:h,newInterval:_},f=await e.previewChange(g);return r(w=>({...w,status:"idle",changePreview:f})),f}catch(g){const f=g instanceof Error?g.message:"Failed to preview change";return r(w=>({...w,status:"error",error:f})),null}},[e]),i=y.useCallback(async u=>{const{subscription:p,userId:h}=s.current;if(!p||!h)return r(_=>({..._,status:"error",error:"No subscription loaded"})),null;r(_=>({..._,status:"loading",error:null}));try{const _={currentResource:p.resource,newResource:u.newResource,userId:h,newInterval:u.newInterval,prorationBehavior:u.prorationBehavior,immediate:u.immediate},g=await e.changeSubscription(_);return g.success?r(f=>({...f,status:"success",subscription:f.subscription?{...f.subscription,resource:g.newResource,interval:g.newInterval,status:g.status}:null,changePreview:null})):r(f=>({...f,status:"error",error:g.error||"Failed to change subscription"})),g}catch(_){const g=_ instanceof Error?_.message:"Failed to change subscription";return r(f=>({...f,status:"error",error:g})),null}},[e]),c=y.useCallback(async u=>{const{subscription:p,userId:h}=s.current;if(!p||!h)return r(_=>({..._,status:"error",error:"No subscription loaded"})),null;r(_=>({..._,status:"loading",error:null}));try{const _={resource:p.resource,userId:h,immediate:u},g=await e.cancel(_);if(g.success){const f=u?"canceled":p.status;r(w=>({...w,status:"success",subscription:w.subscription?{...w.subscription,status:f,cancelAtPeriodEnd:!u}:null}))}else r(f=>({...f,status:"error",error:g.error||"Failed to cancel subscription"}));return g}catch(_){const g=_ instanceof Error?_.message:"Failed to cancel subscription";return r(f=>({...f,status:"error",error:g})),null}},[e]),l=y.useCallback(async(u,p)=>{r(h=>({...h,status:"loading",error:null}));try{const h=await e.getBillingPortalUrl({userId:u,returnUrl:p});return window.location.href=h.url,h}catch(h){const _=h instanceof Error?h.message:"Failed to open billing portal";return r(g=>({...g,status:"error",error:_})),null}},[e]),d=y.useCallback(()=>{r(u=>({...u,changePreview:null}))},[]),m=y.useCallback(()=>{r({status:"idle",error:null,subscription:null,changePreview:null,userId:null})},[]);return{...t,loadSubscription:o,previewChange:a,changeSubscription:i,cancelSubscription:c,openBillingPortal:l,clearPreview:d,reset:m}}const jh={bg:"#fff",bgMuted:"#f9fafb",bgHighlight:"#eff6ff",text:"#111827",textMuted:"#6b7280",textFaint:"#9ca3af",border:"#e5e7eb",borderLight:"#f3f4f6",primary:"#3b82f6",error:"#ef4444",errorBg:"#fef2f2",errorBorder:"#fecaca",warningBg:"#fef3c7",warningBorder:"#fcd34d",warningText:"#92400e",buttonBg:"#f3f4f6",buttonBorder:"#d1d5db",buttonText:"#374151"},kh={bg:"#1e293b",bgMuted:"#334155",bgHighlight:"rgba(59, 130, 246, 0.15)",text:"#f1f5f9",textMuted:"#94a3b8",textFaint:"#64748b",border:"#475569",borderLight:"#334155",primary:"#3b82f6",error:"#ef4444",errorBg:"rgba(239, 68, 68, 0.15)",errorBorder:"rgba(239, 68, 68, 0.3)",warningBg:"rgba(245, 158, 11, 0.15)",warningBorder:"rgba(245, 158, 11, 0.3)",warningText:"#fbbf24",buttonBg:"#334155",buttonBorder:"#475569",buttonText:"#e2e8f0"};function Sh(e){const t=e?kh:jh;return{container:{padding:"24px",backgroundColor:t.bg,borderRadius:"8px",border:`1px solid ${t.border}`,fontFamily:"system-ui, -apple-system, sans-serif",color:t.text},error:{padding:"12px 16px",backgroundColor:t.errorBg,border:`1px solid ${t.errorBorder}`,borderRadius:"6px",color:t.error,marginBottom:"16px"},loading:{padding:"24px",textAlign:"center",color:t.textMuted},details:{marginBottom:"24px"},title:{margin:"0 0 16px 0",fontSize:"18px",fontWeight:600,color:t.text},detailRow:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"8px 0",borderBottom:`1px solid ${t.borderLight}`},label:{color:t.textMuted,fontSize:"14px"},value:{color:t.text,fontSize:"14px",fontWeight:500},statusBadge:{padding:"4px 8px",borderRadius:"4px",color:"#fff",fontSize:"12px",fontWeight:500,textTransform:"capitalize"},cancelNotice:{marginTop:"12px",padding:"8px 12px",backgroundColor:t.warningBg,border:`1px solid ${t.warningBorder}`,borderRadius:"6px",color:t.warningText,fontSize:"13px"},prorationPreview:{padding:"16px",backgroundColor:t.bgMuted,borderRadius:"8px",marginBottom:"24px"},previewTitle:{margin:"0 0 12px 0",fontSize:"16px",fontWeight:600,color:t.text},previewDetails:{marginBottom:"16px"},previewRow:{display:"flex",justifyContent:"space-between",padding:"6px 0",fontSize:"14px",color:t.textMuted},previewTotal:{borderTop:`1px solid ${t.border}`,marginTop:"8px",paddingTop:"12px",fontWeight:600,color:t.text},previewActions:{display:"flex",gap:"12px",justifyContent:"flex-end"},cancelButton:{padding:"8px 16px",backgroundColor:t.bg,border:`1px solid ${t.buttonBorder}`,borderRadius:"6px",color:t.buttonText,cursor:"pointer",fontSize:"14px"},confirmButton:{padding:"8px 16px",backgroundColor:t.primary,border:"none",borderRadius:"6px",color:"#fff",cursor:"pointer",fontSize:"14px",fontWeight:500},plansSection:{marginBottom:"24px"},plansTitle:{margin:"0 0 12px 0",fontSize:"16px",fontWeight:600,color:t.text},plansList:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))",gap:"16px"},planCard:{padding:"16px",backgroundColor:t.bg,border:`1px solid ${t.border}`,borderRadius:"8px",textAlign:"center"},currentPlan:{borderColor:t.primary,backgroundColor:t.bgHighlight},planName:{fontSize:"16px",fontWeight:600,color:t.text,marginBottom:"4px"},planPrice:{fontSize:"14px",color:t.textMuted,marginBottom:"8px"},planDescription:{fontSize:"12px",color:t.textFaint,marginBottom:"12px"},currentBadge:{display:"inline-block",padding:"4px 8px",backgroundColor:t.primary,color:"#fff",borderRadius:"4px",fontSize:"12px",fontWeight:500},changePlanButton:{padding:"8px 16px",backgroundColor:t.buttonBg,border:`1px solid ${t.buttonBorder}`,borderRadius:"6px",color:t.buttonText,cursor:"pointer",fontSize:"14px",width:"100%"},actions:{display:"flex",gap:"12px",justifyContent:"flex-end",paddingTop:"16px",borderTop:`1px solid ${t.border}`},portalButton:{padding:"10px 20px",backgroundColor:t.primary,border:"none",borderRadius:"6px",color:"#fff",cursor:"pointer",fontSize:"14px",fontWeight:500},cancelSubscriptionButton:{padding:"10px 20px",backgroundColor:t.bg,border:`1px solid ${t.error}`,borderRadius:"6px",color:t.error,cursor:"pointer",fontSize:"14px"}}}function Nn(e,t){return new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).format(e/100)}function Jl(e){return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}function Ch(e){switch(e){case"active":return"#22c55e";case"trialing":return"#3b82f6";case"past_due":return"#f59e0b";case"canceled":case"expired":return"#ef4444";default:return"#6b7280"}}function Nh({preview:e,onConfirm:t,onCancel:r,isLoading:s,styles:o}){const a=e.immediateAmount<0;return n.jsxs("div",{className:"cedros-proration-preview",style:o.prorationPreview,children:[n.jsx("h4",{style:o.previewTitle,children:"Change Preview"}),n.jsxs("div",{style:o.previewDetails,children:[n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Current plan:"}),n.jsxs("span",{children:[Nn(e.currentPlanPrice,e.currency),"/period"]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"New plan:"}),n.jsxs("span",{children:[Nn(e.newPlanPrice,e.currency),"/period"]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Days remaining:"}),n.jsxs("span",{children:[e.daysRemaining," days"]})]}),e.prorationDetails&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Unused credit:"}),n.jsxs("span",{children:["-",Nn(e.prorationDetails.unusedCredit,e.currency)]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"New plan cost:"}),n.jsx("span",{children:Nn(e.prorationDetails.newPlanCost,e.currency)})]})]}),n.jsxs("div",{style:{...o.previewRow,...o.previewTotal},children:[n.jsx("span",{children:a?"Credit to account:":"Amount due now:"}),n.jsx("span",{style:{color:a?"#22c55e":"#ef4444"},children:Nn(Math.abs(e.immediateAmount),e.currency)})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Effective date:"}),n.jsx("span",{children:Jl(e.effectiveDate)})]})]}),n.jsxs("div",{style:o.previewActions,children:[n.jsx("button",{onClick:r,style:o.cancelButton,disabled:s,children:"Cancel"}),n.jsx("button",{onClick:t,style:o.confirmButton,disabled:s,children:s?"Processing...":"Confirm Change"})]})]})}function Ph({resource:e,userId:t,availablePlans:r=[],onSubscriptionChanged:s,onSubscriptionCanceled:o,billingPortalReturnUrl:a,showBillingPortal:i=!1,className:c,style:l}){const{mode:d}=J.useCedrosTheme(),m=y.useMemo(()=>Sh(d==="dark"),[d]),{subscription:u,changePreview:p,status:h,error:_,loadSubscription:g,previewChange:f,changeSubscription:w,cancelSubscription:j,openBillingPortal:b,clearPreview:v}=Xl();y.useEffect(()=>{g(e,t)},[e,t,g]);const k=y.useCallback(async(O,$)=>{await f(e,O,t,$)},[e,t,f]),R=y.useCallback(async()=>{if(!p)return;const O=r.find(S=>S.price===p.newPlanPrice&&S.currency===p.currency);(await w({newResource:O?.resource||e,newInterval:O?.interval,immediate:!0}))?.success&&O&&s?.(O.resource,O.interval)},[p,r,e,w,s]),N=y.useCallback(async O=>{(await j(O))?.success&&o?.()},[j,o]),C=y.useCallback(()=>{b(t,a)},[t,a,b]),T=h==="loading";return n.jsxs("div",{className:`cedros-subscription-panel ${c||""}`,style:{...m.container,...l},children:[_&&n.jsx("div",{className:"cedros-subscription-error",style:m.error,children:_}),T&&!u&&n.jsx("div",{className:"cedros-subscription-loading",style:m.loading,children:"Loading subscription..."}),u&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"cedros-subscription-details",style:m.details,children:[n.jsx("h3",{style:m.title,children:"Current Subscription"}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Plan:"}),n.jsx("span",{style:m.value,children:u.resource})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Status:"}),n.jsx("span",{style:{...m.statusBadge,backgroundColor:Ch(u.status)},children:u.status})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Price:"}),n.jsxs("span",{style:m.value,children:[Nn(u.pricePerPeriod,u.currency),"/",u.interval]})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Current period ends:"}),n.jsx("span",{style:m.value,children:Jl(u.currentPeriodEnd)})]}),u.cancelAtPeriodEnd&&n.jsx("div",{style:m.cancelNotice,children:"Subscription will cancel at end of current period"})]}),p&&n.jsx(Nh,{preview:p,onConfirm:R,onCancel:v,isLoading:T,styles:m}),r.length>0&&!p&&n.jsxs("div",{className:"cedros-available-plans",style:m.plansSection,children:[n.jsx("h4",{style:m.plansTitle,children:"Available Plans"}),n.jsx("div",{style:m.plansList,children:r.map(O=>{const $=O.resource===u.resource;return n.jsxs("div",{style:{...m.planCard,...$?m.currentPlan:{}},children:[n.jsx("div",{style:m.planName,children:O.name}),n.jsxs("div",{style:m.planPrice,children:[Nn(O.price,O.currency),"/",O.interval]}),O.description&&n.jsx("div",{style:m.planDescription,children:O.description}),$?n.jsx("span",{style:m.currentBadge,children:"Current Plan"}):n.jsx("button",{onClick:()=>k(O.resource,O.interval),style:m.changePlanButton,disabled:T,children:O.price>u.pricePerPeriod?"Upgrade":"Downgrade"})]},O.resource)})})]}),n.jsxs("div",{className:"cedros-subscription-actions",style:m.actions,children:[i&&u.paymentMethod==="stripe"&&n.jsx("button",{onClick:C,style:m.portalButton,disabled:T,children:"Manage Billing"}),u.status==="active"&&!u.cancelAtPeriodEnd&&n.jsx("button",{onClick:()=>N(!1),style:m.cancelSubscriptionButton,disabled:T,children:"Cancel Subscription"})]})]})]})}function Ah(){if(typeof window>"u")return{passed:!0,severity:"info",message:"HTTPS check skipped (SSR environment)"};const e=window.location.protocol==="https:",t=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1";return e||t?{passed:!0,severity:"info",message:"HTTPS enforced"}:{passed:!1,severity:"error",message:"Page not served over HTTPS",recommendation:"Enable HTTPS for all payment pages. Stripe.js requires HTTPS in production."}}function Eh(){return typeof document>"u"?{passed:!0,severity:"info",message:"CSP check skipped (SSR environment)"}:document.querySelector('meta[http-equiv="Content-Security-Policy"]')?{passed:!0,severity:"info",message:"Content Security Policy detected"}:{passed:!1,severity:"warning",message:"No Content Security Policy detected",recommendation:"Configure CSP headers to protect against XSS and CDN compromise. Use generateCSP() helper from @cedros/pay-react."}}function Th(){return process.env.NODE_ENV==="development"||typeof window<"u"&&window.location.hostname==="localhost"?{passed:!0,severity:"info",message:"Running in development mode (some security checks relaxed)"}:{passed:!0,severity:"info",message:"Running in production mode"}}function Ih(){return{passed:!0,severity:"info",message:"Stripe.js loaded via @stripe/stripe-js package (CSP recommended, not SRI)",recommendation:"Ensure CSP script-src includes https://js.stripe.com"}}function Rh(){return typeof window>"u"?{passed:!0,severity:"info",message:"Mixed content check skipped (SSR environment)"}:window.location.protocol==="https:"?{passed:!0,severity:"info",message:"Mixed content protection active (HTTPS page)"}:{passed:!0,severity:"info",message:"Mixed content check skipped (HTTP page)"}}function Oh(){const e=[Ah(),Eh(),Th(),Ih(),Rh()],t=e.some(a=>a.severity==="error"&&!a.passed),r=e.some(a=>a.severity==="warning"&&!a.passed);let s,o;return t?(s="vulnerable",o="Security issues detected. Review errors and apply recommendations."):r?(s="warnings",o="Minor security warnings detected. Consider applying recommendations."):(s="secure",o="All security checks passed."),{checks:e,overallStatus:s,summary:o}}function Mh(e){process.env.NODE_ENV!=="production"&&(console.group("🔒 Cedros Pay Security Report"),console.log(`Status: ${e.overallStatus.toUpperCase()}`),console.log(`Summary: ${e.summary}`),console.log(""),e.checks.forEach(t=>{const r=t.passed?"✅":t.severity==="error"?"❌":"⚠️";console.log(`${r} ${t.message}`),t.recommendation&&console.log(` → ${t.recommendation}`)}),console.groupEnd())}const Dh={CSP:"Use generateCSP() from @cedros/pay-react to generate Content Security Policy headers",HTTPS:"Always serve payment pages over HTTPS in production",PACKAGE_UPDATES:"Keep @stripe/stripe-js and @cedros/pay-react updated for security patches",AUDIT:"Run npm audit regularly to check for known vulnerabilities",MONITORING:"Monitor Stripe security advisories and apply updates promptly",NO_SRI:"Do NOT use SRI hashes for Stripe.js - use CSP instead"},Ra=y.createContext(null);function Re(){const e=y.useContext(Ra);if(!e)throw new Error("useCedrosShop must be used within CedrosShopProvider");return e}function Oa(){return y.useContext(Ra)}function Lh({config:e,children:t}){return n.jsx(Ra.Provider,{value:{config:e},children:t})}function At(e){return new Promise(t=>setTimeout(t,e))}const ed=[{id:"cat_all",slug:"all",name:"All Products",description:"Everything in the catalog."},{id:"cat_apparel",slug:"apparel",name:"Apparel",description:"Soft goods and daily wear."},{id:"cat_accessories",slug:"accessories",name:"Accessories",description:"Carry, attach, decorate."}],hs=[{id:"p_tee",slug:"cedros-tee",title:"Cedros Tee",description:"A heavyweight tee with a clean silhouette.",images:[{url:"https://picsum.photos/seed/cedros-tee/900/900",alt:"Cedros Tee"},{url:"https://picsum.photos/seed/cedros-tee-2/900/900",alt:"Cedros Tee detail"}],price:38,currency:"USD",tags:["new","cotton"],categoryIds:["cat_apparel"],compareAtPrice:48,inventoryStatus:"in_stock",variants:[{id:"v_tee_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_tee_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_tee_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_crewneck",slug:"cedros-crewneck",title:"Cedros Crewneck",description:"Midweight fleece with a relaxed fit and embroidered mark.",images:[{url:"https://picsum.photos/seed/cedros-crewneck/900/900",alt:"Cedros Crewneck"}],price:64,currency:"USD",tags:["fleece","core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",compareAtPrice:78,variants:[{id:"v_crew_s",title:"Small / Heather",options:{Size:"S",Color:"Heather"}},{id:"v_crew_m",title:"Medium / Heather",options:{Size:"M",Color:"Heather"}},{id:"v_crew_l",title:"Large / Heather",options:{Size:"L",Color:"Heather"}}],shippingProfile:"physical"},{id:"p_hoodie",slug:"cedros-hoodie",title:"Cedros Hoodie",description:"Pullover hoodie with soft interior and structured hood.",images:[{url:"https://picsum.photos/seed/cedros-hoodie/900/900",alt:"Cedros Hoodie"},{url:"https://picsum.photos/seed/cedros-hoodie-2/900/900",alt:"Cedros Hoodie detail"}],price:74,currency:"USD",tags:["fleece","new"],categoryIds:["cat_apparel"],inventoryStatus:"low",variants:[{id:"v_hoodie_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_hoodie_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_hoodie_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_cap",slug:"cedros-cap",title:"Cedros Cap",description:"Unstructured cap with adjustable strap and curved brim.",images:[{url:"https://picsum.photos/seed/cedros-cap/900/900",alt:"Cedros Cap"}],price:28,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_socks",slug:"cedros-socks",title:"Cedros Socks",description:"Rib-knit socks designed for everyday comfort.",images:[{url:"https://picsum.photos/seed/cedros-socks/900/900",alt:"Cedros Socks"}],price:14,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_tote",slug:"cedros-tote",title:"Cedros Tote",description:"Heavy canvas tote with reinforced handles.",images:[{url:"https://picsum.photos/seed/cedros-tote/900/900",alt:"Cedros Tote"}],price:32,currency:"USD",tags:["gift","canvas"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_stickers",slug:"cedros-sticker-pack",title:"Sticker Pack",description:"Five durable vinyl stickers for laptops and water bottles.",images:[{url:"https://picsum.photos/seed/cedros-stickers/900/900",alt:"Sticker Pack"}],price:8,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_keychain",slug:"cedros-keychain",title:"Enamel Keychain",description:"Polished enamel keychain with a subtle mark.",images:[{url:"https://picsum.photos/seed/cedros-keychain/900/900",alt:"Enamel Keychain"}],price:12,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_lanyard",slug:"cedros-lanyard",title:"Woven Lanyard",description:"Soft woven lanyard with swivel clasp.",images:[{url:"https://picsum.photos/seed/cedros-lanyard/900/900",alt:"Woven Lanyard"}],price:10,currency:"USD",tags:["core"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_notebook",slug:"cedros-notebook",title:"Dot Grid Notebook",description:"Lay-flat notebook for sketches, notes, and plans.",images:[{url:"https://picsum.photos/seed/cedros-notebook/900/900",alt:"Dot Grid Notebook"}],price:18,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_waterbottle",slug:"cedros-water-bottle",title:"Insulated Bottle",description:"Vacuum-insulated bottle that keeps drinks cold for hours.",images:[{url:"https://picsum.photos/seed/cedros-bottle/900/900",alt:"Insulated Bottle"}],price:36,currency:"USD",tags:["gift","new"],categoryIds:["cat_accessories"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_posters",slug:"cedros-poster-set",title:"Poster Set",description:"Two prints on thick matte stock.",images:[{url:"https://picsum.photos/seed/cedros-posters/900/900",alt:"Poster Set"}],price:24,currency:"USD",tags:["gift","limited"],categoryIds:["cat_accessories"],inventoryStatus:"out_of_stock",shippingProfile:"physical"},{id:"p_pins",slug:"cedros-pin-set",title:"Pin Set",description:"Two enamel pins with rubber backings.",images:[{url:"https://picsum.photos/seed/cedros-pins/900/900",alt:"Pin Set"}],price:16,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_brandbook",slug:"cedros-brand-book",title:"Brand Book (PDF)",description:"A compact brand book: typography, color, layout, and voice.",images:[{url:"https://picsum.photos/seed/cedros-brandbook/900/900",alt:"Brand Book cover"}],price:19,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital",checkoutRequirements:{email:"optional",name:"none",phone:"none",shippingAddress:!1,billingAddress:!1},fulfillment:{type:"digital_download",notes:"This is a digital product and will be downloadable from your account after purchase."}},{id:"p_wallpaper",slug:"cedros-wallpaper-pack",title:"Wallpaper Pack",description:"A set of desktop + mobile wallpapers in multiple colorways.",images:[{url:"https://picsum.photos/seed/cedros-wallpaper/900/900",alt:"Wallpaper Pack"}],price:6,currency:"USD",tags:["digital","new"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"},{id:"p_longsleeve",slug:"cedros-long-sleeve",title:"Long Sleeve Tee",description:"Soft long sleeve tee with rib cuff and relaxed drape.",images:[{url:"https://picsum.photos/seed/cedros-longsleeve/900/900",alt:"Long Sleeve Tee"}],price:44,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_shorts",slug:"cedros-shorts",title:"Everyday Shorts",description:"Lightweight shorts with a comfortable waistband.",images:[{url:"https://picsum.photos/seed/cedros-shorts/900/900",alt:"Everyday Shorts"}],price:40,currency:"USD",tags:["new"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_beanie",slug:"cedros-beanie",title:"Rib Beanie",description:"Warm rib beanie with a clean folded cuff.",images:[{url:"https://picsum.photos/seed/cedros-beanie/900/900",alt:"Rib Beanie"}],price:20,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_jacket",slug:"cedros-coach-jacket",title:"Coach Jacket",description:"Lightweight jacket with snap front and subtle sheen.",images:[{url:"https://picsum.photos/seed/cedros-jacket/900/900",alt:"Coach Jacket"}],price:96,currency:"USD",tags:["limited"],categoryIds:["cat_apparel"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_mug",slug:"cedros-mug",title:"Cedros Mug",description:"Stoneware mug with a satin glaze.",images:[{url:"https://picsum.photos/seed/cedros-mug/900/900",alt:"Cedros Mug"}],price:22,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_guide",slug:"cedros-field-guide",title:"Field Guide (Digital)",description:"A short digital guide to shipping delightful checkout flows.",images:[{url:"https://picsum.photos/seed/cedros-guide/900/900",alt:"Field Guide cover"}],price:12,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"}];let So=[];const Vr={};function $h(e,t){let r=e;if(t.category&&t.category!=="all"){const l=ed.find(d=>d.slug===t.category||d.id===t.category);l&&(r=r.filter(d=>d.categoryIds.includes(l.id)))}if(t.search){const l=t.search.toLowerCase();r=r.filter(d=>d.title.toLowerCase().includes(l)||d.description.toLowerCase().includes(l))}const s=t.filters??{},o=s.tags;if(Array.isArray(o)&&o.length>0){const l=new Set(o.map(String));r=r.filter(d=>d.tags?.some(m=>l.has(m)))}const a=typeof s.priceMin=="number"?s.priceMin:void 0,i=typeof s.priceMax=="number"?s.priceMax:void 0;return typeof a=="number"&&(r=r.filter(l=>l.price>=a)),typeof i=="number"&&(r=r.filter(l=>l.price<=i)),(typeof s.inStock=="boolean"?s.inStock:void 0)===!0&&(r=r.filter(l=>l.inventoryStatus!=="out_of_stock")),r}function zh(e,t){if(!t||t==="featured")return e;const r=[...e];return t==="price_asc"&&r.sort((s,o)=>s.price-o.price),t==="price_desc"&&r.sort((s,o)=>o.price-s.price),r}function Fh(e,t,r){const s=(t-1)*r;return{items:e.slice(s,s+r),page:t,pageSize:r,total:e.length,hasNextPage:s+r<e.length}}function Bh(e){const t=new Date().toISOString(),r=e.cart.map(o=>{const a=hs.find(i=>i.id===o.resource||i.slug===o.resource)??hs[0];return{title:a.title,qty:o.quantity,unitPrice:a.price,currency:e.options.currency,imageUrl:a.images[0]?.url}}),s=r.reduce((o,a)=>o+a.qty*a.unitPrice,0);return{id:`ord_${Math.random().toString(16).slice(2)}`,createdAt:t,status:"paid",total:s,currency:e.options.currency,items:r,receiptUrl:e.options.successUrl}}function Uh(){return{async listProducts(e){await At(150);const t=e.page??1,r=e.pageSize??24,s=$h(hs,e),o=zh(s,e.sort);return Fh(o,t,r)},async getProductBySlug(e){return await At(100),hs.find(t=>t.slug===e)??null},async listCategories(){return await At(80),ed},async getOrderHistory(){return await At(120),So},async getCart({customerId:e}){return await At(80),Vr[e]??{items:[]}},async mergeCart({customerId:e,cart:t}){await At(120);const r=Vr[e]??{items:[]},s=new Map,o=i=>{const c=`${i.productId}::${i.variantId??""}`,l=s.get(c);l?s.set(c,{...l,qty:l.qty+i.qty}):s.set(c,i)};for(const i of r.items)o(i);for(const i of t.items)o(i);const a={items:Array.from(s.values()),promoCode:t.promoCode??r.promoCode};return Vr[e]=a,a},async updateCart({customerId:e,cart:t}){await At(60),Vr[e]=t},async createCheckoutSession(e){await At(250);const t=Bh(e);if(So=[t,...So].slice(0,25),e.options.successUrl){const r=new URL(e.options.successUrl,"http://localhost");return r.searchParams.set("demoOrderId",t.id),{kind:"redirect",url:r.toString().replace("http://localhost","")}}return{kind:"custom",data:{orderId:t.id}}},async listSubscriptionTiers(){return await At(80),[{id:"tier_starter",title:"Starter",description:"For small shops getting started.",priceMonthly:19,priceAnnual:190,currency:"USD",features:["Basic analytics","Email support","1 storefront"]},{id:"tier_growth",title:"Growth",description:"For teams iterating fast.",priceMonthly:49,priceAnnual:490,currency:"USD",features:["Advanced analytics","Priority support","3 storefronts"],isPopular:!0},{id:"tier_enterprise",title:"Enterprise",description:"For high volume and custom needs.",priceMonthly:199,priceAnnual:1990,currency:"USD",features:["SLA","Dedicated success","Unlimited storefronts"]}]},async getSubscriptionStatus(){return await At(80),{isActive:!1}},async createSubscriptionCheckoutSession(e){return await At(200),e.successUrl?{kind:"redirect",url:e.successUrl}:{kind:"custom",data:e}}}}function td(e){return e.replace(/[_-]+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function Wh(e){return e?e.toUpperCase():"USD"}function Vh(e){if(e&&(e==="in_stock"||e==="low"||e==="out_of_stock"||e==="backorder"))return e}function qh(e){if(e&&(e==="physical"||e==="digital"))return e}function Hh(e){const t=[];if(Array.isArray(e))for(const r of e)typeof r=="string"&&t.push(r);else if(typeof e=="string"){const r=e.trim();if(r.startsWith("["))try{const s=JSON.parse(r);if(Array.isArray(s))for(const o of s)typeof o=="string"&&t.push(o);else t.push(e)}catch{t.push(e)}else t.push(e)}return t.flatMap(r=>r.split(",")).map(r=>r.trim().toUpperCase()).filter(Boolean)}function qr(e){const t=Wh(e.fiatCurrency),r=e.images&&e.images.length?e.images:e.imageUrl?[{url:e.imageUrl,alt:e.title}]:[],s=e.effectiveFiatAmountCents??e.fiatAmountCents??0,o=e.compareAtAmountCents,a=e.metadata?.shippingCountries??e.metadata?.shipping_countries,i=Hh(a);return{id:e.id,slug:e.slug??e.id,title:e.title??td(e.id),description:e.description??"",images:r,price:s/100,currency:t,tags:e.tags??[],categoryIds:e.categoryIds??[],inventoryStatus:Vh(e.inventoryStatus),inventoryQuantity:typeof e.inventoryQuantity=="number"?e.inventoryQuantity:void 0,compareAtPrice:typeof o=="number"?o/100:void 0,shippingProfile:qh(e.shippingProfile),checkoutRequirements:e.checkoutRequirements,fulfillment:e.fulfillment,attributes:i.length?{shippingCountries:i.join(",")}:void 0}}function Co(e){if(Array.isArray(e))return{products:e};const t=e.products??e.items??[],r=e.total??e.count;return{products:t,total:r}}async function tn(e,t,r){const s={};r&&(s["X-API-Key"]=r);const o=await fetch(`${e}${t}`,{headers:s});if(!o.ok){const a=await o.text().catch(()=>""),i=new Error(`Request failed (${o.status}): ${a}`);throw i.status=o.status,i}return o.json()}function Zh(e){return{listProducts:async l=>{const d=l.page??1,m=l.pageSize??24,u=m,p=(d-1)*m,h=new URLSearchParams;h.set("limit",String(u)),h.set("offset",String(p)),l.search&&h.set("search",l.search),l.category&&h.set("category",l.category),l.sort&&h.set("sort",l.sort),l.filters?.inStock&&h.set("in_stock","true"),l.filters?.minPrice!=null&&h.set("min_price",String(l.filters.minPrice)),l.filters?.maxPrice!=null&&h.set("max_price",String(l.filters.maxPrice));const _=l.filters?.tags,g=Array.isArray(_)?_:typeof _=="string"?[_]:[];g.length&&h.set("tags",g.join(","));const f=await tn(e.serverUrl,`/paywall/v1/products?${h.toString()}`,e.apiKey),{products:w,total:j}=Co(f);return{items:w.map(qr),page:d,pageSize:m,total:j,hasNextPage:typeof j=="number"?p+u<j:w.length===u}},getProductBySlug:async l=>{try{const d=await tn(e.serverUrl,`/paywall/v1/products/by-slug/${encodeURIComponent(l)}`,e.apiKey);return qr(d)}catch(d){const m=d?.status;if(m!==404&&m!==405)throw d;try{const u=await tn(e.serverUrl,`/paywall/v1/products/${encodeURIComponent(l)}`,e.apiKey);return qr(u)}catch(u){const p=u?.status;if(p!==404&&p!==405)throw u;const h=await tn(e.serverUrl,"/paywall/v1/products?limit=200&offset=0",e.apiKey),{products:_}=Co(h),g=_.find(f=>f.slug===l||f.id===l);return g?qr(g):null}}},listCategories:async()=>{const l=await tn(e.serverUrl,"/paywall/v1/products?limit=500&offset=0",e.apiKey),{products:d}=Co(l),m=new Set;for(const u of d)for(const p of u.categoryIds??[])m.add(p);return Array.from(m).map(u=>({id:u,slug:u,name:td(u)}))},getOrderHistory:async()=>[],createCheckoutSession:async l=>{throw new Error("createCheckoutSession is not implemented for paywall adapter")},getStorefrontSettings:async()=>{try{return(await tn(e.serverUrl,"/admin/config/storefront",e.apiKey)).config??null}catch{return null}},getPaymentMethodsConfig:async()=>{try{const[l,d,m]=await Promise.allSettled([tn(e.serverUrl,"/admin/config/stripe",e.apiKey),tn(e.serverUrl,"/admin/config/x402",e.apiKey),tn(e.serverUrl,"/admin/config/cedros_login",e.apiKey)]),u=l.status==="fulfilled"?!!l.value?.config?.enabled:!1,p=d.status==="fulfilled"?!!d.value?.config?.enabled:!1,h=m.status==="fulfilled"?!!m.value?.config?.enabled:!1;return{card:u,crypto:p,credits:h}}catch{return null}},getAIRelatedProducts:async l=>{const d={"Content-Type":"application/json"};e.apiKey&&(d["X-API-Key"]=e.apiKey);const m=await fetch(`${e.serverUrl}/admin/ai/related-products`,{method:"POST",headers:d,body:JSON.stringify(l)});if(!m.ok){const u=await m.text().catch(()=>"");throw new Error(`AI related products request failed (${m.status}): ${u}`)}return m.json()}}}function Gh(e){throw new Error(`Unhandled cart action: ${JSON.stringify(e)}`)}function Sn(e){return`${e.productId}::${e.variantId??""}`}const Qh={items:[]};function Yh(e,t){switch(t.type){case"cart/hydrate":return t.state;case"cart/add":{const r=Math.max(1,Math.floor(t.qty??1)),s=Sn(t.item);return e.items.find(a=>Sn(a)===s)?{...e,items:e.items.map(a=>Sn(a)===s?{...a,qty:a.qty+r}:a)}:{...e,items:[...e.items,{...t.item,qty:r}]}}case"cart/remove":{const r=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.filter(s=>Sn(s)!==r)}}case"cart/setQty":{const r=Math.max(0,Math.floor(t.qty)),s=`${t.productId}::${t.variantId??""}`;return r===0?{...e,items:e.items.filter(o=>Sn(o)!==s)}:{...e,items:e.items.map(o=>Sn(o)===s?{...o,qty:r}:o)}}case"cart/clear":return{items:[],promoCode:void 0};case"cart/setPromoCode":return{...e,promoCode:t.promoCode||void 0};case"cart/updateHold":{const r=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.map(s=>Sn(s)===r?{...s,holdId:t.holdId,holdExpiresAt:t.holdExpiresAt}:s)}}default:return Gh(t)}}function Kh(e){return e.reduce((t,r)=>t+r.qty,0)}function Xh(e){return e.reduce((t,r)=>t+r.qty*r.unitPrice,0)}function nc(){try{return typeof window>"u"?null:window.localStorage}catch{return null}}function Jh(e,t){try{const r=e.getItem(t);return r?JSON.parse(r):null}catch{return null}}function eg(e,t,r){try{e.setItem(t,JSON.stringify(r))}catch{}}const nd=y.createContext(null);function Dt(){const e=y.useContext(nd);if(!e)throw new Error("useCart must be used within CartProvider");return e}function tg({children:e}){const{config:t}=Re(),r=t.cart?.storageKey??"cedros_shop_cart_v1",s=t.customer?.id,o=t.customer?.isSignedIn??!!s,a=t.cart?.syncDebounceMs??800,i=!!t.adapter.getCartInventoryStatus,[c,l]=y.useReducer(Yh,Qh),[d,m]=y.useState(!1),u=y.useRef(!1),p=y.useRef(null);y.useEffect(()=>{const f=nc();if(!f)return;const w=Jh(f,r);w&&Array.isArray(w.items)&&l({type:"cart/hydrate",state:w}),m(!0)},[r]),y.useEffect(()=>{const f=nc();f&&eg(f,r,c)},[c,r]),y.useEffect(()=>{d&&(!o||!s||!t.adapter.mergeCart&&!t.adapter.getCart||u.current||(u.current=!0,(async()=>{try{const f=t.adapter.mergeCart?await t.adapter.mergeCart({customerId:s,cart:c}):await t.adapter.getCart({customerId:s});f&&Array.isArray(f.items)&&(l({type:"cart/hydrate",state:f}),p.current=JSON.stringify(f))}catch{}})()))},[t.adapter,s,d,o,c]),y.useEffect(()=>{if(!d||!o||!s||!t.adapter.updateCart||!u.current||typeof window>"u")return;const f=JSON.stringify(c);if(p.current===f)return;const w=window.setTimeout(()=>{t.adapter.updateCart({customerId:s,cart:c}).then(()=>{p.current=f}).catch(()=>{})},a);return()=>window.clearTimeout(w)},[t.adapter,s,d,o,c,a]);const h=y.useCallback((f,w)=>{const j=c.items.find(b=>b.productId===f&&b.variantId===w);if(j)return{holdId:j.holdId,expiresAt:j.holdExpiresAt}},[c.items]),_=y.useCallback((f,w,j)=>{l({type:"cart/updateHold",productId:f,variantId:w,holdExpiresAt:j})},[]),g=y.useMemo(()=>{const f=Kh(c.items),w=Xh(c.items);return{items:c.items,promoCode:c.promoCode,count:f,subtotal:w,addItem:(j,b)=>l({type:"cart/add",item:j,qty:b}),removeItem:(j,b)=>l({type:"cart/remove",productId:j,variantId:b}),setQty:(j,b,v)=>l({type:"cart/setQty",productId:j,variantId:b,qty:v}),clear:()=>l({type:"cart/clear"}),setPromoCode:j=>l({type:"cart/setPromoCode",promoCode:j}),holdsSupported:i,getItemHold:h,updateItemHold:_}},[c.items,c.promoCode,i,h,_]);return n.jsx(nd.Provider,{value:g,children:e})}function G(e,t,r){function s(c,l){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:l,constr:i,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,l);const d=i.prototype,m=Object.keys(d);for(let u=0;u<m.length;u++){const p=m[u];p in c||(c[p]=d[p].bind(c))}}const o=r?.Parent??Object;class a extends o{}Object.defineProperty(a,"name",{value:e});function i(c){var l;const d=r?.Parent?new a:this;s(d,c),(l=d._zod).deferred??(l.deferred=[]);for(const m of d._zod.deferred)m();return d}return Object.defineProperty(i,"init",{value:s}),Object.defineProperty(i,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class Kn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class rd extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const sd={};function An(e){return sd}function od(e){const t=Object.values(e).filter(s=>typeof s=="number");return Object.entries(e).filter(([s,o])=>t.indexOf(+s)===-1).map(([s,o])=>o)}function ea(e,t){return typeof t=="bigint"?t.toString():t}function Ma(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Da(e){return e==null}function La(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function ng(e,t){const r=(e.toString().split(".")[1]||"").length,s=t.toString();let o=(s.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(s)){const l=s.match(/\d?e-(\d?)/);l?.[1]&&(o=Number.parseInt(l[1]))}const a=r>o?r:o,i=Number.parseInt(e.toFixed(a).replace(".","")),c=Number.parseInt(t.toFixed(a).replace(".",""));return i%c/10**a}const rc=Symbol("evaluating");function Ce(e,t,r){let s;Object.defineProperty(e,t,{get(){if(s!==rc)return s===void 0&&(s=rc,s=r()),s},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function zn(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function yn(...e){const t={};for(const r of e){const s=Object.getOwnPropertyDescriptors(r);Object.assign(t,s)}return Object.defineProperties({},t)}function sc(e){return JSON.stringify(e)}function rg(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ad="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function gs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const sg=Ma(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Pr(e){if(gs(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const r=t.prototype;return!(gs(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function id(e){return Pr(e)?{...e}:Array.isArray(e)?[...e]:e}const og=new Set(["string","number","symbol"]);function Os(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function vn(e,t,r){const s=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(s._zod.parent=e),s}function me(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function ag(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const ig={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function cg(e,t){const r=e._zod.def,s=r.checks;if(s&&s.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const a=yn(e._zod.def,{get shape(){const i={};for(const c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(i[c]=r.shape[c])}return zn(this,"shape",i),i},checks:[]});return vn(e,a)}function lg(e,t){const r=e._zod.def,s=r.checks;if(s&&s.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const a=yn(e._zod.def,{get shape(){const i={...e._zod.def.shape};for(const c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete i[c]}return zn(this,"shape",i),i},checks:[]});return vn(e,a)}function dg(e,t){if(!Pr(t))throw new Error("Invalid input to extend: expected a plain object");const r=e._zod.def.checks;if(r&&r.length>0){const a=e._zod.def.shape;for(const i in t)if(Object.getOwnPropertyDescriptor(a,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=yn(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return zn(this,"shape",a),a}});return vn(e,o)}function ug(e,t){if(!Pr(t))throw new Error("Invalid input to safeExtend: expected a plain object");const r=yn(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return zn(this,"shape",s),s}});return vn(e,r)}function mg(e,t){const r=yn(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t._zod.def.shape};return zn(this,"shape",s),s},get catchall(){return t._zod.def.catchall},checks:[]});return vn(e,r)}function pg(e,t,r){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const i=yn(t._zod.def,{get shape(){const c=t._zod.def.shape,l={...c};if(r)for(const d in r){if(!(d in c))throw new Error(`Unrecognized key: "${d}"`);r[d]&&(l[d]=e?new e({type:"optional",innerType:c[d]}):c[d])}else for(const d in c)l[d]=e?new e({type:"optional",innerType:c[d]}):c[d];return zn(this,"shape",l),l},checks:[]});return vn(t,i)}function fg(e,t,r){const s=yn(t._zod.def,{get shape(){const o=t._zod.def.shape,a={...o};if(r)for(const i in r){if(!(i in a))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(a[i]=new e({type:"nonoptional",innerType:o[i]}))}else for(const i in o)a[i]=new e({type:"nonoptional",innerType:o[i]});return zn(this,"shape",a),a}});return vn(t,s)}function Yn(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function cd(e,t){return t.map(r=>{var s;return(s=r).path??(s.path=[]),r.path.unshift(e),r})}function Hr(e){return typeof e=="string"?e:e?.message}function En(e,t,r){const s={...e,path:e.path??[]};if(!e.message){const o=Hr(e.inst?._zod.def?.error?.(e))??Hr(t?.error?.(e))??Hr(r.customError?.(e))??Hr(r.localeError?.(e))??"Invalid input";s.message=o}return delete s.inst,delete s.continue,t?.reportInput||delete s.input,s}function $a(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ar(...e){const[t,r,s]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:s}:{...t}}const ld=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ea,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},dd=G("$ZodError",ld),ud=G("$ZodError",ld,{Parent:Error});function hg(e,t=r=>r.message){const r={},s=[];for(const o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):s.push(t(o));return{formErrors:s,fieldErrors:r}}function gg(e,t=r=>r.message){const r={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>s({issues:i}));else if(a.code==="invalid_key")s({issues:a.issues});else if(a.code==="invalid_element")s({issues:a.issues});else if(a.path.length===0)r._errors.push(t(a));else{let i=r,c=0;for(;c<a.path.length;){const l=a.path[c];c===a.path.length-1?(i[l]=i[l]||{_errors:[]},i[l]._errors.push(t(a))):i[l]=i[l]||{_errors:[]},i=i[l],c++}}};return s(e),r}const za=e=>(t,r,s,o)=>{const a=s?Object.assign(s,{async:!1}):{async:!1},i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise)throw new Kn;if(i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>En(l,a,An())));throw ad(c,o?.callee),c}return i.value},Fa=e=>async(t,r,s,o)=>{const a=s?Object.assign(s,{async:!0}):{async:!0};let i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>En(l,a,An())));throw ad(c,o?.callee),c}return i.value},Ms=e=>(t,r,s)=>{const o=s?{...s,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},o);if(a instanceof Promise)throw new Kn;return a.issues.length?{success:!1,error:new(e??dd)(a.issues.map(i=>En(i,o,An())))}:{success:!0,data:a.value}},xg=Ms(ud),Ds=e=>async(t,r,s)=>{const o=s?Object.assign(s,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},o);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(i=>En(i,o,An())))}:{success:!0,data:a.value}},yg=Ds(ud),vg=e=>(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return za(e)(t,r,o)},bg=e=>(t,r,s)=>za(e)(t,r,s),wg=e=>async(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Fa(e)(t,r,o)},_g=e=>async(t,r,s)=>Fa(e)(t,r,s),jg=e=>(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Ms(e)(t,r,o)},kg=e=>(t,r,s)=>Ms(e)(t,r,s),Sg=e=>async(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Ds(e)(t,r,o)},Cg=e=>async(t,r,s)=>Ds(e)(t,r,s),Ng=/^[cC][^\s-]{8,}$/,Pg=/^[0-9a-z]+$/,Ag=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Eg=/^[0-9a-vA-V]{20}$/,Tg=/^[A-Za-z0-9]{27}$/,Ig=/^[a-zA-Z0-9_-]{21}$/,Rg=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Og=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,oc=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Mg=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Dg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Lg(){return new RegExp(Dg,"u")}const $g=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,zg=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Fg=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Bg=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ug=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,md=/^[A-Za-z0-9_-]*$/,Wg=/^\+[1-9]\d{6,14}$/,pd="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Vg=new RegExp(`^${pd}$`);function fd(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function qg(e){return new RegExp(`^${fd(e)}$`)}function Hg(e){const t=fd({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const s=`${t}(?:${r.join("|")})`;return new RegExp(`^${pd}T(?:${s})$`)}const Zg=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Gg=/^-?\d+$/,Qg=/^-?\d+(?:\.\d+)?$/,Yg=/^[^A-Z]*$/,Kg=/^[^a-z]*$/,ht=G("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),hd={number:"number",bigint:"bigint",object:"date"},gd=G("$ZodCheckLessThan",(e,t)=>{ht.init(e,t);const r=hd[typeof t.value];e._zod.onattach.push(s=>{const o=s._zod.bag,a=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<a&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value<=t.value:s.value<t.value)||s.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),xd=G("$ZodCheckGreaterThan",(e,t)=>{ht.init(e,t);const r=hd[typeof t.value];e._zod.onattach.push(s=>{const o=s._zod.bag,a=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>a&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value>=t.value:s.value>t.value)||s.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Xg=G("$ZodCheckMultipleOf",(e,t)=>{ht.init(e,t),e._zod.onattach.push(r=>{var s;(s=r._zod.bag).multipleOf??(s.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):ng(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Jg=G("$ZodCheckNumberFormat",(e,t)=>{ht.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),s=r?"int":"number",[o,a]=ig[t.format];e._zod.onattach.push(i=>{const c=i._zod.bag;c.format=t.format,c.minimum=o,c.maximum=a,r&&(c.pattern=Gg)}),e._zod.check=i=>{const c=i.value;if(r){if(!Number.isInteger(c)){i.issues.push({expected:s,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?i.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort}):i.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort});return}}c<o&&i.issues.push({origin:"number",input:c,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),c>a&&i.issues.push({origin:"number",input:c,code:"too_big",maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),ex=G("$ZodCheckMaxLength",(e,t)=>{var r;ht.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!Da(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(s._zod.bag.maximum=t.maximum)}),e._zod.check=s=>{const o=s.value;if(o.length<=t.maximum)return;const i=$a(o);s.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),tx=G("$ZodCheckMinLength",(e,t)=>{var r;ht.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!Da(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(s._zod.bag.minimum=t.minimum)}),e._zod.check=s=>{const o=s.value;if(o.length>=t.minimum)return;const i=$a(o);s.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),nx=G("$ZodCheckLengthEquals",(e,t)=>{var r;ht.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!Da(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=s=>{const o=s.value,a=o.length;if(a===t.length)return;const i=$a(o),c=a>t.length;s.issues.push({origin:i,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:s.value,inst:e,continue:!t.abort})}}),Ls=G("$ZodCheckStringFormat",(e,t)=>{var r,s;ht.init(e,t),e._zod.onattach.push(o=>{const a=o._zod.bag;a.format=t.format,t.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(s=e._zod).check??(s.check=()=>{})}),rx=G("$ZodCheckRegex",(e,t)=>{Ls.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),sx=G("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Yg),Ls.init(e,t)}),ox=G("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Kg),Ls.init(e,t)}),ax=G("$ZodCheckIncludes",(e,t)=>{ht.init(e,t);const r=Os(t.includes),s=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=s,e._zod.onattach.push(o=>{const a=o._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(s)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),ix=G("$ZodCheckStartsWith",(e,t)=>{ht.init(e,t);const r=new RegExp(`^${Os(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(s=>{const o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=s=>{s.value.startsWith(t.prefix)||s.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:s.value,inst:e,continue:!t.abort})}}),cx=G("$ZodCheckEndsWith",(e,t)=>{ht.init(e,t);const r=new RegExp(`.*${Os(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(s=>{const o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=s=>{s.value.endsWith(t.suffix)||s.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:s.value,inst:e,continue:!t.abort})}}),lx=G("$ZodCheckOverwrite",(e,t)=>{ht.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class dx{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const s=t.split(`
|
|
53
|
+
- Include relevant keywords naturally for SEO`}],sh=[{id:"gemini",label:"Google Gemini API",placeholder:"AIza..."},{id:"openai",label:"OpenAI API",placeholder:"sk-..."}],Ji={apiKeys:[{provider:"gemini",isConfigured:!1},{provider:"openai",isConfigured:!1}],taskAssignments:Jo.map(e=>({task:e.task,label:e.label,description:e.description,assignedModel:"not_set",systemPrompt:e.defaultPrompt}))};function ql({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("api-keys"),[a,i]=y.useState(Ji),[c,l]=y.useState(!0),[d,m]=y.useState(!1),[u,p]=y.useState(null),[h,_]=y.useState(!1),[g,f]=y.useState(null),w=y.useRef(null),[j,b]=y.useState({gemini:"",openai:""}),[v,k]=y.useState({gemini:!1,openai:!1}),R=y.useCallback(async()=>{try{let A;if(r?.isAuthenticated())A=await r.fetchWithAuth("/admin/config/ai");else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const B=await fetch(`${e}/admin/config/ai`,{headers:I});if(!B.ok)throw new Error(`Failed to fetch: ${B.status}`);A=await B.json()}A.settings&&i(A.settings)}catch{i(Ji),f("Could not load saved AI settings. Showing defaults.")}finally{l(!1)}},[e,t,r]);y.useEffect(()=>{R()},[R]);const N=y.useCallback(async A=>{const I=j[A];if(I.trim()){m(!0),p(null);try{const B={provider:A,apiKey:I};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/api-key",{method:"PUT",body:JSON.stringify(B)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const E=await fetch(`${e}/admin/config/ai/api-key`,{method:"PUT",headers:D,body:JSON.stringify(B)});if(!E.ok)throw new Error(`Failed to save: ${E.status}`)}i(D=>({...D,apiKeys:D.apiKeys.map(E=>E.provider===A?{...E,isConfigured:!0,maskedKey:`${I.slice(0,4)}...${I.slice(-4)}`,updatedAt:new Date().toISOString()}:E)})),b(D=>({...D,[A]:""})),_(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>_(!1),3e3)}catch(B){p(B instanceof Error?B.message:"Failed to save API key")}finally{m(!1)}}},[j,e,t,r]),C=y.useCallback(async A=>{if(confirm(`Are you sure you want to delete the ${A==="gemini"?"Google Gemini":"OpenAI"} API key?`)){m(!0),p(null);try{if(r?.isAuthenticated())await r.fetchWithAuth(`/admin/config/ai/api-key/${A}`,{method:"DELETE"});else{const I={"Content-Type":"application/json"};t&&(I["X-API-Key"]=t);const B=await fetch(`${e}/admin/config/ai/api-key/${A}`,{method:"DELETE",headers:I});if(!B.ok)throw new Error(`Failed to delete: ${B.status}`)}i(I=>({...I,apiKeys:I.apiKeys.map(B=>B.provider===A?{provider:A,isConfigured:!1}:B)}))}catch(I){p(I instanceof Error?I.message:"Failed to delete API key")}finally{m(!1)}}},[e,t,r]),T=y.useCallback(async(A,I)=>{m(!0),p(null);try{const B={task:A,model:I};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/assignment",{method:"PUT",body:JSON.stringify(B)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const E=await fetch(`${e}/admin/config/ai/assignment`,{method:"PUT",headers:D,body:JSON.stringify(B)});if(!E.ok)throw new Error(`Failed to save: ${E.status}`)}i(D=>({...D,taskAssignments:D.taskAssignments.map(E=>E.task===A?{...E,assignedModel:I}:E)})),_(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>_(!1),3e3)}catch(B){p(B instanceof Error?B.message:"Failed to save assignment")}finally{m(!1)}},[e,t,r]),O=y.useCallback(A=>{if(A==="not_set")return!0;const I=jo.find(D=>D.id===A);return I?.provider?a.apiKeys.find(D=>D.provider===I.provider)?.isConfigured??!1:!0},[a.apiKeys]),$=y.useMemo(()=>jo.map(A=>{const I=O(A.id);return{value:A.id,label:I?A.label:`${A.label} (API key required)`,disabled:!I}}),[O]),S=y.useCallback(async(A,I)=>{m(!0),p(null);try{const B={task:A,systemPrompt:I};if(r?.isAuthenticated())await r.fetchWithAuth("/admin/config/ai/prompt",{method:"PUT",body:JSON.stringify(B)});else{const D={"Content-Type":"application/json"};t&&(D["X-API-Key"]=t);const E=await fetch(`${e}/admin/config/ai/prompt`,{method:"PUT",headers:D,body:JSON.stringify(B)});if(!E.ok)throw new Error(`Failed to save: ${E.status}`)}i(D=>({...D,taskAssignments:D.taskAssignments.map(E=>E.task===A?{...E,systemPrompt:I}:E)})),_(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>_(!1),3e3)}catch(B){p(B instanceof Error?B.message:"Failed to save prompt")}finally{m(!1)}},[e,t,r]);return y.useEffect(()=>()=>{w.current&&clearTimeout(w.current)},[]),c?n.jsx("div",{className:"cedros-admin__section",children:n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading," Loading AI settings..."]})}):n.jsxs("div",{className:"cedros-admin__ai-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store AI"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure AI providers, model assignments, and system prompts."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="api-keys"?"cedros-admin__tab--active":""}`,onClick:()=>o("api-keys"),children:"API Keys"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="assignments"?"cedros-admin__tab--active":""}`,onClick:()=>o("assignments"),children:"Model Assignments"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="prompts"?"cedros-admin__tab--active":""}`,onClick:()=>o("prompts"),children:"Prompts"})]}),u&&n.jsx("div",{className:"cedros-admin__error-banner",style:{marginTop:"1rem"},children:u}),n.jsx(Yt,{message:g,onRetry:R}),h&&n.jsxs("div",{className:"cedros-admin__success-banner",style:{marginTop:"1rem"},children:[Q.check," Settings saved successfully"]}),s==="api-keys"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"API Keys"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure API keys for AI providers. Keys are stored securely and never exposed."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:sh.map(A=>{const I=a.apiKeys.find(D=>D.provider===A.id),B=I?.isConfigured??!1;return n.jsxs("div",{className:"cedros-admin__api-key-card",style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:A.label}),B&&I?.maskedKey&&n.jsxs("div",{style:{fontSize:12,opacity:.6,marginTop:2},children:["Current key: ",I.maskedKey,I.updatedAt&&n.jsxs("span",{children:[" (updated ",new Date(I.updatedAt).toLocaleDateString(),")"]})]})]}),n.jsx("span",{className:`cedros-admin__badge ${B?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:B?"Configured":"Not Set"})]}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:n.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[n.jsx("input",{type:v[A.id]?"text":"password",className:"cedros-admin__input",placeholder:B?"Enter new key to replace":A.placeholder,value:j[A.id],onChange:D=>b(E=>({...E,[A.id]:D.target.value})),onBlur:()=>{j[A.id].trim()&&N(A.id)},style:{flex:1}}),n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>k(D=>({...D,[A.id]:!D[A.id]})),title:v[A.id]?"Hide key":"Show key",style:{padding:"0.5rem"},children:v[A.id]?Q.eyeOff:Q.eye}),B&&n.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>C(A.id),disabled:d,title:"Remove API key",style:{padding:"0.5rem"},children:Q.trash})]})})]},A.id)})})]}),s==="assignments"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"Model Assignments"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Assign AI models to specific tasks. Models require their provider's API key to be configured."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:a.taskAssignments.map(A=>{const I=Jo.find(D=>D.task===A.task),B=jo.find(D=>D.id===A.assignedModel);return n.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{marginBottom:"0.75rem"},children:[n.jsx("div",{style:{fontWeight:600},children:I?.label??A.task}),n.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:I?.description})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[n.jsx(ot,{value:A.assignedModel,onChange:D=>T(A.task,D),options:$,label:"",disabled:d,style:{flex:1,maxWidth:280}}),B&&B.provider&&n.jsx("span",{className:`cedros-admin__badge ${O(B.id)?"cedros-admin__badge--success":"cedros-admin__badge--warning"}`,children:O(B.id)?"Ready":"Missing API Key"})]})]},A.task)})})]}),s==="prompts"&&n.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[n.jsx("div",{className:"cedros-admin__section-header",children:n.jsx("h3",{className:"cedros-admin__section-title",children:"System Prompts"})}),n.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure the default system prompts for each AI task. These prompts guide the AI's behavior and responses."}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:a.taskAssignments.map(A=>{const I=Jo.find(B=>B.task===A.task);return n.jsx(oh,{task:A.task,label:I?.label??A.task,description:I?.description??"",initialPrompt:A.systemPrompt??"",onSave:S},A.task)})})]})]})}function oh({task:e,label:t,description:r,initialPrompt:s,onSave:o}){const[a,i]=y.useState(s),[c,l]=y.useState("idle"),d=y.useRef(null),m=y.useRef(null),u=y.useRef(!0);return y.useEffect(()=>{if(u.current){u.current=!1;return}return d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current),l("pending"),d.current=setTimeout(async()=>{l("saving");try{await o(e,a),l("saved"),m.current=setTimeout(()=>l("idle"),2e3)}catch{l("error")}},1500),()=>{d.current&&clearTimeout(d.current)}},[a,e,o]),y.useEffect(()=>()=>{d.current&&clearTimeout(d.current),m.current&&clearTimeout(m.current)},[]),n.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[n.jsxs("div",{style:{marginBottom:"0.75rem",display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontWeight:600},children:t}),n.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:r})]}),n.jsx(ah,{status:c})]}),n.jsx("textarea",{className:"cedros-admin__input",value:a,onChange:p=>i(p.target.value),placeholder:"Enter system prompt...",rows:4,style:{width:"100%",resize:"vertical",fontFamily:"inherit",minHeight:100}})]})}function ah({status:e}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.75rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved"}),e==="saving"&&n.jsxs(n.Fragment,{children:[Q.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[Q.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsx("span",{children:"Failed"})]})}const ih=Object.freeze(Object.defineProperty({__proto__:null,AISettingsSection:ql},Symbol.toStringTag,{value:"Module"}));function qn({href:e,children:t}){return n.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{color:"inherit",textDecoration:"underline"},children:t})}const ec=[{id:"stripe",label:"Stripe",category:"stripe",description:n.jsxs(n.Fragment,{children:["Configure your Stripe integration for card payments. Get your API keys from the"," ",n.jsx(qn,{href:"https://dashboard.stripe.com/apikeys",children:"Stripe Dashboard"}),"."]})},{id:"crypto",label:"Crypto",category:"x402",description:n.jsxs(n.Fragment,{children:["Configure Solana wallet and token settings for crypto payments. Get a fast RPC endpoint from"," ",n.jsx(qn,{href:"https://www.helius.dev",children:"Helius"})," or"," ",n.jsx(qn,{href:"https://www.quicknode.com/chains/sol",children:"QuickNode"}),". Set up a payment address using"," ",n.jsx(qn,{href:"https://phantom.app",children:"Phantom"})," or"," ",n.jsx(qn,{href:"https://solflare.com",children:"Solflare"})," wallet."]})},{id:"credits",label:"Credits",category:"cedros_login",description:n.jsxs(n.Fragment,{children:["Configure Cedros Login integration for credits payments. See the"," ",n.jsx(qn,{href:"https://docs.cedros.dev/credits",children:"Credits API documentation"}),"."]})}];function Hl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("stripe"),a=ec.find(i=>i.id===s);return n.jsxs("div",{className:"cedros-admin__payment-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Payment Options"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure payment methods including Stripe, crypto, and credits."})]}),n.jsx("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:ec.map(i=>n.jsx("button",{type:"button",className:`cedros-admin__tab ${s===i.id?"cedros-admin__tab--active":""}`,onClick:()=>o(i.id),children:i.label},i.id))}),n.jsx("div",{style:{marginTop:"1rem"},children:n.jsx(Ul,{serverUrl:e,apiKey:t,authManager:r,category:a.category,title:`${a.label} Settings`,description:a.description,showEnabledToggle:!0},a.category)})]})}const ch=Object.freeze(Object.defineProperty({__proto__:null,PaymentSettingsSection:Hl},Symbol.toStringTag,{value:"Module"})),ko={email_enabled:!1,smtp_host:"",smtp_port:587,smtp_username:"",smtp_password:"",from_email:"",from_name:"",webhook_enabled:!1,webhook_url:"",webhook_secret:"",webhook_timeout:30};function Zl({serverUrl:e,apiKey:t,authManager:r}){const[s,o]=y.useState("messages"),[a,i]=y.useState(ko),[c,l]=y.useState(!0),[d,m]=y.useState(!0),[u,p]=y.useState(null),[h,_]=y.useState(new Set),g=y.useCallback(async()=>{try{p(null);let v;const k="/admin/config/messaging";if(r?.isAuthenticated())v=await r.fetchWithAuth(k);else{const R={"Content-Type":"application/json"};t&&(R["X-API-Key"]=t);const N=await fetch(`${e}${k}`,{headers:R});if(!N.ok)throw new Error(`Failed to fetch: ${N.status}`);v=await N.json()}i({...ko,...v.config})}catch{i(ko),p("Could not load saved settings. Showing defaults.")}finally{l(!1),setTimeout(()=>m(!1),100)}},[e,t,r]);y.useEffect(()=>{g()},[g]);const f=y.useCallback(async v=>{const k="/admin/config/messaging",R={...v};h.has("smtp_password")||delete R.smtp_password,h.has("webhook_secret")||delete R.webhook_secret;const N=JSON.stringify({config:R});try{if(r?.isAuthenticated())await r.fetchWithAuth(k,{method:"PUT",body:N});else{const C={"Content-Type":"application/json"};t&&(C["X-API-Key"]=t);const T=await fetch(`${e}${k}`,{method:"PUT",headers:C,body:N});if(!T.ok)throw new Error(`Failed to save: ${T.status}`)}}catch{throw p("Failed to save messaging settings"),new Error("Save failed")}},[e,t,r,h]),{status:w,error:j}=Ta({data:a,onSave:f,debounceMs:1500,enabled:!d}),b=(v,k)=>{(v==="smtp_password"||v==="webhook_secret")&&_(R=>new Set(R).add(v)),i(R=>({...R,[v]:k}))};return c?n.jsxs("div",{className:"cedros-admin__messaging-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),n.jsxs("div",{className:"cedros-admin__loading",style:{marginTop:"1rem"},children:[Q.loading," Loading message settings..."]})]}):n.jsxs("div",{className:"cedros-admin__messaging-settings",children:[n.jsxs("div",{className:"cedros-admin__page-header",children:[n.jsx("h2",{className:"cedros-admin__page-title",children:"Store Messages"}),n.jsx("p",{className:"cedros-admin__page-description",children:"Configure email delivery and webhook notifications."})]}),n.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="messages"?"cedros-admin__tab--active":""}`,onClick:()=>o("messages"),children:"Messages"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="email"?"cedros-admin__tab--active":""}`,onClick:()=>o("email"),children:"Email"}),n.jsx("button",{type:"button",className:`cedros-admin__tab ${s==="webhooks"?"cedros-admin__tab--active":""}`,onClick:()=>o("webhooks"),children:"Webhooks"}),n.jsx("div",{style:{flex:1}}),n.jsx(lh,{status:w,error:j})]}),n.jsx(Yt,{message:u,onRetry:g}),n.jsxs("div",{className:"cedros-admin__tab-content",style:{marginTop:"1rem"},children:[s==="messages"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Enable or disable notification types. Configure the delivery settings in the Email or Webhooks tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[n.jsx(tc,{checked:a.email_enabled,onChange:()=>b("email_enabled",!a.email_enabled)}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:500},children:"Email Confirmation"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send order confirmation emails to customers after successful purchase."}),n.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Email configuration"})]})]}),n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"1rem",padding:"1rem",border:"1px solid var(--cedros-admin-border, #e5e5e5)",borderRadius:"0.5rem"},children:[n.jsx(tc,{checked:a.webhook_enabled,onChange:()=>b("webhook_enabled",!a.webhook_enabled)}),n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontWeight:500},children:"Admin Purchase Notification"}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.8125rem",opacity:.6},children:"Send webhook notifications to your server when a purchase is completed."}),n.jsx("p",{style:{margin:"0.5rem 0 0",fontSize:"0.75rem",opacity:.5},children:"Requires Webhook configuration"})]})]})]})]}),s==="email"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Configure your email provider for sending customer notifications."}),!a.email_enabled&&n.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Email notifications are disabled. Enable them in the Messages tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.email_enabled?1:.5},children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Host"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_host,onChange:v=>b("smtp_host",v.target.value),placeholder:"smtp.example.com",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Port"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.smtp_port,onChange:v=>b("smtp_port",parseInt(v.target.value)||587),placeholder:"587",disabled:!a.email_enabled,style:{maxWidth:120}})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Username"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.smtp_username,onChange:v=>b("smtp_username",v.target.value),placeholder:"username or API key",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"SMTP Password"}),n.jsx("input",{type:"password",className:"cedros-admin__input",value:h.has("smtp_password")?a.smtp_password:"",onChange:v=>b("smtp_password",v.target.value),placeholder:a.smtp_password?"••••••••":"Enter password",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"From Email"}),n.jsx("input",{type:"email",className:"cedros-admin__input",value:a.from_email,onChange:v=>b("from_email",v.target.value),placeholder:"orders@yourstore.com",disabled:!a.email_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"From Name"}),n.jsx("input",{type:"text",className:"cedros-admin__input",value:a.from_name,onChange:v=>b("from_name",v.target.value),placeholder:"Your Store",disabled:!a.email_enabled})]})]})]}),s==="webhooks"&&n.jsxs("div",{className:"cedros-admin__section",children:[n.jsx("p",{style:{marginBottom:"1.5rem",fontSize:"0.875rem",opacity:.7},children:"Configure webhook endpoint for receiving purchase notifications."}),!a.webhook_enabled&&n.jsx("div",{style:{padding:"1rem",marginBottom:"1.5rem",background:"var(--cedros-admin-bg-accent, #fef3c7)",borderRadius:"0.5rem",border:"1px solid var(--cedros-admin-warning, #f59e0b)",fontSize:"0.875rem"},children:"Webhook notifications are disabled. Enable them in the Messages tab."}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",opacity:a.webhook_enabled?1:.5},children:[n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Webhook URL"}),n.jsx("input",{type:"url",className:"cedros-admin__input",value:a.webhook_url,onChange:v=>b("webhook_url",v.target.value),placeholder:"https://api.yoursite.com/webhooks/orders",disabled:!a.webhook_enabled})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Webhook Secret"}),n.jsx("input",{type:"password",className:"cedros-admin__input",value:h.has("webhook_secret")?a.webhook_secret:"",onChange:v=>b("webhook_secret",v.target.value),placeholder:a.webhook_secret?"••••••••":"Enter secret for HMAC-SHA256",disabled:!a.webhook_enabled}),n.jsx("p",{style:{margin:"0.25rem 0 0",fontSize:"0.75rem",opacity:.6},children:"Used for HMAC-SHA256 signature verification"})]}),n.jsxs("div",{className:"cedros-admin__field",children:[n.jsx("label",{className:"cedros-admin__field-label",children:"Timeout (seconds)"}),n.jsx("input",{type:"number",className:"cedros-admin__input",value:a.webhook_timeout,onChange:v=>b("webhook_timeout",parseInt(v.target.value)||30),placeholder:"30",disabled:!a.webhook_enabled,style:{maxWidth:120}})]})]})]})]})]})}function lh({status:e,error:t}){return e==="idle"?null:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:e==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[e==="pending"&&n.jsx("span",{style:{opacity:.7},children:"Unsaved changes"}),e==="saving"&&n.jsxs(n.Fragment,{children:[Q.loading,n.jsx("span",{children:"Saving..."})]}),e==="saved"&&n.jsxs(n.Fragment,{children:[Q.check,n.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),e==="error"&&n.jsxs("span",{children:["Save failed",t?`: ${t}`:""]})]})}function tc({checked:e,onChange:t,disabled:r=!1}){return n.jsx("button",{type:"button",role:"switch","aria-checked":e,disabled:r,onClick:t,style:{position:"relative",width:44,height:24,borderRadius:12,border:"none",backgroundColor:e?"var(--cedros-admin-primary, #171717)":"var(--cedros-admin-border, #d4d4d4)",cursor:r?"not-allowed":"pointer",transition:"background-color 0.2s",flexShrink:0,opacity:r?.5:1},children:n.jsx("span",{style:{position:"absolute",top:2,left:e?22:2,width:20,height:20,borderRadius:"50%",backgroundColor:"white",boxShadow:"0 1px 3px rgba(0,0,0,0.2)",transition:"left 0.2s"}})})}const dh=Object.freeze(Object.defineProperty({__proto__:null,MessagingSection:Zl},Symbol.toStringTag,{value:"Module"}));function Gl({serverUrl:e,apiKey:t,pageSize:r=20,authManager:s}){const[o,a]=y.useState([]),[i,c]=y.useState(!0),[l,d]=y.useState(!1),[m,u]=y.useState(null),[p,h]=y.useState(!1),[_,g]=y.useState(""),[f,w]=y.useState("all"),[j,b]=y.useState(null),[v,k]=y.useState(null),[R,N]=y.useState({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),C=y.useCallback(async()=>{c(!0);try{k(null);let z;const Z=`/admin/faqs?limit=${r}`;if(s?.isAuthenticated())z=await s.fetchWithAuth(Z);else{const K={"Content-Type":"application/json"};t&&(K["X-API-Key"]=t);const L=await fetch(`${e}${Z}`,{headers:K});if(!L.ok)throw new Error(`Failed to fetch FAQs: ${L.status}`);z=await L.json()}a(z.faqs||[])}catch{a([]),k("Failed to load FAQs")}finally{c(!1)}},[e,t,r,s]);y.useEffect(()=>{C()},[C]);const T=async z=>{if(z.preventDefault(),!(!R.question.trim()||!R.answer.trim())){h(!0);try{const Z=R.keywordsCsv.split(",").map(L=>L.trim().toLowerCase()).filter(Boolean),K={question:R.question.trim(),answer:R.answer.trim(),keywords:Z,active:R.active,useInChat:R.useInChat,displayOnPage:R.displayOnPage};if(m){const L=`/admin/faqs/${m.id}`;if(s?.isAuthenticated())await s.fetchWithAuth(L,{method:"PUT",body:JSON.stringify(K)});else{const W={"Content-Type":"application/json"};t&&(W["X-API-Key"]=t);const Y=await fetch(`${e}${L}`,{method:"PUT",headers:W,body:JSON.stringify(K)});if(!Y.ok)throw new Error(`Failed to update FAQ: ${Y.status}`)}}else if(s?.isAuthenticated())await s.fetchWithAuth("/admin/faqs",{method:"POST",body:JSON.stringify(K)});else{const L={"Content-Type":"application/json"};t&&(L["X-API-Key"]=t);const W=await fetch(`${e}/admin/faqs`,{method:"POST",headers:L,body:JSON.stringify(K)});if(!W.ok)throw new Error(`Failed to create FAQ: ${W.status}`)}S(),C()}catch{k(m?"Failed to update FAQ":"Failed to create FAQ")}finally{h(!1)}}},O=async z=>{try{const Z=`/admin/faqs/${z}`;if(s?.isAuthenticated())await s.fetchWithAuth(Z,{method:"DELETE"});else{const K={"Content-Type":"application/json"};t&&(K["X-API-Key"]=t);const L=await fetch(`${e}${Z}`,{method:"DELETE",headers:K});if(!L.ok)throw new Error(`Failed to delete FAQ: ${L.status}`)}C()}catch{k("Failed to delete FAQ")}b(null)},$=async z=>{try{const Z=`/admin/faqs/${z.id}`,K={...z,active:!z.active};if(s?.isAuthenticated())await s.fetchWithAuth(Z,{method:"PUT",body:JSON.stringify(K)});else{const L={"Content-Type":"application/json"};t&&(L["X-API-Key"]=t);const W=await fetch(`${e}${Z}`,{method:"PUT",headers:L,body:JSON.stringify(K)});if(!W.ok)throw new Error(`Failed to update FAQ: ${W.status}`)}C()}catch{k("Failed to update FAQ status")}},S=()=>{N({question:"",answer:"",keywordsCsv:"",active:!0,useInChat:!0,displayOnPage:!0}),u(null),d(!1)},A=z=>{N({question:z.question,answer:z.answer,keywordsCsv:z.keywords.join(", "),active:z.active,useInChat:z.useInChat??!0,displayOnPage:z.displayOnPage??!0}),u(z),d(!0)},I=o.length,B=o.filter(z=>z.active).length,D=o.filter(z=>z.active&&z.useInChat).length,E=o.filter(z=>z.active&&z.displayOnPage).length,P=y.useMemo(()=>o.filter(z=>{if(f==="active"&&!z.active||f==="inactive"&&z.active)return!1;if(_){const Z=_.toLowerCase();return z.question.toLowerCase().includes(Z)||z.answer.toLowerCase().includes(Z)||z.keywords.some(K=>K.includes(Z))}return!0}),[o,f,_]);return n.jsxs("div",{className:"cedros-admin__faqs",children:[n.jsx(Yt,{message:v,onRetry:C}),n.jsx(rr,{stats:[{label:"Total FAQs",value:I},{label:"Active",value:B,variant:"success"},{label:"In Chat",value:D},{label:"On Page",value:E}]}),n.jsxs("div",{className:"cedros-admin__section",children:[n.jsxs("div",{className:"cedros-admin__section-header",children:[n.jsxs("div",{className:"cedros-admin__section-header-left",children:[n.jsx("h3",{className:"cedros-admin__section-title",children:"Knowledge Base"}),n.jsx("p",{className:"cedros-admin__section-subtitle",children:"Manage FAQs for the AI chat assistant and public FAQ page."})]}),n.jsx("div",{className:"cedros-admin__section-header-right",children:n.jsxs("button",{className:"cedros-admin__btn cedros-admin__btn--primary",onClick:()=>{S(),d(!0)},children:[Q.plus," Add FAQ"]})})]}),n.jsxs("div",{className:"cedros-admin__filters",style:{display:"flex",gap:"1rem",marginBottom:"1rem"},children:[n.jsx("input",{type:"text",placeholder:"Search FAQs...",value:_,onChange:z=>g(z.target.value),className:"cedros-admin__input",style:{flex:1,maxWidth:300}}),n.jsxs("select",{value:f,onChange:z=>w(z.target.value),className:"cedros-admin__select",children:[n.jsx("option",{value:"all",children:"All Status"}),n.jsx("option",{value:"active",children:"Active Only"}),n.jsx("option",{value:"inactive",children:"Inactive Only"})]})]}),l&&n.jsx("div",{className:"cedros-admin__form-container",style:{marginBottom:"1.5rem"},children:n.jsxs("form",{onSubmit:T,className:"cedros-admin__form",children:[n.jsxs("div",{className:"cedros-admin__form-header",children:[n.jsx("h4",{children:m?"Edit FAQ":"Add New FAQ"}),n.jsx("button",{type:"button",className:"cedros-admin__btn--icon",onClick:S,children:Q.close})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Question *"}),n.jsx("input",{type:"text",value:R.question,onChange:z=>N(Z=>({...Z,question:z.target.value})),className:"cedros-admin__input",placeholder:"What is your return policy?",required:!0})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Answer *"}),n.jsx("textarea",{value:R.answer,onChange:z=>N(Z=>({...Z,answer:z.target.value})),className:"cedros-admin__textarea",placeholder:"We accept returns within 30 days...",rows:4,required:!0}),n.jsx("span",{className:"cedros-admin__hint",children:"Supports markdown formatting."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Keywords"}),n.jsx("input",{type:"text",value:R.keywordsCsv,onChange:z=>N(Z=>({...Z,keywordsCsv:z.target.value})),className:"cedros-admin__input",placeholder:"returns, refund, policy"}),n.jsx("span",{className:"cedros-admin__hint",children:"Comma-separated keywords to help AI find this FAQ."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:R.active,onChange:z=>N(Z=>({...Z,active:z.target.checked}))}),n.jsx("span",{children:"Active"})]}),n.jsx("span",{className:"cedros-admin__hint",children:"Inactive FAQs won't appear anywhere."})]}),n.jsxs("div",{className:"cedros-admin__form-group",children:[n.jsx("label",{className:"cedros-admin__label",children:"Visibility"}),n.jsxs("div",{className:"cedros-admin__checkbox-group",children:[n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:R.useInChat,onChange:z=>N(Z=>({...Z,useInChat:z.target.checked}))}),n.jsx("span",{children:"Use in AI Chat"})]}),n.jsxs("label",{className:"cedros-admin__checkbox-label",children:[n.jsx("input",{type:"checkbox",checked:R.displayOnPage,onChange:z=>N(Z=>({...Z,displayOnPage:z.target.checked}))}),n.jsx("span",{children:"Display on FAQ Page"})]})]}),n.jsx("span",{className:"cedros-admin__hint",children:"Choose where this FAQ should appear."})]}),n.jsxs("div",{className:"cedros-admin__form-actions",children:[n.jsx("button",{type:"button",className:"cedros-admin__btn",onClick:S,children:"Cancel"}),n.jsx("button",{type:"submit",className:"cedros-admin__btn cedros-admin__btn--primary",disabled:p||!R.question.trim()||!R.answer.trim(),children:p?Q.loading:m?"Update FAQ":"Create FAQ"})]})]})}),i?n.jsxs("div",{className:"cedros-admin__loading",children:[Q.loading,n.jsx("span",{children:"Loading FAQs..."})]}):P.length===0?n.jsx("div",{className:"cedros-admin__empty",children:n.jsx("p",{children:_||f!=="all"?"No FAQs match your filters.":"No FAQs yet. Add one to get started."})}):n.jsx("div",{className:"cedros-admin__faq-list",children:P.map(z=>n.jsxs("div",{className:`cedros-admin__faq-item ${z.active?"":"cedros-admin__faq-item--inactive"}`,children:[n.jsxs("div",{className:"cedros-admin__faq-content",children:[n.jsxs("div",{className:"cedros-admin__faq-question",children:[n.jsx("span",{className:`cedros-admin__status-dot ${z.active?"cedros-admin__status-dot--active":"cedros-admin__status-dot--inactive"}`}),z.question]}),n.jsx("div",{className:"cedros-admin__faq-answer",children:z.answer}),n.jsxs("div",{className:"cedros-admin__faq-meta",children:[z.keywords.length>0&&n.jsx("div",{className:"cedros-admin__faq-keywords",children:z.keywords.map(Z=>n.jsx("span",{className:"cedros-admin__tag",children:Z},Z))}),n.jsxs("div",{className:"cedros-admin__faq-visibility",children:[z.useInChat&&n.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--chat",title:"Used in AI Chat",children:[Q.chat," Chat"]}),z.displayOnPage&&n.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--page",title:"Displayed on FAQ Page",children:[Q.globe," Page"]})]})]})]}),n.jsxs("div",{className:"cedros-admin__faq-actions",children:[n.jsx("button",{className:"cedros-admin__btn--icon",onClick:()=>$(z),title:z.active?"Deactivate":"Activate",children:z.active?Q.eyeOff:Q.eye}),n.jsx("button",{className:"cedros-admin__btn--icon",onClick:()=>A(z),title:"Edit",children:Q.edit}),n.jsx("button",{className:"cedros-admin__btn--icon cedros-admin__btn--danger",onClick:()=>b(z.id),title:"Delete",children:Q.trash})]}),j===z.id&&n.jsx("div",{className:"cedros-admin__confirm-overlay",children:n.jsxs("div",{className:"cedros-admin__confirm-dialog",children:[n.jsx("p",{children:"Delete this FAQ?"}),n.jsxs("div",{className:"cedros-admin__confirm-actions",children:[n.jsx("button",{className:"cedros-admin__btn",onClick:()=>b(null),children:"Cancel"}),n.jsx("button",{className:"cedros-admin__btn cedros-admin__btn--danger",onClick:()=>O(z.id),children:"Delete"})]})]})})]},z.id))})]})]})}const uh=Object.freeze(Object.defineProperty({__proto__:null,FAQSection:Gl},Symbol.toStringTag,{value:"Module"}));class mh{serverUrl;walletSigner=null;jwtToken=null;constructor(t){this.serverUrl=t}getAuthMethod(){return this.walletSigner?.publicKey&&this.walletSigner.signMessage?"wallet":this.jwtToken?"cedros-login":"none"}isAuthenticated(){return this.getAuthMethod()!=="none"}setWalletSigner(t){this.walletSigner=t,J.getLogger().debug("[AdminAuthManager] Wallet signer updated:",!!t?.publicKey)}setCedrosLoginAuth(t,r){this.jwtToken=t,J.getLogger().debug("[AdminAuthManager] Cedros-login auth updated:",{hasToken:!!t})}async createAuthHeaders(t){const r=this.getAuthMethod();if(r==="wallet")return this.createWalletAuthHeaders(t);if(r==="cedros-login")return this.createJwtAuthHeaders();throw new Error("No admin authentication configured. Connect a wallet or sign in as admin.")}async createWalletAuthHeaders(t){if(!this.walletSigner?.publicKey||!this.walletSigner.signMessage)throw new Error("Wallet not connected or does not support message signing");const r=await this.fetchNonce(t),s=new TextEncoder().encode(r.nonce_id),o=await this.walletSigner.signMessage(s),a=Zi.bs58.encode(this.walletSigner.publicKey.toBytes()),i=Zi.bs58.encode(o);return{"X-Signer":a,"X-Message":r.nonce_id,"X-Signature":i}}createJwtAuthHeaders(){if(!this.jwtToken)throw new Error("No JWT token available");return{Authorization:`Bearer ${this.jwtToken}`}}async fetchNonce(t){const r=`${this.serverUrl}/paywall/v1/nonce`;J.getLogger().debug("[AdminAuthManager] Fetching nonce for purpose:",t);const s=await J.fetchWithTimeout(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({purpose:t})});if(!s.ok){const o=await s.text();throw new Error(`Failed to fetch nonce: ${s.status} ${o}`)}return await s.json()}async fetchWithAuth(t,r={}){if(this.getAuthMethod()==="none")throw new Error("No admin authentication configured");const o=this.getPurposeFromPath(t,r.method||"GET"),a=await this.createAuthHeaders(o),i={"Content-Type":"application/json",...r.headers||{},...a},c=await J.fetchWithTimeout(`${this.serverUrl}${t}`,{...r,headers:i});if(!c.ok){const l=await c.text();throw new Error(`Admin API error ${c.status}: ${l}`)}return await c.json()}getPurposeFromPath(t,r){const o={"/admin/stats":{GET:"admin_stats"},"/admin/products":{GET:"admin_products_list",POST:"admin_products_create"},"/admin/transactions":{GET:"admin_transactions_list"},"/admin/coupons":{GET:"admin_coupons_list",POST:"admin_coupons_create"},"/admin/refunds":{GET:"admin_refunds_list"},"/admin/config":{GET:"admin_config_list"}}[t];if(o?.[r])return o[r];if(t.startsWith("/admin/products/")){if(r==="PUT")return"admin_products_update";if(r==="DELETE")return"admin_products_delete"}if(t.startsWith("/admin/coupons/")){if(r==="PUT")return"admin_coupons_update";if(r==="DELETE")return"admin_coupons_delete"}if(t.startsWith("/admin/refunds/")&&t.includes("/process"))return"admin_refunds_process";if(t.startsWith("/admin/config/")){if(r==="GET")return"admin_config_get";if(r==="PUT")return"admin_config_update";if(r==="PATCH")return"admin_config_patch"}return`admin_${r.toLowerCase()}`}}function ph({serverUrl:e,cedrosLoginToken:t,isAdmin:r=!1}){const s=ja.useWallet(),o=y.useMemo(()=>{const u=new mh(e);return u.setCedrosLoginAuth(t??null,r),u},[e,t,r]);y.useEffect(()=>{s.publicKey&&s.signMessage?o.setWalletSigner({publicKey:s.publicKey,signMessage:s.signMessage}):o.setWalletSigner(null)},[o,s.publicKey,s.signMessage]);const a=o.getAuthMethod(),i=o.isAuthenticated(),c=!!(s.publicKey&&s.signMessage),l=!!t,d=y.useMemo(()=>{if(!s.publicKey)return null;const u=s.publicKey.toBase58();return`${u.slice(0,4)}...${u.slice(-4)}`},[s.publicKey]),m=y.useCallback((u,p)=>o.fetchWithAuth(u,p),[o]);return{authMethod:a,isAuthenticated:i,walletConnected:c,walletAddress:d,cedrosLoginAvailable:l,authManager:o,fetchWithAuth:m}}const Ql=[{label:"Menu",sections:[{id:"transactions",label:"Transactions",icon:Q.transactions},{id:"products",label:"Products",icon:Q.products},{id:"subscriptions",label:"Subscriptions",icon:Q.calendarRepeat},{id:"coupons",label:"Coupons",icon:Q.coupons},{id:"refunds",label:"Refunds",icon:Q.refunds}]},{label:"Configuration",collapsible:!0,sections:[{id:"storefront",label:"Storefront",icon:Q.storefront},{id:"ai-settings",label:"Store AI",icon:Q.brain},{id:"faqs",label:"Knowledge Base",icon:Q.faq},{id:"payment-settings",label:"Payment Options",icon:Q.creditCard},{id:"messaging",label:"Store Messages",icon:Q.mail},{id:"settings",label:"Store Server",icon:Q.server}]}],fh=Ql.flatMap(e=>e.sections);function hh(){const[e,t]=y.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");return y.useEffect(()=>{const r=window.matchMedia("(prefers-color-scheme: dark)"),s=o=>t(o.matches?"dark":"light");return r.addEventListener("change",s),()=>r.removeEventListener("change",s)},[]),e}function gh(e,t,r){return e!=="system"?e:t||r}function xh({serverUrl:e,apiKey:t,title:r="Cedros Pay",sections:s=["transactions","products","subscriptions","coupons","refunds","storefront","ai-settings","faqs","payment-settings","messaging","settings"],defaultSection:o="transactions",refreshInterval:a=3e4,pageSize:i=20,onSectionChange:c,className:l="",cedrosLoginToken:d,isAdmin:m=!1,theme:u="system"}){const[p,h]=y.useState(o),[_,g]=y.useState(!0),[f,w]=y.useState(new Set),j=y.useCallback($=>{w(S=>{const A=new Set(S);return A.has($)?A.delete($):A.add($),A})},[]),b=J.useCedrosThemeOptional(),v=hh(),R=gh(u,b?.mode??null,v)==="dark"?"cedros-admin--dark":"",{authManager:N}=ph({serverUrl:e,cedrosLoginToken:d,isAdmin:m}),C=y.useCallback($=>{h($),c?.($)},[c]),O=fh.filter($=>s.includes($.id)).find($=>$.id===p);return y.useEffect(()=>{const $=setTimeout(()=>g(!1),500);return()=>clearTimeout($)},[]),_?n.jsxs("div",{className:`cedros-admin cedros-admin--loading ${R} ${l}`,children:[Q.loading,n.jsx("span",{className:"cedros-admin__loading-text",children:"Loading dashboard..."})]}):n.jsxs("div",{className:`cedros-admin ${R} ${l}`,children:[n.jsxs("aside",{className:"cedros-admin__sidebar",children:[n.jsx("div",{className:"cedros-admin__sidebar-header",children:n.jsxs("div",{className:"cedros-admin__logo",children:[Q.wallet,n.jsx("span",{className:"cedros-admin__logo-text",children:r})]})}),n.jsx("nav",{className:"cedros-admin__nav",children:Ql.map($=>{const S=$.sections.filter(I=>s.includes(I.id));if(S.length===0)return null;const A=$.collapsible&&f.has($.label);return n.jsxs("div",{className:"cedros-admin__nav-group",children:[$.collapsible?n.jsxs("button",{type:"button",className:"cedros-admin__nav-label cedros-admin__nav-label--collapsible",onClick:()=>j($.label),"aria-expanded":!A,children:[$.label,n.jsx("span",{className:`cedros-admin__nav-label-icon ${A?"":"cedros-admin__nav-label-icon--expanded"}`,children:Q.chevronRight})]}):n.jsx("span",{className:"cedros-admin__nav-label",children:$.label}),!A&&S.map(I=>n.jsxs("button",{type:"button",className:`cedros-admin__nav-item ${p===I.id?"cedros-admin__nav-item--active":""}`,onClick:()=>C(I.id),"aria-current":p===I.id?"page":void 0,children:[n.jsx("span",{className:"cedros-admin__nav-icon",children:I.icon}),n.jsx("span",{className:"cedros-admin__nav-text",children:I.label})]},I.id))]},$.label)})})]}),n.jsxs("main",{className:"cedros-admin__main",children:[n.jsx("header",{className:"cedros-admin__header",children:n.jsxs("div",{className:"cedros-admin__breadcrumb",children:[n.jsx("span",{className:"cedros-admin__breadcrumb-root",children:r}),n.jsx("span",{className:"cedros-admin__breadcrumb-sep",children:Q.chevronRight}),n.jsx("span",{className:"cedros-admin__breadcrumb-current",children:O?.label})]})}),n.jsxs("div",{className:"cedros-admin__content",children:[p==="products"&&n.jsx(Ll,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="subscriptions"&&n.jsx(Wl,{serverUrl:e,apiKey:t,authManager:N}),p==="transactions"&&n.jsx($l,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="coupons"&&n.jsx(zl,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="refunds"&&n.jsx(Fl,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="storefront"&&n.jsx(Vl,{serverUrl:e,apiKey:t,authManager:N}),p==="ai-settings"&&n.jsx(ql,{serverUrl:e,apiKey:t,authManager:N}),p==="faqs"&&n.jsx(Gl,{serverUrl:e,apiKey:t,pageSize:i,authManager:N}),p==="payment-settings"&&n.jsx(Hl,{serverUrl:e,apiKey:t,authManager:N}),p==="messaging"&&n.jsx(Zl,{serverUrl:e,apiKey:t,authManager:N}),p==="settings"&&n.jsx(Ia,{serverUrl:e,apiKey:t,authManager:N})]})]})]})}const Pt=e=>y.lazy(async()=>{const s=(await e()).default;return{default:({pluginContext:a})=>{const i={serverUrl:a.serverUrl};return n.jsx(s,{...i})}}}),yh={id:"cedros-pay",name:"Cedros Pay",version:"1.0.0",sections:[{id:"transactions",label:"Transactions",icon:Q.transactions,group:"Store",order:0},{id:"products",label:"Products",icon:Q.products,group:"Store",order:1},{id:"subscriptions",label:"Subscriptions",icon:Q.subscriptions,group:"Store",order:2},{id:"coupons",label:"Coupons",icon:Q.coupons,group:"Store",order:3},{id:"refunds",label:"Refunds",icon:Q.refunds,group:"Store",order:4},{id:"storefront",label:"Storefront",icon:Q.storefront,group:"Configuration",order:10},{id:"ai-settings",label:"Store AI",icon:Q.ai,group:"Configuration",order:11},{id:"faqs",label:"Knowledge Base",icon:Q.faq,group:"Configuration",order:12},{id:"payment-settings",label:"Payment Options",icon:Q.wallet,group:"Configuration",order:13},{id:"messaging",label:"Store Messages",icon:Q.notifications,group:"Configuration",order:14},{id:"settings",label:"Store Server",icon:Q.settings,group:"Configuration",order:15}],groups:[{id:"Store",label:"Store",order:1},{id:"Configuration",label:"Configuration",order:2,defaultCollapsed:!0}],components:{products:Pt(()=>Promise.resolve().then(()=>require("./sections-B7ONQqXM.js")).then(e=>({default:e.ProductsSection}))),subscriptions:Pt(()=>Promise.resolve().then(()=>Jf).then(e=>({default:e.SubscriptionsSection}))),transactions:Pt(()=>Promise.resolve().then(()=>require("./sections-B7ONQqXM.js")).then(e=>({default:e.TransactionsSection}))),coupons:Pt(()=>Promise.resolve().then(()=>require("./sections-B7ONQqXM.js")).then(e=>({default:e.CouponsSection}))),refunds:Pt(()=>Promise.resolve().then(()=>require("./sections-B7ONQqXM.js")).then(e=>({default:e.RefundsSection}))),storefront:Pt(()=>Promise.resolve().then(()=>rh).then(e=>({default:e.StorefrontSection}))),"ai-settings":Pt(()=>Promise.resolve().then(()=>ih).then(e=>({default:e.AISettingsSection}))),faqs:Pt(()=>Promise.resolve().then(()=>uh).then(e=>({default:e.FAQSection}))),"payment-settings":Pt(()=>Promise.resolve().then(()=>ch).then(e=>({default:e.PaymentSettingsSection}))),messaging:Pt(()=>Promise.resolve().then(()=>dh).then(e=>({default:e.MessagingSection}))),settings:Pt(()=>Promise.resolve().then(()=>Yf).then(e=>({default:e.SettingsSection})))},createPluginContext(e){const t=e.cedrosPay,r=e.cedrosLogin;return{serverUrl:t?.serverUrl||r?.serverUrl||"",userId:r?.user?.id,getAccessToken:()=>r?.getAccessToken?.()||t?.jwtToken||null,hasPermission:o=>this.checkPermission(o,e),orgId:e.org?.orgId,pluginData:{walletAddress:t?.walletAddress}}},checkPermission(e,t){return t.org?.permissions?t.org.permissions.includes(e):!!(t.cedrosLogin?.user||t.cedrosPay?.jwtToken||t.cedrosPay?.walletAddress)},cssNamespace:"cedros-dashboard"};function vh({product:e,paymentMethod:t,showOriginalPrice:r=!1,className:s="",style:o={}}){const a=t==="stripe",i=a?e.fiatAmount:e.cryptoAmount,c=a?e.effectiveFiatAmount:e.effectiveCryptoAmount,l=a?e.fiatCurrency.toUpperCase():e.cryptoToken,d=a?e.hasStripeCoupon:e.hasCryptoCoupon,m=a?e.stripeDiscountPercent:e.cryptoDiscountPercent;return n.jsxs("div",{className:s,style:o,children:[r&&d&&n.jsxs("span",{style:{textDecoration:"line-through",opacity:.6,marginRight:"0.5rem",fontSize:"0.875em"},children:[i.toFixed(2)," ",l]}),n.jsxs("span",{style:{fontWeight:600},children:[c.toFixed(2)," ",l]}),d&&m>0&&n.jsxs("span",{style:{marginLeft:"0.5rem",padding:"0.125rem 0.375rem",backgroundColor:"#10b981",color:"white",borderRadius:"0.25rem",fontSize:"0.75em",fontWeight:600},children:[m,"% OFF"]})]})}function bh({product:e,paymentMethod:t,className:r="",style:s={}}){const o=t==="stripe",a=o?e.hasStripeCoupon:e.hasCryptoCoupon,i=o?e.stripeDiscountPercent:e.cryptoDiscountPercent,c=o?e.stripeCouponCode:e.cryptoCouponCode;if(!a||i===0)return null;const l=o?`${i}% off with card!`:`${i}% off with crypto!`;return n.jsxs("div",{className:r,style:{display:"inline-flex",alignItems:"center",padding:"0.5rem 0.75rem",backgroundColor:o?"#6366f1":"#10b981",color:"white",borderRadius:"0.375rem",fontSize:"0.875rem",fontWeight:600,...s},children:[l,c&&n.jsxs("span",{style:{marginLeft:"0.5rem",opacity:.8,fontSize:"0.75em",fontWeight:400},children:["(",c,")"]})]})}function Yl(){const{subscriptionManager:e}=J.useCedrosContext(),[t,r]=y.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null}),s=y.useCallback(async c=>{r(d=>({...d,status:"loading",error:null}));const l=await e.processSubscription(c);return r(d=>({...d,status:l.success?"success":"error",error:l.success?null:l.error||"Subscription failed",sessionId:l.success&&l.transactionId||null})),l},[e]),o=y.useCallback(async c=>{r(l=>({...l,status:"checking",error:null}));try{const l=await e.checkSubscriptionStatus(c);return r(d=>({...d,status:l.active?"success":"idle",subscriptionStatus:l.status,expiresAt:l.expiresAt||l.currentPeriodEnd||null})),l}catch(l){const d=l instanceof Error?l.message:"Failed to check subscription status";throw r(m=>({...m,status:"error",error:d})),l}},[e]),a=y.useCallback(async(c,l,d)=>{r(m=>({...m,status:"loading",error:null}));try{const m=await e.requestSubscriptionQuote(c,l,d);return r(u=>({...u,status:"idle"})),m}catch(m){const u=m instanceof Error?m.message:"Failed to get subscription quote";throw r(p=>({...p,status:"error",error:u})),m}},[e]),i=y.useCallback(()=>{r({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null})},[]);return{...t,processSubscription:s,checkStatus:o,requestQuote:a,reset:i}}function wh({resource:e,interval:t,intervalDays:r,trialDays:s,successUrl:o,cancelUrl:a,metadata:i,customerEmail:c,couponCode:l,label:d,disabled:m=!1,onAttempt:u,onSuccess:p,onError:h,className:_=""}){const{status:g,error:f,sessionId:w,processSubscription:j}=Yl(),b=J.useCedrosTheme(),{t:v,translations:k}=xn(),R=d||v("ui.subscribe"),N=b.unstyled?_:`${b.className} cedros-theme__stripe-button ${_}`.trim(),C=f&&typeof f!="string"?f?.code??null:null,O=f?typeof f=="string"?f:(D=>{if(!D||!k)return"";const E=k.errors[D];return E?E.action?`${E.message} ${E.action}`:E.message:""})(C):null,$=y.useCallback(async()=>{J.getLogger().debug("[SubscribeButton] executeSubscription:",{resource:e,interval:t,intervalDays:r,trialDays:s,couponCode:l}),Ln("stripe",e),u&&u("stripe"),un("stripe",e);const D=await j({resource:e,interval:t,intervalDays:r,trialDays:s,customerEmail:c,metadata:i,couponCode:l,successUrl:o,cancelUrl:a});D.success&&D.transactionId?($n("stripe",D.transactionId,e),p&&p(D.transactionId)):!D.success&&D.error&&(kt("stripe",D.error,e),h&&h(D.error))},[e,t,r,s,c,i,l,o,a,j,u,p,h]),S=y.useMemo(()=>`subscribe-${e}-${t}`,[e,t]),A=y.useMemo(()=>Mn(S,$),[S,$]),I=g==="loading",B=m||I;return n.jsxs("div",{className:N,style:b.unstyled?{}:b.style,children:[n.jsx("button",{onClick:A,disabled:B,className:b.unstyled?_:"cedros-theme__button cedros-theme__stripe",type:"button",children:I?v("ui.processing"):R}),O&&n.jsx("div",{className:b.unstyled?"":"cedros-theme__error",children:O}),w&&n.jsx("div",{className:b.unstyled?"":"cedros-theme__success",children:v("ui.redirecting_to_checkout")})]})}function Kl(){const{subscriptionManager:e,creditsManager:t}=J.useCedrosContext(),[r,s]=y.useState({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null}),o=y.useCallback(async(l,d)=>{s(m=>({...m,status:"checking",error:null}));try{const m=await e.checkSubscriptionStatus({resource:l,userId:d});return s(u=>({...u,status:m.active?"success":"idle",subscriptionStatus:m.status,expiresAt:m.expiresAt||m.currentPeriodEnd||null})),m}catch(m){const u=J.formatError(m,"Failed to check subscription status");return s(p=>({...p,status:"error",error:u})),null}},[e]),a=y.useCallback(async(l,d,m)=>{s(u=>({...u,status:"loading",error:null}));try{const u=await t.requestQuote(l,m?.couponCode);return s(p=>({...p,status:"idle",creditsRequirement:u})),u}catch(u){const p=J.formatError(u,"Failed to get subscription quote");return s(h=>({...h,status:"error",error:p})),null}},[t]),i=y.useCallback(async(l,d,m,u)=>{if(!m){const p="Authentication required for credits payment";return s(h=>({...h,status:"error",error:p})),{success:!1,error:p}}s(p=>({...p,status:"loading",error:null}));try{const p=await t.processPayment(l,m,u?.couponCode,{interval:d,...u?.intervalDays&&{intervalDays:String(u.intervalDays)}});return p.success?s({status:"success",error:null,sessionId:p.transactionId||null,subscriptionStatus:"active",expiresAt:null,creditsRequirement:null}):s(h=>({...h,status:"error",error:p.error||"Credits subscription payment failed"})),p}catch(p){const h=J.formatError(p,"Credits subscription payment failed");return s(_=>({..._,status:"error",error:h})),{success:!1,error:h}}},[t]),c=y.useCallback(()=>{s({status:"idle",error:null,sessionId:null,subscriptionStatus:null,expiresAt:null,creditsRequirement:null})},[]);return{...r,checkStatus:o,requestQuote:a,processPayment:i,reset:c}}function _h({resource:e,interval:t,intervalDays:r,authToken:s,userId:o,couponCode:a,label:i,disabled:c=!1,onAttempt:l,onSuccess:d,onError:m,className:u="",hideMessages:p=!1,autoCheckStatus:h=!1}){const{status:_,error:g,subscriptionStatus:f,expiresAt:w,checkStatus:j,processPayment:b}=Kl(),v=J.useCedrosTheme(),{t:k,translations:R}=xn(),N=y.useRef(j);y.useEffect(()=>{N.current=j},[j]),y.useEffect(()=>{h&&o&&(J.getLogger().debug("[CreditsSubscribeButton] Auto-checking subscription status",{resource:e,userId:o}),N.current(e,o))},[h,o,e]);const C=i||k("ui.subscribe_with_credits")||"Subscribe with Credits",T=g&&typeof g!="string"?g?.code??null:null,$=g?typeof g=="string"?g:(Z=>{if(!Z||!R)return"";const K=R.errors[Z];return K?K.action?`${K.message} ${K.action}`:K.message:""})(T):null,S=y.useCallback(async()=>{if(J.getLogger().debug("[CreditsSubscribeButton] executeSubscriptionFlow",{resource:e,interval:t,intervalDays:r,hasAuthToken:!!s}),Ln("credits",e),l&&l("credits"),!s){const K="Authentication required: please log in to subscribe with credits";J.getLogger().error("[CreditsSubscribeButton]",K),kt("credits",K,e),m&&m(K);return}un("credits",e);const Z=await b(e,t,s,{couponCode:a,intervalDays:r});Z.success&&Z.transactionId?($n("credits",Z.transactionId,e),d&&d(Z.transactionId)):!Z.success&&Z.error&&(kt("credits",Z.error,e),m&&m(Z.error))},[e,t,r,s,a,b,l,d,m]),A=y.useMemo(()=>`credits-subscribe-${e}-${t}`,[e,t]),I=y.useMemo(()=>Mn(A,S,{cooldownMs:200,deduplicationWindowMs:0}),[A,S]),B=_==="loading"||_==="checking",D=f==="active"||f==="trialing",E=c||B||D;let P=C;if(B)P=k("ui.processing");else if(D&&w){const Z=new Date(w).toLocaleDateString();P=`${k("ui.subscribed_until")} ${Z}`}else D&&(P=k("ui.subscribed"));const z=v.unstyled?u:`${v.className} cedros-theme__credits-button ${u}`.trim();return n.jsxs("div",{className:z,style:v.unstyled?{}:v.style,children:[n.jsx("button",{onClick:I,disabled:E,className:v.unstyled?u:"cedros-theme__button cedros-theme__credits",type:"button",children:P}),!p&&$&&n.jsx("div",{className:v.unstyled?"":"cedros-theme__error",children:$}),!p&&D&&n.jsx("div",{className:v.unstyled?"":"cedros-theme__success",children:k("ui.subscription_active")})]})}function Xl(){const{subscriptionChangeManager:e}=J.useCedrosContext(),[t,r]=y.useState({status:"idle",error:null,subscription:null,changePreview:null,userId:null}),s=y.useRef(t);s.current=t;const o=y.useCallback(async(u,p)=>{r(h=>({...h,status:"loading",error:null}));try{const h=await e.getDetails(u,p);return r(_=>({..._,status:"success",subscription:h,userId:p})),h}catch(h){const _=h instanceof Error?h.message:"Failed to load subscription";return r(g=>({...g,status:"error",error:_})),null}},[e]),a=y.useCallback(async(u,p,h,_)=>{r(g=>({...g,status:"loading",error:null}));try{const g={currentResource:u,newResource:p,userId:h,newInterval:_},f=await e.previewChange(g);return r(w=>({...w,status:"idle",changePreview:f})),f}catch(g){const f=g instanceof Error?g.message:"Failed to preview change";return r(w=>({...w,status:"error",error:f})),null}},[e]),i=y.useCallback(async u=>{const{subscription:p,userId:h}=s.current;if(!p||!h)return r(_=>({..._,status:"error",error:"No subscription loaded"})),null;r(_=>({..._,status:"loading",error:null}));try{const _={currentResource:p.resource,newResource:u.newResource,userId:h,newInterval:u.newInterval,prorationBehavior:u.prorationBehavior,immediate:u.immediate},g=await e.changeSubscription(_);return g.success?r(f=>({...f,status:"success",subscription:f.subscription?{...f.subscription,resource:g.newResource,interval:g.newInterval,status:g.status}:null,changePreview:null})):r(f=>({...f,status:"error",error:g.error||"Failed to change subscription"})),g}catch(_){const g=_ instanceof Error?_.message:"Failed to change subscription";return r(f=>({...f,status:"error",error:g})),null}},[e]),c=y.useCallback(async u=>{const{subscription:p,userId:h}=s.current;if(!p||!h)return r(_=>({..._,status:"error",error:"No subscription loaded"})),null;r(_=>({..._,status:"loading",error:null}));try{const _={resource:p.resource,userId:h,immediate:u},g=await e.cancel(_);if(g.success){const f=u?"canceled":p.status;r(w=>({...w,status:"success",subscription:w.subscription?{...w.subscription,status:f,cancelAtPeriodEnd:!u}:null}))}else r(f=>({...f,status:"error",error:g.error||"Failed to cancel subscription"}));return g}catch(_){const g=_ instanceof Error?_.message:"Failed to cancel subscription";return r(f=>({...f,status:"error",error:g})),null}},[e]),l=y.useCallback(async(u,p)=>{r(h=>({...h,status:"loading",error:null}));try{const h=await e.getBillingPortalUrl({userId:u,returnUrl:p});return window.location.href=h.url,h}catch(h){const _=h instanceof Error?h.message:"Failed to open billing portal";return r(g=>({...g,status:"error",error:_})),null}},[e]),d=y.useCallback(()=>{r(u=>({...u,changePreview:null}))},[]),m=y.useCallback(()=>{r({status:"idle",error:null,subscription:null,changePreview:null,userId:null})},[]);return{...t,loadSubscription:o,previewChange:a,changeSubscription:i,cancelSubscription:c,openBillingPortal:l,clearPreview:d,reset:m}}const jh={bg:"#fff",bgMuted:"#f9fafb",bgHighlight:"#eff6ff",text:"#111827",textMuted:"#6b7280",textFaint:"#9ca3af",border:"#e5e7eb",borderLight:"#f3f4f6",primary:"#3b82f6",error:"#ef4444",errorBg:"#fef2f2",errorBorder:"#fecaca",warningBg:"#fef3c7",warningBorder:"#fcd34d",warningText:"#92400e",buttonBg:"#f3f4f6",buttonBorder:"#d1d5db",buttonText:"#374151"},kh={bg:"#1e293b",bgMuted:"#334155",bgHighlight:"rgba(59, 130, 246, 0.15)",text:"#f1f5f9",textMuted:"#94a3b8",textFaint:"#64748b",border:"#475569",borderLight:"#334155",primary:"#3b82f6",error:"#ef4444",errorBg:"rgba(239, 68, 68, 0.15)",errorBorder:"rgba(239, 68, 68, 0.3)",warningBg:"rgba(245, 158, 11, 0.15)",warningBorder:"rgba(245, 158, 11, 0.3)",warningText:"#fbbf24",buttonBg:"#334155",buttonBorder:"#475569",buttonText:"#e2e8f0"};function Sh(e){const t=e?kh:jh;return{container:{padding:"24px",backgroundColor:t.bg,borderRadius:"8px",border:`1px solid ${t.border}`,fontFamily:"system-ui, -apple-system, sans-serif",color:t.text},error:{padding:"12px 16px",backgroundColor:t.errorBg,border:`1px solid ${t.errorBorder}`,borderRadius:"6px",color:t.error,marginBottom:"16px"},loading:{padding:"24px",textAlign:"center",color:t.textMuted},details:{marginBottom:"24px"},title:{margin:"0 0 16px 0",fontSize:"18px",fontWeight:600,color:t.text},detailRow:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"8px 0",borderBottom:`1px solid ${t.borderLight}`},label:{color:t.textMuted,fontSize:"14px"},value:{color:t.text,fontSize:"14px",fontWeight:500},statusBadge:{padding:"4px 8px",borderRadius:"4px",color:"#fff",fontSize:"12px",fontWeight:500,textTransform:"capitalize"},cancelNotice:{marginTop:"12px",padding:"8px 12px",backgroundColor:t.warningBg,border:`1px solid ${t.warningBorder}`,borderRadius:"6px",color:t.warningText,fontSize:"13px"},prorationPreview:{padding:"16px",backgroundColor:t.bgMuted,borderRadius:"8px",marginBottom:"24px"},previewTitle:{margin:"0 0 12px 0",fontSize:"16px",fontWeight:600,color:t.text},previewDetails:{marginBottom:"16px"},previewRow:{display:"flex",justifyContent:"space-between",padding:"6px 0",fontSize:"14px",color:t.textMuted},previewTotal:{borderTop:`1px solid ${t.border}`,marginTop:"8px",paddingTop:"12px",fontWeight:600,color:t.text},previewActions:{display:"flex",gap:"12px",justifyContent:"flex-end"},cancelButton:{padding:"8px 16px",backgroundColor:t.bg,border:`1px solid ${t.buttonBorder}`,borderRadius:"6px",color:t.buttonText,cursor:"pointer",fontSize:"14px"},confirmButton:{padding:"8px 16px",backgroundColor:t.primary,border:"none",borderRadius:"6px",color:"#fff",cursor:"pointer",fontSize:"14px",fontWeight:500},plansSection:{marginBottom:"24px"},plansTitle:{margin:"0 0 12px 0",fontSize:"16px",fontWeight:600,color:t.text},plansList:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))",gap:"16px"},planCard:{padding:"16px",backgroundColor:t.bg,border:`1px solid ${t.border}`,borderRadius:"8px",textAlign:"center"},currentPlan:{borderColor:t.primary,backgroundColor:t.bgHighlight},planName:{fontSize:"16px",fontWeight:600,color:t.text,marginBottom:"4px"},planPrice:{fontSize:"14px",color:t.textMuted,marginBottom:"8px"},planDescription:{fontSize:"12px",color:t.textFaint,marginBottom:"12px"},currentBadge:{display:"inline-block",padding:"4px 8px",backgroundColor:t.primary,color:"#fff",borderRadius:"4px",fontSize:"12px",fontWeight:500},changePlanButton:{padding:"8px 16px",backgroundColor:t.buttonBg,border:`1px solid ${t.buttonBorder}`,borderRadius:"6px",color:t.buttonText,cursor:"pointer",fontSize:"14px",width:"100%"},actions:{display:"flex",gap:"12px",justifyContent:"flex-end",paddingTop:"16px",borderTop:`1px solid ${t.border}`},portalButton:{padding:"10px 20px",backgroundColor:t.primary,border:"none",borderRadius:"6px",color:"#fff",cursor:"pointer",fontSize:"14px",fontWeight:500},cancelSubscriptionButton:{padding:"10px 20px",backgroundColor:t.bg,border:`1px solid ${t.error}`,borderRadius:"6px",color:t.error,cursor:"pointer",fontSize:"14px"}}}function Nn(e,t){return new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).format(e/100)}function Jl(e){return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}function Ch(e){switch(e){case"active":return"#22c55e";case"trialing":return"#3b82f6";case"past_due":return"#f59e0b";case"canceled":case"expired":return"#ef4444";default:return"#6b7280"}}function Nh({preview:e,onConfirm:t,onCancel:r,isLoading:s,styles:o}){const a=e.immediateAmount<0;return n.jsxs("div",{className:"cedros-proration-preview",style:o.prorationPreview,children:[n.jsx("h4",{style:o.previewTitle,children:"Change Preview"}),n.jsxs("div",{style:o.previewDetails,children:[n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Current plan:"}),n.jsxs("span",{children:[Nn(e.currentPlanPrice,e.currency),"/period"]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"New plan:"}),n.jsxs("span",{children:[Nn(e.newPlanPrice,e.currency),"/period"]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Days remaining:"}),n.jsxs("span",{children:[e.daysRemaining," days"]})]}),e.prorationDetails&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Unused credit:"}),n.jsxs("span",{children:["-",Nn(e.prorationDetails.unusedCredit,e.currency)]})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"New plan cost:"}),n.jsx("span",{children:Nn(e.prorationDetails.newPlanCost,e.currency)})]})]}),n.jsxs("div",{style:{...o.previewRow,...o.previewTotal},children:[n.jsx("span",{children:a?"Credit to account:":"Amount due now:"}),n.jsx("span",{style:{color:a?"#22c55e":"#ef4444"},children:Nn(Math.abs(e.immediateAmount),e.currency)})]}),n.jsxs("div",{style:o.previewRow,children:[n.jsx("span",{children:"Effective date:"}),n.jsx("span",{children:Jl(e.effectiveDate)})]})]}),n.jsxs("div",{style:o.previewActions,children:[n.jsx("button",{onClick:r,style:o.cancelButton,disabled:s,children:"Cancel"}),n.jsx("button",{onClick:t,style:o.confirmButton,disabled:s,children:s?"Processing...":"Confirm Change"})]})]})}function Ph({resource:e,userId:t,availablePlans:r=[],onSubscriptionChanged:s,onSubscriptionCanceled:o,billingPortalReturnUrl:a,showBillingPortal:i=!1,className:c,style:l}){const{mode:d}=J.useCedrosTheme(),m=y.useMemo(()=>Sh(d==="dark"),[d]),{subscription:u,changePreview:p,status:h,error:_,loadSubscription:g,previewChange:f,changeSubscription:w,cancelSubscription:j,openBillingPortal:b,clearPreview:v}=Xl();y.useEffect(()=>{g(e,t)},[e,t,g]);const k=y.useCallback(async(O,$)=>{await f(e,O,t,$)},[e,t,f]),R=y.useCallback(async()=>{if(!p)return;const O=r.find(S=>S.price===p.newPlanPrice&&S.currency===p.currency);(await w({newResource:O?.resource||e,newInterval:O?.interval,immediate:!0}))?.success&&O&&s?.(O.resource,O.interval)},[p,r,e,w,s]),N=y.useCallback(async O=>{(await j(O))?.success&&o?.()},[j,o]),C=y.useCallback(()=>{b(t,a)},[t,a,b]),T=h==="loading";return n.jsxs("div",{className:`cedros-subscription-panel ${c||""}`,style:{...m.container,...l},children:[_&&n.jsx("div",{className:"cedros-subscription-error",style:m.error,children:_}),T&&!u&&n.jsx("div",{className:"cedros-subscription-loading",style:m.loading,children:"Loading subscription..."}),u&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"cedros-subscription-details",style:m.details,children:[n.jsx("h3",{style:m.title,children:"Current Subscription"}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Plan:"}),n.jsx("span",{style:m.value,children:u.resource})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Status:"}),n.jsx("span",{style:{...m.statusBadge,backgroundColor:Ch(u.status)},children:u.status})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Price:"}),n.jsxs("span",{style:m.value,children:[Nn(u.pricePerPeriod,u.currency),"/",u.interval]})]}),n.jsxs("div",{style:m.detailRow,children:[n.jsx("span",{style:m.label,children:"Current period ends:"}),n.jsx("span",{style:m.value,children:Jl(u.currentPeriodEnd)})]}),u.cancelAtPeriodEnd&&n.jsx("div",{style:m.cancelNotice,children:"Subscription will cancel at end of current period"})]}),p&&n.jsx(Nh,{preview:p,onConfirm:R,onCancel:v,isLoading:T,styles:m}),r.length>0&&!p&&n.jsxs("div",{className:"cedros-available-plans",style:m.plansSection,children:[n.jsx("h4",{style:m.plansTitle,children:"Available Plans"}),n.jsx("div",{style:m.plansList,children:r.map(O=>{const $=O.resource===u.resource;return n.jsxs("div",{style:{...m.planCard,...$?m.currentPlan:{}},children:[n.jsx("div",{style:m.planName,children:O.name}),n.jsxs("div",{style:m.planPrice,children:[Nn(O.price,O.currency),"/",O.interval]}),O.description&&n.jsx("div",{style:m.planDescription,children:O.description}),$?n.jsx("span",{style:m.currentBadge,children:"Current Plan"}):n.jsx("button",{onClick:()=>k(O.resource,O.interval),style:m.changePlanButton,disabled:T,children:O.price>u.pricePerPeriod?"Upgrade":"Downgrade"})]},O.resource)})})]}),n.jsxs("div",{className:"cedros-subscription-actions",style:m.actions,children:[i&&u.paymentMethod==="stripe"&&n.jsx("button",{onClick:C,style:m.portalButton,disabled:T,children:"Manage Billing"}),u.status==="active"&&!u.cancelAtPeriodEnd&&n.jsx("button",{onClick:()=>N(!1),style:m.cancelSubscriptionButton,disabled:T,children:"Cancel Subscription"})]})]})]})}function Ah(){if(typeof window>"u")return{passed:!0,severity:"info",message:"HTTPS check skipped (SSR environment)"};const e=window.location.protocol==="https:",t=window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1";return e||t?{passed:!0,severity:"info",message:"HTTPS enforced"}:{passed:!1,severity:"error",message:"Page not served over HTTPS",recommendation:"Enable HTTPS for all payment pages. Stripe.js requires HTTPS in production."}}function Eh(){return typeof document>"u"?{passed:!0,severity:"info",message:"CSP check skipped (SSR environment)"}:document.querySelector('meta[http-equiv="Content-Security-Policy"]')?{passed:!0,severity:"info",message:"Content Security Policy detected"}:{passed:!1,severity:"warning",message:"No Content Security Policy detected",recommendation:"Configure CSP headers to protect against XSS and CDN compromise. Use generateCSP() helper from @cedros/pay-react."}}function Th(){return process.env.NODE_ENV==="development"||typeof window<"u"&&window.location.hostname==="localhost"?{passed:!0,severity:"info",message:"Running in development mode (some security checks relaxed)"}:{passed:!0,severity:"info",message:"Running in production mode"}}function Ih(){return{passed:!0,severity:"info",message:"Stripe.js loaded via @stripe/stripe-js package (CSP recommended, not SRI)",recommendation:"Ensure CSP script-src includes https://js.stripe.com"}}function Rh(){return typeof window>"u"?{passed:!0,severity:"info",message:"Mixed content check skipped (SSR environment)"}:window.location.protocol==="https:"?{passed:!0,severity:"info",message:"Mixed content protection active (HTTPS page)"}:{passed:!0,severity:"info",message:"Mixed content check skipped (HTTP page)"}}function Oh(){const e=[Ah(),Eh(),Th(),Ih(),Rh()],t=e.some(a=>a.severity==="error"&&!a.passed),r=e.some(a=>a.severity==="warning"&&!a.passed);let s,o;return t?(s="vulnerable",o="Security issues detected. Review errors and apply recommendations."):r?(s="warnings",o="Minor security warnings detected. Consider applying recommendations."):(s="secure",o="All security checks passed."),{checks:e,overallStatus:s,summary:o}}function Mh(e){process.env.NODE_ENV!=="production"&&(console.group("🔒 Cedros Pay Security Report"),console.log(`Status: ${e.overallStatus.toUpperCase()}`),console.log(`Summary: ${e.summary}`),console.log(""),e.checks.forEach(t=>{const r=t.passed?"✅":t.severity==="error"?"❌":"⚠️";console.log(`${r} ${t.message}`),t.recommendation&&console.log(` → ${t.recommendation}`)}),console.groupEnd())}const Dh={CSP:"Use generateCSP() from @cedros/pay-react to generate Content Security Policy headers",HTTPS:"Always serve payment pages over HTTPS in production",PACKAGE_UPDATES:"Keep @stripe/stripe-js and @cedros/pay-react updated for security patches",AUDIT:"Run npm audit regularly to check for known vulnerabilities",MONITORING:"Monitor Stripe security advisories and apply updates promptly",NO_SRI:"Do NOT use SRI hashes for Stripe.js - use CSP instead"},Ra=y.createContext(null);function Re(){const e=y.useContext(Ra);if(!e)throw new Error("useCedrosShop must be used within CedrosShopProvider");return e}function Oa(){return y.useContext(Ra)}function Lh({config:e,children:t}){return n.jsx(Ra.Provider,{value:{config:e},children:t})}function At(e){return new Promise(t=>setTimeout(t,e))}const ed=[{id:"cat_all",slug:"all",name:"All Products",description:"Everything in the catalog."},{id:"cat_apparel",slug:"apparel",name:"Apparel",description:"Soft goods and daily wear."},{id:"cat_accessories",slug:"accessories",name:"Accessories",description:"Carry, attach, decorate."}],hs=[{id:"p_tee",slug:"cedros-tee",title:"Cedros Tee",description:"A heavyweight tee with a clean silhouette.",images:[{url:"https://picsum.photos/seed/cedros-tee/900/900",alt:"Cedros Tee"},{url:"https://picsum.photos/seed/cedros-tee-2/900/900",alt:"Cedros Tee detail"}],price:38,currency:"USD",tags:["new","cotton"],categoryIds:["cat_apparel"],compareAtPrice:48,inventoryStatus:"in_stock",variants:[{id:"v_tee_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_tee_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_tee_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_crewneck",slug:"cedros-crewneck",title:"Cedros Crewneck",description:"Midweight fleece with a relaxed fit and embroidered mark.",images:[{url:"https://picsum.photos/seed/cedros-crewneck/900/900",alt:"Cedros Crewneck"}],price:64,currency:"USD",tags:["fleece","core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",compareAtPrice:78,variants:[{id:"v_crew_s",title:"Small / Heather",options:{Size:"S",Color:"Heather"}},{id:"v_crew_m",title:"Medium / Heather",options:{Size:"M",Color:"Heather"}},{id:"v_crew_l",title:"Large / Heather",options:{Size:"L",Color:"Heather"}}],shippingProfile:"physical"},{id:"p_hoodie",slug:"cedros-hoodie",title:"Cedros Hoodie",description:"Pullover hoodie with soft interior and structured hood.",images:[{url:"https://picsum.photos/seed/cedros-hoodie/900/900",alt:"Cedros Hoodie"},{url:"https://picsum.photos/seed/cedros-hoodie-2/900/900",alt:"Cedros Hoodie detail"}],price:74,currency:"USD",tags:["fleece","new"],categoryIds:["cat_apparel"],inventoryStatus:"low",variants:[{id:"v_hoodie_s",title:"Small / Black",options:{Size:"S",Color:"Black"}},{id:"v_hoodie_m",title:"Medium / Black",options:{Size:"M",Color:"Black"}},{id:"v_hoodie_l",title:"Large / Black",options:{Size:"L",Color:"Black"}}],shippingProfile:"physical"},{id:"p_cap",slug:"cedros-cap",title:"Cedros Cap",description:"Unstructured cap with adjustable strap and curved brim.",images:[{url:"https://picsum.photos/seed/cedros-cap/900/900",alt:"Cedros Cap"}],price:28,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_socks",slug:"cedros-socks",title:"Cedros Socks",description:"Rib-knit socks designed for everyday comfort.",images:[{url:"https://picsum.photos/seed/cedros-socks/900/900",alt:"Cedros Socks"}],price:14,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_tote",slug:"cedros-tote",title:"Cedros Tote",description:"Heavy canvas tote with reinforced handles.",images:[{url:"https://picsum.photos/seed/cedros-tote/900/900",alt:"Cedros Tote"}],price:32,currency:"USD",tags:["gift","canvas"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_stickers",slug:"cedros-sticker-pack",title:"Sticker Pack",description:"Five durable vinyl stickers for laptops and water bottles.",images:[{url:"https://picsum.photos/seed/cedros-stickers/900/900",alt:"Sticker Pack"}],price:8,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_keychain",slug:"cedros-keychain",title:"Enamel Keychain",description:"Polished enamel keychain with a subtle mark.",images:[{url:"https://picsum.photos/seed/cedros-keychain/900/900",alt:"Enamel Keychain"}],price:12,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_lanyard",slug:"cedros-lanyard",title:"Woven Lanyard",description:"Soft woven lanyard with swivel clasp.",images:[{url:"https://picsum.photos/seed/cedros-lanyard/900/900",alt:"Woven Lanyard"}],price:10,currency:"USD",tags:["core"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_notebook",slug:"cedros-notebook",title:"Dot Grid Notebook",description:"Lay-flat notebook for sketches, notes, and plans.",images:[{url:"https://picsum.photos/seed/cedros-notebook/900/900",alt:"Dot Grid Notebook"}],price:18,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_waterbottle",slug:"cedros-water-bottle",title:"Insulated Bottle",description:"Vacuum-insulated bottle that keeps drinks cold for hours.",images:[{url:"https://picsum.photos/seed/cedros-bottle/900/900",alt:"Insulated Bottle"}],price:36,currency:"USD",tags:["gift","new"],categoryIds:["cat_accessories"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_posters",slug:"cedros-poster-set",title:"Poster Set",description:"Two prints on thick matte stock.",images:[{url:"https://picsum.photos/seed/cedros-posters/900/900",alt:"Poster Set"}],price:24,currency:"USD",tags:["gift","limited"],categoryIds:["cat_accessories"],inventoryStatus:"out_of_stock",shippingProfile:"physical"},{id:"p_pins",slug:"cedros-pin-set",title:"Pin Set",description:"Two enamel pins with rubber backings.",images:[{url:"https://picsum.photos/seed/cedros-pins/900/900",alt:"Pin Set"}],price:16,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_brandbook",slug:"cedros-brand-book",title:"Brand Book (PDF)",description:"A compact brand book: typography, color, layout, and voice.",images:[{url:"https://picsum.photos/seed/cedros-brandbook/900/900",alt:"Brand Book cover"}],price:19,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital",checkoutRequirements:{email:"optional",name:"none",phone:"none",shippingAddress:!1,billingAddress:!1},fulfillment:{type:"digital_download",notes:"This is a digital product and will be downloadable from your account after purchase."}},{id:"p_wallpaper",slug:"cedros-wallpaper-pack",title:"Wallpaper Pack",description:"A set of desktop + mobile wallpapers in multiple colorways.",images:[{url:"https://picsum.photos/seed/cedros-wallpaper/900/900",alt:"Wallpaper Pack"}],price:6,currency:"USD",tags:["digital","new"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"},{id:"p_longsleeve",slug:"cedros-long-sleeve",title:"Long Sleeve Tee",description:"Soft long sleeve tee with rib cuff and relaxed drape.",images:[{url:"https://picsum.photos/seed/cedros-longsleeve/900/900",alt:"Long Sleeve Tee"}],price:44,currency:"USD",tags:["cotton"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_shorts",slug:"cedros-shorts",title:"Everyday Shorts",description:"Lightweight shorts with a comfortable waistband.",images:[{url:"https://picsum.photos/seed/cedros-shorts/900/900",alt:"Everyday Shorts"}],price:40,currency:"USD",tags:["new"],categoryIds:["cat_apparel"],inventoryStatus:"in_stock",shippingProfile:"physical"},{id:"p_beanie",slug:"cedros-beanie",title:"Rib Beanie",description:"Warm rib beanie with a clean folded cuff.",images:[{url:"https://picsum.photos/seed/cedros-beanie/900/900",alt:"Rib Beanie"}],price:20,currency:"USD",tags:["core"],categoryIds:["cat_apparel"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_jacket",slug:"cedros-coach-jacket",title:"Coach Jacket",description:"Lightweight jacket with snap front and subtle sheen.",images:[{url:"https://picsum.photos/seed/cedros-jacket/900/900",alt:"Coach Jacket"}],price:96,currency:"USD",tags:["limited"],categoryIds:["cat_apparel"],inventoryStatus:"backorder",shippingProfile:"physical"},{id:"p_mug",slug:"cedros-mug",title:"Cedros Mug",description:"Stoneware mug with a satin glaze.",images:[{url:"https://picsum.photos/seed/cedros-mug/900/900",alt:"Cedros Mug"}],price:22,currency:"USD",tags:["gift"],categoryIds:["cat_accessories"],inventoryStatus:"low",shippingProfile:"physical"},{id:"p_guide",slug:"cedros-field-guide",title:"Field Guide (Digital)",description:"A short digital guide to shipping delightful checkout flows.",images:[{url:"https://picsum.photos/seed/cedros-guide/900/900",alt:"Field Guide cover"}],price:12,currency:"USD",tags:["digital"],categoryIds:["cat_accessories"],inventoryStatus:"in_stock",shippingProfile:"digital"}];let So=[];const Vr={};function $h(e,t){let r=e;if(t.category&&t.category!=="all"){const l=ed.find(d=>d.slug===t.category||d.id===t.category);l&&(r=r.filter(d=>d.categoryIds.includes(l.id)))}if(t.search){const l=t.search.toLowerCase();r=r.filter(d=>d.title.toLowerCase().includes(l)||d.description.toLowerCase().includes(l))}const s=t.filters??{},o=s.tags;if(Array.isArray(o)&&o.length>0){const l=new Set(o.map(String));r=r.filter(d=>d.tags?.some(m=>l.has(m)))}const a=typeof s.priceMin=="number"?s.priceMin:void 0,i=typeof s.priceMax=="number"?s.priceMax:void 0;return typeof a=="number"&&(r=r.filter(l=>l.price>=a)),typeof i=="number"&&(r=r.filter(l=>l.price<=i)),(typeof s.inStock=="boolean"?s.inStock:void 0)===!0&&(r=r.filter(l=>l.inventoryStatus!=="out_of_stock")),r}function zh(e,t){if(!t||t==="featured")return e;const r=[...e];return t==="price_asc"&&r.sort((s,o)=>s.price-o.price),t==="price_desc"&&r.sort((s,o)=>o.price-s.price),r}function Fh(e,t,r){const s=(t-1)*r;return{items:e.slice(s,s+r),page:t,pageSize:r,total:e.length,hasNextPage:s+r<e.length}}function Bh(e){const t=new Date().toISOString(),r=e.cart.map(o=>{const a=hs.find(i=>i.id===o.resource||i.slug===o.resource)??hs[0];return{title:a.title,qty:o.quantity,unitPrice:a.price,currency:e.options.currency,imageUrl:a.images[0]?.url}}),s=r.reduce((o,a)=>o+a.qty*a.unitPrice,0);return{id:`ord_${Math.random().toString(16).slice(2)}`,createdAt:t,status:"paid",total:s,currency:e.options.currency,items:r,receiptUrl:e.options.successUrl}}function Uh(){return{async listProducts(e){await At(150);const t=e.page??1,r=e.pageSize??24,s=$h(hs,e),o=zh(s,e.sort);return Fh(o,t,r)},async getProductBySlug(e){return await At(100),hs.find(t=>t.slug===e)??null},async listCategories(){return await At(80),ed},async getOrderHistory(){return await At(120),So},async getCart({customerId:e}){return await At(80),Vr[e]??{items:[]}},async mergeCart({customerId:e,cart:t}){await At(120);const r=Vr[e]??{items:[]},s=new Map,o=i=>{const c=`${i.productId}::${i.variantId??""}`,l=s.get(c);l?s.set(c,{...l,qty:l.qty+i.qty}):s.set(c,i)};for(const i of r.items)o(i);for(const i of t.items)o(i);const a={items:Array.from(s.values()),promoCode:t.promoCode??r.promoCode};return Vr[e]=a,a},async updateCart({customerId:e,cart:t}){await At(60),Vr[e]=t},async createCheckoutSession(e){await At(250);const t=Bh(e);if(So=[t,...So].slice(0,25),e.options.successUrl){const r=new URL(e.options.successUrl,"http://localhost");return r.searchParams.set("demoOrderId",t.id),{kind:"redirect",url:r.toString().replace("http://localhost","")}}return{kind:"custom",data:{orderId:t.id}}},async listSubscriptionTiers(){return await At(80),[{id:"tier_starter",title:"Starter",description:"For small shops getting started.",priceMonthly:19,priceAnnual:190,currency:"USD",features:["Basic analytics","Email support","1 storefront"]},{id:"tier_growth",title:"Growth",description:"For teams iterating fast.",priceMonthly:49,priceAnnual:490,currency:"USD",features:["Advanced analytics","Priority support","3 storefronts"],isPopular:!0},{id:"tier_enterprise",title:"Enterprise",description:"For high volume and custom needs.",priceMonthly:199,priceAnnual:1990,currency:"USD",features:["SLA","Dedicated success","Unlimited storefronts"]}]},async getSubscriptionStatus(){return await At(80),{isActive:!1}},async createSubscriptionCheckoutSession(e){return await At(200),e.successUrl?{kind:"redirect",url:e.successUrl}:{kind:"custom",data:e}}}}function td(e){return e.replace(/[_-]+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function Wh(e){return e?e.toUpperCase():"USD"}function Vh(e){if(e&&(e==="in_stock"||e==="low"||e==="out_of_stock"||e==="backorder"))return e}function qh(e){if(e&&(e==="physical"||e==="digital"))return e}function Hh(e){const t=[];if(Array.isArray(e))for(const r of e)typeof r=="string"&&t.push(r);else if(typeof e=="string"){const r=e.trim();if(r.startsWith("["))try{const s=JSON.parse(r);if(Array.isArray(s))for(const o of s)typeof o=="string"&&t.push(o);else t.push(e)}catch{t.push(e)}else t.push(e)}return t.flatMap(r=>r.split(",")).map(r=>r.trim().toUpperCase()).filter(Boolean)}function qr(e){const t=Wh(e.fiatCurrency),r=e.images&&e.images.length?e.images:e.imageUrl?[{url:e.imageUrl,alt:e.title}]:[],s=e.effectiveFiatAmountCents??e.fiatAmountCents??0,o=e.compareAtAmountCents,a=e.metadata?.shippingCountries??e.metadata?.shipping_countries,i=Hh(a);return{id:e.id,slug:e.slug??e.id,title:e.title??td(e.id),description:e.description??"",images:r,price:s/100,currency:t,tags:e.tags??[],categoryIds:e.categoryIds??[],inventoryStatus:Vh(e.inventoryStatus),inventoryQuantity:typeof e.inventoryQuantity=="number"?e.inventoryQuantity:void 0,compareAtPrice:typeof o=="number"?o/100:void 0,shippingProfile:qh(e.shippingProfile),checkoutRequirements:e.checkoutRequirements,fulfillment:e.fulfillment,attributes:i.length?{shippingCountries:i.join(",")}:void 0}}function Co(e){if(Array.isArray(e))return{products:e};const t=e.products??e.items??[],r=e.total??e.count;return{products:t,total:r}}async function tn(e,t,r){const s={};r&&(s["X-API-Key"]=r);const o=await fetch(`${e}${t}`,{headers:s});if(!o.ok){const a=await o.text().catch(()=>""),i=new Error(`Request failed (${o.status}): ${a}`);throw i.status=o.status,i}return o.json()}function Zh(e){return{listProducts:async l=>{const d=l.page??1,m=l.pageSize??24,u=m,p=(d-1)*m,h=new URLSearchParams;h.set("limit",String(u)),h.set("offset",String(p)),l.search&&h.set("search",l.search),l.category&&h.set("category",l.category),l.sort&&h.set("sort",l.sort),l.filters?.inStock&&h.set("in_stock","true"),l.filters?.minPrice!=null&&h.set("min_price",String(l.filters.minPrice)),l.filters?.maxPrice!=null&&h.set("max_price",String(l.filters.maxPrice));const _=l.filters?.tags,g=Array.isArray(_)?_:typeof _=="string"?[_]:[];g.length&&h.set("tags",g.join(","));const f=await tn(e.serverUrl,`/paywall/v1/products?${h.toString()}`,e.apiKey),{products:w,total:j}=Co(f);return{items:w.map(qr),page:d,pageSize:m,total:j,hasNextPage:typeof j=="number"?p+u<j:w.length===u}},getProductBySlug:async l=>{try{const d=await tn(e.serverUrl,`/paywall/v1/products/by-slug/${encodeURIComponent(l)}`,e.apiKey);return qr(d)}catch(d){const m=d?.status;if(m!==404&&m!==405)throw d;try{const u=await tn(e.serverUrl,`/paywall/v1/products/${encodeURIComponent(l)}`,e.apiKey);return qr(u)}catch(u){const p=u?.status;if(p!==404&&p!==405)throw u;const h=await tn(e.serverUrl,"/paywall/v1/products?limit=200&offset=0",e.apiKey),{products:_}=Co(h),g=_.find(f=>f.slug===l||f.id===l);return g?qr(g):null}}},listCategories:async()=>{const l=await tn(e.serverUrl,"/paywall/v1/products?limit=500&offset=0",e.apiKey),{products:d}=Co(l),m=new Set;for(const u of d)for(const p of u.categoryIds??[])m.add(p);return Array.from(m).map(u=>({id:u,slug:u,name:td(u)}))},getOrderHistory:async()=>[],createCheckoutSession:async l=>{throw new Error("createCheckoutSession is not implemented for paywall adapter")},getStorefrontSettings:async()=>{try{return(await tn(e.serverUrl,"/admin/config/storefront",e.apiKey)).config??null}catch{return null}},getPaymentMethodsConfig:async()=>{try{const[l,d,m]=await Promise.allSettled([tn(e.serverUrl,"/admin/config/stripe",e.apiKey),tn(e.serverUrl,"/admin/config/x402",e.apiKey),tn(e.serverUrl,"/admin/config/cedros_login",e.apiKey)]),u=l.status==="fulfilled"?!!l.value?.config?.enabled:!1,p=d.status==="fulfilled"?!!d.value?.config?.enabled:!1,h=m.status==="fulfilled"?!!m.value?.config?.enabled:!1;return{card:u,crypto:p,credits:h}}catch{return null}},getAIRelatedProducts:async l=>{const d={"Content-Type":"application/json"};e.apiKey&&(d["X-API-Key"]=e.apiKey);const m=await fetch(`${e.serverUrl}/admin/ai/related-products`,{method:"POST",headers:d,body:JSON.stringify(l)});if(!m.ok){const u=await m.text().catch(()=>"");throw new Error(`AI related products request failed (${m.status}): ${u}`)}return m.json()}}}function Gh(e){throw new Error(`Unhandled cart action: ${JSON.stringify(e)}`)}function Sn(e){return`${e.productId}::${e.variantId??""}`}const Qh={items:[]};function Yh(e,t){switch(t.type){case"cart/hydrate":return t.state;case"cart/add":{const r=Math.max(1,Math.floor(t.qty??1)),s=Sn(t.item);return e.items.find(a=>Sn(a)===s)?{...e,items:e.items.map(a=>Sn(a)===s?{...a,qty:a.qty+r}:a)}:{...e,items:[...e.items,{...t.item,qty:r}]}}case"cart/remove":{const r=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.filter(s=>Sn(s)!==r)}}case"cart/setQty":{const r=Math.max(0,Math.floor(t.qty)),s=`${t.productId}::${t.variantId??""}`;return r===0?{...e,items:e.items.filter(o=>Sn(o)!==s)}:{...e,items:e.items.map(o=>Sn(o)===s?{...o,qty:r}:o)}}case"cart/clear":return{items:[],promoCode:void 0};case"cart/setPromoCode":return{...e,promoCode:t.promoCode||void 0};case"cart/updateHold":{const r=`${t.productId}::${t.variantId??""}`;return{...e,items:e.items.map(s=>Sn(s)===r?{...s,holdId:t.holdId,holdExpiresAt:t.holdExpiresAt}:s)}}default:return Gh(t)}}function Kh(e){return e.reduce((t,r)=>t+r.qty,0)}function Xh(e){return e.reduce((t,r)=>t+r.qty*r.unitPrice,0)}function nc(){try{return typeof window>"u"?null:window.localStorage}catch{return null}}function Jh(e,t){try{const r=e.getItem(t);return r?JSON.parse(r):null}catch{return null}}function eg(e,t,r){try{e.setItem(t,JSON.stringify(r))}catch{}}const nd=y.createContext(null);function Dt(){const e=y.useContext(nd);if(!e)throw new Error("useCart must be used within CartProvider");return e}function tg({children:e}){const{config:t}=Re(),r=t.cart?.storageKey??"cedros_shop_cart_v1",s=t.customer?.id,o=t.customer?.isSignedIn??!!s,a=t.cart?.syncDebounceMs??800,i=!!t.adapter.getCartInventoryStatus,[c,l]=y.useReducer(Yh,Qh),[d,m]=y.useState(!1),u=y.useRef(!1),p=y.useRef(null);y.useEffect(()=>{const f=nc();if(!f)return;const w=Jh(f,r);w&&Array.isArray(w.items)&&l({type:"cart/hydrate",state:w}),m(!0)},[r]),y.useEffect(()=>{const f=nc();f&&eg(f,r,c)},[c,r]),y.useEffect(()=>{d&&(!o||!s||!t.adapter.mergeCart&&!t.adapter.getCart||u.current||(u.current=!0,(async()=>{try{const f=t.adapter.mergeCart?await t.adapter.mergeCart({customerId:s,cart:c}):await t.adapter.getCart({customerId:s});f&&Array.isArray(f.items)&&(l({type:"cart/hydrate",state:f}),p.current=JSON.stringify(f))}catch{}})()))},[t.adapter,s,d,o,c]),y.useEffect(()=>{if(!d||!o||!s||!t.adapter.updateCart||!u.current||typeof window>"u")return;const f=JSON.stringify(c);if(p.current===f)return;const w=window.setTimeout(()=>{t.adapter.updateCart({customerId:s,cart:c}).then(()=>{p.current=f}).catch(()=>{})},a);return()=>window.clearTimeout(w)},[t.adapter,s,d,o,c,a]);const h=y.useCallback((f,w)=>{const j=c.items.find(b=>b.productId===f&&b.variantId===w);if(j)return{holdId:j.holdId,expiresAt:j.holdExpiresAt}},[c.items]),_=y.useCallback((f,w,j)=>{l({type:"cart/updateHold",productId:f,variantId:w,holdExpiresAt:j})},[]),g=y.useMemo(()=>{const f=Kh(c.items),w=Xh(c.items);return{items:c.items,promoCode:c.promoCode,count:f,subtotal:w,addItem:(j,b)=>l({type:"cart/add",item:j,qty:b}),removeItem:(j,b)=>l({type:"cart/remove",productId:j,variantId:b}),setQty:(j,b,v)=>l({type:"cart/setQty",productId:j,variantId:b,qty:v}),clear:()=>l({type:"cart/clear"}),setPromoCode:j=>l({type:"cart/setPromoCode",promoCode:j}),holdsSupported:i,getItemHold:h,updateItemHold:_}},[c.items,c.promoCode,i,h,_]);return n.jsx(nd.Provider,{value:g,children:e})}function G(e,t,r){function s(c,l){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:l,constr:i,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,l);const d=i.prototype,m=Object.keys(d);for(let u=0;u<m.length;u++){const p=m[u];p in c||(c[p]=d[p].bind(c))}}const o=r?.Parent??Object;class a extends o{}Object.defineProperty(a,"name",{value:e});function i(c){var l;const d=r?.Parent?new a:this;s(d,c),(l=d._zod).deferred??(l.deferred=[]);for(const m of d._zod.deferred)m();return d}return Object.defineProperty(i,"init",{value:s}),Object.defineProperty(i,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class Kn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class rd extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const sd={};function An(e){return sd}function od(e){const t=Object.values(e).filter(s=>typeof s=="number");return Object.entries(e).filter(([s,o])=>t.indexOf(+s)===-1).map(([s,o])=>o)}function ea(e,t){return typeof t=="bigint"?t.toString():t}function Ma(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Da(e){return e==null}function La(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function ng(e,t){const r=(e.toString().split(".")[1]||"").length,s=t.toString();let o=(s.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(s)){const l=s.match(/\d?e-(\d?)/);l?.[1]&&(o=Number.parseInt(l[1]))}const a=r>o?r:o,i=Number.parseInt(e.toFixed(a).replace(".","")),c=Number.parseInt(t.toFixed(a).replace(".",""));return i%c/10**a}const rc=Symbol("evaluating");function Ce(e,t,r){let s;Object.defineProperty(e,t,{get(){if(s!==rc)return s===void 0&&(s=rc,s=r()),s},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function zn(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function yn(...e){const t={};for(const r of e){const s=Object.getOwnPropertyDescriptors(r);Object.assign(t,s)}return Object.defineProperties({},t)}function sc(e){return JSON.stringify(e)}function rg(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ad="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function gs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const sg=Ma(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Pr(e){if(gs(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const r=t.prototype;return!(gs(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function id(e){return Pr(e)?{...e}:Array.isArray(e)?[...e]:e}const og=new Set(["string","number","symbol"]);function Os(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function vn(e,t,r){const s=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(s._zod.parent=e),s}function me(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function ag(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const ig={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function cg(e,t){const r=e._zod.def,s=r.checks;if(s&&s.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const a=yn(e._zod.def,{get shape(){const i={};for(const c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(i[c]=r.shape[c])}return zn(this,"shape",i),i},checks:[]});return vn(e,a)}function lg(e,t){const r=e._zod.def,s=r.checks;if(s&&s.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const a=yn(e._zod.def,{get shape(){const i={...e._zod.def.shape};for(const c in t){if(!(c in r.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete i[c]}return zn(this,"shape",i),i},checks:[]});return vn(e,a)}function dg(e,t){if(!Pr(t))throw new Error("Invalid input to extend: expected a plain object");const r=e._zod.def.checks;if(r&&r.length>0){const a=e._zod.def.shape;for(const i in t)if(Object.getOwnPropertyDescriptor(a,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=yn(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return zn(this,"shape",a),a}});return vn(e,o)}function ug(e,t){if(!Pr(t))throw new Error("Invalid input to safeExtend: expected a plain object");const r=yn(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return zn(this,"shape",s),s}});return vn(e,r)}function mg(e,t){const r=yn(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t._zod.def.shape};return zn(this,"shape",s),s},get catchall(){return t._zod.def.catchall},checks:[]});return vn(e,r)}function pg(e,t,r){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const i=yn(t._zod.def,{get shape(){const c=t._zod.def.shape,l={...c};if(r)for(const d in r){if(!(d in c))throw new Error(`Unrecognized key: "${d}"`);r[d]&&(l[d]=e?new e({type:"optional",innerType:c[d]}):c[d])}else for(const d in c)l[d]=e?new e({type:"optional",innerType:c[d]}):c[d];return zn(this,"shape",l),l},checks:[]});return vn(t,i)}function fg(e,t,r){const s=yn(t._zod.def,{get shape(){const o=t._zod.def.shape,a={...o};if(r)for(const i in r){if(!(i in a))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(a[i]=new e({type:"nonoptional",innerType:o[i]}))}else for(const i in o)a[i]=new e({type:"nonoptional",innerType:o[i]});return zn(this,"shape",a),a}});return vn(t,s)}function Yn(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function cd(e,t){return t.map(r=>{var s;return(s=r).path??(s.path=[]),r.path.unshift(e),r})}function Hr(e){return typeof e=="string"?e:e?.message}function En(e,t,r){const s={...e,path:e.path??[]};if(!e.message){const o=Hr(e.inst?._zod.def?.error?.(e))??Hr(t?.error?.(e))??Hr(r.customError?.(e))??Hr(r.localeError?.(e))??"Invalid input";s.message=o}return delete s.inst,delete s.continue,t?.reportInput||delete s.input,s}function $a(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ar(...e){const[t,r,s]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:s}:{...t}}const ld=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ea,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},dd=G("$ZodError",ld),ud=G("$ZodError",ld,{Parent:Error});function hg(e,t=r=>r.message){const r={},s=[];for(const o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):s.push(t(o));return{formErrors:s,fieldErrors:r}}function gg(e,t=r=>r.message){const r={_errors:[]},s=o=>{for(const a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>s({issues:i}));else if(a.code==="invalid_key")s({issues:a.issues});else if(a.code==="invalid_element")s({issues:a.issues});else if(a.path.length===0)r._errors.push(t(a));else{let i=r,c=0;for(;c<a.path.length;){const l=a.path[c];c===a.path.length-1?(i[l]=i[l]||{_errors:[]},i[l]._errors.push(t(a))):i[l]=i[l]||{_errors:[]},i=i[l],c++}}};return s(e),r}const za=e=>(t,r,s,o)=>{const a=s?Object.assign(s,{async:!1}):{async:!1},i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise)throw new Kn;if(i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>En(l,a,An())));throw ad(c,o?.callee),c}return i.value},Fa=e=>async(t,r,s,o)=>{const a=s?Object.assign(s,{async:!0}):{async:!0};let i=t._zod.run({value:r,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const c=new(o?.Err??e)(i.issues.map(l=>En(l,a,An())));throw ad(c,o?.callee),c}return i.value},Ms=e=>(t,r,s)=>{const o=s?{...s,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},o);if(a instanceof Promise)throw new Kn;return a.issues.length?{success:!1,error:new(e??dd)(a.issues.map(i=>En(i,o,An())))}:{success:!0,data:a.value}},xg=Ms(ud),Ds=e=>async(t,r,s)=>{const o=s?Object.assign(s,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},o);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(i=>En(i,o,An())))}:{success:!0,data:a.value}},yg=Ds(ud),vg=e=>(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return za(e)(t,r,o)},bg=e=>(t,r,s)=>za(e)(t,r,s),wg=e=>async(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Fa(e)(t,r,o)},_g=e=>async(t,r,s)=>Fa(e)(t,r,s),jg=e=>(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Ms(e)(t,r,o)},kg=e=>(t,r,s)=>Ms(e)(t,r,s),Sg=e=>async(t,r,s)=>{const o=s?Object.assign(s,{direction:"backward"}):{direction:"backward"};return Ds(e)(t,r,o)},Cg=e=>async(t,r,s)=>Ds(e)(t,r,s),Ng=/^[cC][^\s-]{8,}$/,Pg=/^[0-9a-z]+$/,Ag=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Eg=/^[0-9a-vA-V]{20}$/,Tg=/^[A-Za-z0-9]{27}$/,Ig=/^[a-zA-Z0-9_-]{21}$/,Rg=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Og=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,oc=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Mg=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Dg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Lg(){return new RegExp(Dg,"u")}const $g=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,zg=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Fg=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Bg=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ug=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,md=/^[A-Za-z0-9_-]*$/,Wg=/^\+[1-9]\d{6,14}$/,pd="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Vg=new RegExp(`^${pd}$`);function fd(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function qg(e){return new RegExp(`^${fd(e)}$`)}function Hg(e){const t=fd({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const s=`${t}(?:${r.join("|")})`;return new RegExp(`^${pd}T(?:${s})$`)}const Zg=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Gg=/^-?\d+$/,Qg=/^-?\d+(?:\.\d+)?$/,Yg=/^[^A-Z]*$/,Kg=/^[^a-z]*$/,ht=G("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),hd={number:"number",bigint:"bigint",object:"date"},gd=G("$ZodCheckLessThan",(e,t)=>{ht.init(e,t);const r=hd[typeof t.value];e._zod.onattach.push(s=>{const o=s._zod.bag,a=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<a&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value<=t.value:s.value<t.value)||s.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),xd=G("$ZodCheckGreaterThan",(e,t)=>{ht.init(e,t);const r=hd[typeof t.value];e._zod.onattach.push(s=>{const o=s._zod.bag,a=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>a&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=s=>{(t.inclusive?s.value>=t.value:s.value>t.value)||s.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Xg=G("$ZodCheckMultipleOf",(e,t)=>{ht.init(e,t),e._zod.onattach.push(r=>{var s;(s=r._zod.bag).multipleOf??(s.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):ng(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Jg=G("$ZodCheckNumberFormat",(e,t)=>{ht.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),s=r?"int":"number",[o,a]=ig[t.format];e._zod.onattach.push(i=>{const c=i._zod.bag;c.format=t.format,c.minimum=o,c.maximum=a,r&&(c.pattern=Gg)}),e._zod.check=i=>{const c=i.value;if(r){if(!Number.isInteger(c)){i.issues.push({expected:s,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?i.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort}):i.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort});return}}c<o&&i.issues.push({origin:"number",input:c,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),c>a&&i.issues.push({origin:"number",input:c,code:"too_big",maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),ex=G("$ZodCheckMaxLength",(e,t)=>{var r;ht.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!Da(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(s._zod.bag.maximum=t.maximum)}),e._zod.check=s=>{const o=s.value;if(o.length<=t.maximum)return;const i=$a(o);s.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),tx=G("$ZodCheckMinLength",(e,t)=>{var r;ht.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!Da(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(s._zod.bag.minimum=t.minimum)}),e._zod.check=s=>{const o=s.value;if(o.length>=t.minimum)return;const i=$a(o);s.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),nx=G("$ZodCheckLengthEquals",(e,t)=>{var r;ht.init(e,t),(r=e._zod.def).when??(r.when=s=>{const o=s.value;return!Da(o)&&o.length!==void 0}),e._zod.onattach.push(s=>{const o=s._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=s=>{const o=s.value,a=o.length;if(a===t.length)return;const i=$a(o),c=a>t.length;s.issues.push({origin:i,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:s.value,inst:e,continue:!t.abort})}}),Ls=G("$ZodCheckStringFormat",(e,t)=>{var r,s;ht.init(e,t),e._zod.onattach.push(o=>{const a=o._zod.bag;a.format=t.format,t.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(s=e._zod).check??(s.check=()=>{})}),rx=G("$ZodCheckRegex",(e,t)=>{Ls.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),sx=G("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Yg),Ls.init(e,t)}),ox=G("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Kg),Ls.init(e,t)}),ax=G("$ZodCheckIncludes",(e,t)=>{ht.init(e,t);const r=Os(t.includes),s=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=s,e._zod.onattach.push(o=>{const a=o._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(s)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),ix=G("$ZodCheckStartsWith",(e,t)=>{ht.init(e,t);const r=new RegExp(`^${Os(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(s=>{const o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=s=>{s.value.startsWith(t.prefix)||s.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:s.value,inst:e,continue:!t.abort})}}),cx=G("$ZodCheckEndsWith",(e,t)=>{ht.init(e,t);const r=new RegExp(`.*${Os(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(s=>{const o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=s=>{s.value.endsWith(t.suffix)||s.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:s.value,inst:e,continue:!t.abort})}}),lx=G("$ZodCheckOverwrite",(e,t)=>{ht.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class dx{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const s=t.split(`
|
|
54
54
|
`).filter(i=>i),o=Math.min(...s.map(i=>i.length-i.trimStart().length)),a=s.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(const i of a)this.content.push(i)}compile(){const t=Function,r=this?.args,o=[...(this?.content??[""]).map(a=>` ${a}`)];return new t(...r,o.join(`
|
|
55
55
|
`))}}const ux={major:4,minor:3,patch:6},Ue=G("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ux;const s=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&s.unshift(e);for(const o of s)for(const a of o._zod.onattach)a(e);if(s.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(i,c,l)=>{let d=Yn(i),m;for(const u of c){if(u._zod.def.when){if(!u._zod.def.when(i))continue}else if(d)continue;const p=i.issues.length,h=u._zod.check(i);if(h instanceof Promise&&l?.async===!1)throw new Kn;if(m||h instanceof Promise)m=(m??Promise.resolve()).then(async()=>{await h,i.issues.length!==p&&(d||(d=Yn(i,p)))});else{if(i.issues.length===p)continue;d||(d=Yn(i,p))}}return m?m.then(()=>i):i},a=(i,c,l)=>{if(Yn(i))return i.aborted=!0,i;const d=o(c,s,l);if(d instanceof Promise){if(l.async===!1)throw new Kn;return d.then(m=>e._zod.parse(m,l))}return e._zod.parse(d,l)};e._zod.run=(i,c)=>{if(c.skipChecks)return e._zod.parse(i,c);if(c.direction==="backward"){const d=e._zod.parse({value:i.value,issues:[]},{...c,skipChecks:!0});return d instanceof Promise?d.then(m=>a(m,i,c)):a(d,i,c)}const l=e._zod.parse(i,c);if(l instanceof Promise){if(c.async===!1)throw new Kn;return l.then(d=>o(d,s,c))}return o(l,s,c)}}Ce(e,"~standard",()=>({validate:o=>{try{const a=xg(e,o);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return yg(e,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),Ba=G("$ZodString",(e,t)=>{Ue.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Zg(e._zod.bag),e._zod.parse=(r,s)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Te=G("$ZodStringFormat",(e,t)=>{Ls.init(e,t),Ba.init(e,t)}),mx=G("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Og),Te.init(e,t)}),px=G("$ZodUUID",(e,t)=>{if(t.version){const s={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(s===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=oc(s))}else t.pattern??(t.pattern=oc());Te.init(e,t)}),fx=G("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Mg),Te.init(e,t)}),hx=G("$ZodURL",(e,t)=>{Te.init(e,t),e._zod.check=r=>{try{const s=r.value.trim(),o=new URL(s);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=o.href:r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),gx=G("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Lg()),Te.init(e,t)}),xx=G("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Ig),Te.init(e,t)}),yx=G("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Ng),Te.init(e,t)}),vx=G("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Pg),Te.init(e,t)}),bx=G("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Ag),Te.init(e,t)}),wx=G("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Eg),Te.init(e,t)}),_x=G("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Tg),Te.init(e,t)}),jx=G("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Hg(t)),Te.init(e,t)}),kx=G("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Vg),Te.init(e,t)}),Sx=G("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=qg(t)),Te.init(e,t)}),Cx=G("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Rg),Te.init(e,t)}),Nx=G("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=$g),Te.init(e,t),e._zod.bag.format="ipv4"}),Px=G("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=zg),Te.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),Ax=G("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Fg),Te.init(e,t)}),Ex=G("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Bg),Te.init(e,t),e._zod.check=r=>{const s=r.value.split("/");try{if(s.length!==2)throw new Error;const[o,a]=s;if(!a)throw new Error;const i=Number(a);if(`${i}`!==a)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function yd(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const Tx=G("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Ug),Te.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{yd(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function Ix(e){if(!md.test(e))return!1;const t=e.replace(/[-_]/g,s=>s==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return yd(r)}const Rx=G("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=md),Te.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{Ix(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Ox=G("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Wg),Te.init(e,t)});function Mx(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[s]=r;if(!s)return!1;const o=JSON.parse(atob(s));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const Dx=G("$ZodJWT",(e,t)=>{Te.init(e,t),e._zod.check=r=>{Mx(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),vd=G("$ZodNumber",(e,t)=>{Ue.init(e,t),e._zod.pattern=e._zod.bag.pattern??Qg,e._zod.parse=(r,s)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;const a=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...a?{received:a}:{}}),r}}),Lx=G("$ZodNumberFormat",(e,t)=>{Jg.init(e,t),vd.init(e,t)}),$x=G("$ZodUnknown",(e,t)=>{Ue.init(e,t),e._zod.parse=r=>r}),zx=G("$ZodNever",(e,t)=>{Ue.init(e,t),e._zod.parse=(r,s)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function ac(e,t,r){e.issues.length&&t.issues.push(...cd(r,e.issues)),t.value[r]=e.value}const Fx=G("$ZodArray",(e,t)=>{Ue.init(e,t),e._zod.parse=(r,s)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);const a=[];for(let i=0;i<o.length;i++){const c=o[i],l=t.element._zod.run({value:c,issues:[]},s);l instanceof Promise?a.push(l.then(d=>ac(d,r,i))):ac(l,r,i)}return a.length?Promise.all(a).then(()=>r):r}});function xs(e,t,r,s,o){if(e.issues.length){if(o&&!(r in s))return;t.issues.push(...cd(r,e.issues))}e.value===void 0?r in s&&(t.value[r]=void 0):t.value[r]=e.value}function bd(e){const t=Object.keys(e.shape);for(const s of t)if(!e.shape?.[s]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${s}": expected a Zod schema`);const r=ag(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function wd(e,t,r,s,o,a){const i=[],c=o.keySet,l=o.catchall._zod,d=l.def.type,m=l.optout==="optional";for(const u in t){if(c.has(u))continue;if(d==="never"){i.push(u);continue}const p=l.run({value:t[u],issues:[]},s);p instanceof Promise?e.push(p.then(h=>xs(h,r,u,t,m))):xs(p,r,u,t,m)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:a}),e.length?Promise.all(e).then(()=>r):r}const Bx=G("$ZodObject",(e,t)=>{if(Ue.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const c=t.shape;Object.defineProperty(t,"shape",{get:()=>{const l={...c};return Object.defineProperty(t,"shape",{value:l}),l}})}const s=Ma(()=>bd(t));Ce(e._zod,"propValues",()=>{const c=t.shape,l={};for(const d in c){const m=c[d]._zod;if(m.values){l[d]??(l[d]=new Set);for(const u of m.values)l[d].add(u)}}return l});const o=gs,a=t.catchall;let i;e._zod.parse=(c,l)=>{i??(i=s.value);const d=c.value;if(!o(d))return c.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),c;c.value={};const m=[],u=i.shape;for(const p of i.keys){const h=u[p],_=h._zod.optout==="optional",g=h._zod.run({value:d[p],issues:[]},l);g instanceof Promise?m.push(g.then(f=>xs(f,c,p,d,_))):xs(g,c,p,d,_)}return a?wd(m,d,c,l,s.value,e):m.length?Promise.all(m).then(()=>c):c}}),Ux=G("$ZodObjectJIT",(e,t)=>{Bx.init(e,t);const r=e._zod.parse,s=Ma(()=>bd(t)),o=p=>{const h=new dx(["shape","payload","ctx"]),_=s.value,g=b=>{const v=sc(b);return`shape[${v}]._zod.run({ value: input[${v}], issues: [] }, ctx)`};h.write("const input = payload.value;");const f=Object.create(null);let w=0;for(const b of _.keys)f[b]=`key_${w++}`;h.write("const newResult = {};");for(const b of _.keys){const v=f[b],k=sc(b),N=p[b]?._zod?.optout==="optional";h.write(`const ${v} = ${g(b)};`),N?h.write(`
|
|
56
56
|
if (${v}.issues.length) {
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-Dhf-hhsE.js");require("react/jsx-runtime");require("react");const t=require("./CedrosContext-C2v_s8cc.js");require("@solana/web3.js");require("./index-WcOlBYZJ.js");require("@solana/wallet-adapter-react");exports.CEDROS_EVENTS=e.CEDROS_EVENTS;exports.CSP_PRESETS=e.CSP_PRESETS;exports.CedrosPay=e.CedrosPay;exports.CedrosPayAdminDashboard=e.CedrosPayAdminDashboard;exports.CreditsButton=e.CreditsButton;exports.CreditsSubscribeButton=e.CreditsSubscribeButton;exports.ERROR_CATEGORIES=e.ERROR_CATEGORIES;exports.PaymentMethodBadge=e.PaymentMethodBadge;exports.PaymentModal=e.PaymentModal;exports.ProductPrice=e.ProductPrice;exports.PurchaseButton=e.PurchaseButton;exports.RPC_PROVIDERS=e.RPC_PROVIDERS;exports.SECURITY_RECOMMENDATIONS=e.SECURITY_RECOMMENDATIONS;exports.StripeButton=e.StripeButton;exports.SubscribeButton=e.SubscribeButton;exports.SubscriptionManagementPanel=e.SubscriptionManagementPanel;exports.calculateDiscountPercentage=e.calculateDiscountPercentage;exports.cedrosPayPlugin=e.cedrosPayPlugin;exports.createTranslator=e.createTranslator;exports.detectLocale=e.detectLocale;exports.ecommerce=e.index;exports.emitPaymentError=e.emitPaymentError;exports.emitPaymentProcessing=e.emitPaymentProcessing;exports.emitPaymentStart=e.emitPaymentStart;exports.emitPaymentSuccess=e.emitPaymentSuccess;exports.emitWalletConnect=e.emitWalletConnect;exports.emitWalletConnected=e.emitWalletConnected;exports.emitWalletError=e.emitWalletError;exports.formatCSP=e.formatCSP;exports.formatCouponCodes=e.formatCouponCodes;exports.generateCSP=e.generateCSP;exports.generateCSPDirectives=e.generateCSPDirectives;exports.getAvailableLocales=e.getAvailableLocales;exports.getLocalizedError=e.getLocalizedError;exports.getUserErrorMessage=e.getUserErrorMessage;exports.isRetryableError=e.isRetryableError;exports.loadLocale=e.loadLocale;exports.logSecurityReport=e.logSecurityReport;exports.parseCouponCodes=e.parseCouponCodes;exports.stackCheckoutCoupons=e.stackCheckoutCoupons;exports.useCreditsPayment=e.useCreditsPayment;exports.useCreditsSubscription=e.useCreditsSubscription;exports.useLocalizedError=e.useLocalizedError;exports.usePaymentMode=e.usePaymentMode;exports.useStripeCheckout=e.useStripeCheckout;exports.useSubscription=e.useSubscription;exports.useSubscriptionManagement=e.useSubscriptionManagement;exports.useTranslation=e.useTranslation;exports.validateSecurity=e.validateSecurity;exports.CIRCUIT_BREAKER_PRESETS=t.CIRCUIT_BREAKER_PRESETS;exports.CedrosProvider=t.CedrosProvider;exports.CircuitBreakerOpenError=t.CircuitBreakerOpenError;exports.CircuitState=t.CircuitState;exports.LogLevel=t.LogLevel;exports.Logger=t.Logger;exports.RATE_LIMITER_PRESETS=t.RATE_LIMITER_PRESETS;exports.RETRY_PRESETS=t.RETRY_PRESETS;exports.createCircuitBreaker=t.createCircuitBreaker;exports.createLogger=t.createLogger;exports.createRateLimiter=t.createRateLimiter;exports.getLogger=t.getLogger;exports.retryWithBackoff=t.retryWithBackoff;exports.useCedrosContext=t.useCedrosContext;exports.useCedrosTheme=t.useCedrosTheme;exports.validateConfig=t.validateConfig;
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { x as c, w as n, C as u, a as C, b as m, h as S, E, f as P, d, e as l, P as R, R as g, L as p, S as y, g as T, i as L, q as b, c as B, Q as M, M as _, W as f, G as h, D as I, y as v, F as O, z as k, A, B as D, v as W, o as x, r as N, t as U, O as z, T as V, I as j, H as G, N as K, K as Y, p as q, s as w, j as F, m as H, V as J, k as Q, u as X, l as Z, n as $, U as ee, J as ae } from "./index-
|
|
1
|
+
import { x as c, w as n, C as u, a as C, b as m, h as S, E, f as P, d, e as l, P as R, R as g, L as p, S as y, g as T, i as L, q as b, c as B, Q as M, M as _, W as f, G as h, D as I, y as v, F as O, z as k, A, B as D, v as W, o as x, r as N, t as U, O as z, T as V, I as j, H as G, N as K, K as Y, p as q, s as w, j as F, m as H, V as J, k as Q, u as X, l as Z, n as $, U as ee, J as ae } from "./index-9OMDKaoz.mjs";
|
|
2
2
|
import "react/jsx-runtime";
|
|
3
3
|
import "react";
|
|
4
4
|
import { f as te, C as re, e as oe, d as ie, L as ce, h as ne, R as ue, g as Ce, b as me, j as Se, c as Ee, i as Pe, r as de, u as le, a as Re, v as ge } from "./CedrosContext-D7nh5-Zh.mjs";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("react/jsx-runtime");require("react");const e=require("./index-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("react/jsx-runtime");require("react");const e=require("./index-Dhf-hhsE.js");exports.CouponsSection=e.CouponsSection;exports.ProductsSection=e.ProductsSection;exports.RefundsSection=e.RefundsSection;exports.SettingsSection=e.SettingsSection;exports.TransactionsSection=e.TransactionsSection;
|
package/dist/stripe-only.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-Dhf-hhsE.js");require("react/jsx-runtime");require("react");const t=require("./CedrosContext-C2v_s8cc.js");require("@solana/web3.js");require("./index-WcOlBYZJ.js");require("@solana/wallet-adapter-react");exports.CEDROS_EVENTS=e.CEDROS_EVENTS;exports.CSP_PRESETS=e.CSP_PRESETS;exports.CedrosPay=e.CedrosPay;exports.CedrosPayAdminDashboard=e.CedrosPayAdminDashboard;exports.CreditsButton=e.CreditsButton;exports.CreditsSubscribeButton=e.CreditsSubscribeButton;exports.ERROR_CATEGORIES=e.ERROR_CATEGORIES;exports.PaymentMethodBadge=e.PaymentMethodBadge;exports.PaymentModal=e.PaymentModal;exports.ProductPrice=e.ProductPrice;exports.PurchaseButton=e.PurchaseButton;exports.RPC_PROVIDERS=e.RPC_PROVIDERS;exports.SECURITY_RECOMMENDATIONS=e.SECURITY_RECOMMENDATIONS;exports.StripeButton=e.StripeButton;exports.SubscribeButton=e.SubscribeButton;exports.SubscriptionManagementPanel=e.SubscriptionManagementPanel;exports.calculateDiscountPercentage=e.calculateDiscountPercentage;exports.cedrosPayPlugin=e.cedrosPayPlugin;exports.createTranslator=e.createTranslator;exports.detectLocale=e.detectLocale;exports.ecommerce=e.index;exports.emitPaymentError=e.emitPaymentError;exports.emitPaymentProcessing=e.emitPaymentProcessing;exports.emitPaymentStart=e.emitPaymentStart;exports.emitPaymentSuccess=e.emitPaymentSuccess;exports.emitWalletConnect=e.emitWalletConnect;exports.emitWalletConnected=e.emitWalletConnected;exports.emitWalletError=e.emitWalletError;exports.formatCSP=e.formatCSP;exports.formatCouponCodes=e.formatCouponCodes;exports.generateCSP=e.generateCSP;exports.generateCSPDirectives=e.generateCSPDirectives;exports.getAvailableLocales=e.getAvailableLocales;exports.getLocalizedError=e.getLocalizedError;exports.getUserErrorMessage=e.getUserErrorMessage;exports.isRetryableError=e.isRetryableError;exports.loadLocale=e.loadLocale;exports.logSecurityReport=e.logSecurityReport;exports.parseCouponCodes=e.parseCouponCodes;exports.stackCheckoutCoupons=e.stackCheckoutCoupons;exports.useCreditsPayment=e.useCreditsPayment;exports.useCreditsSubscription=e.useCreditsSubscription;exports.useLocalizedError=e.useLocalizedError;exports.usePaymentMode=e.usePaymentMode;exports.useStripeCheckout=e.useStripeCheckout;exports.useSubscription=e.useSubscription;exports.useSubscriptionManagement=e.useSubscriptionManagement;exports.useTranslation=e.useTranslation;exports.validateSecurity=e.validateSecurity;exports.CIRCUIT_BREAKER_PRESETS=t.CIRCUIT_BREAKER_PRESETS;exports.CedrosProvider=t.CedrosProvider;exports.CircuitBreakerOpenError=t.CircuitBreakerOpenError;exports.CircuitState=t.CircuitState;exports.LogLevel=t.LogLevel;exports.Logger=t.Logger;exports.RATE_LIMITER_PRESETS=t.RATE_LIMITER_PRESETS;exports.RETRY_PRESETS=t.RETRY_PRESETS;exports.createCircuitBreaker=t.createCircuitBreaker;exports.createLogger=t.createLogger;exports.createRateLimiter=t.createRateLimiter;exports.getLogger=t.getLogger;exports.retryWithBackoff=t.retryWithBackoff;exports.useCedrosContext=t.useCedrosContext;exports.useCedrosTheme=t.useCedrosTheme;exports.validateConfig=t.validateConfig;
|
package/dist/stripe-only.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { x as c, w as n, C as u, a as C, b as m, h as S, E, f as P, d, e as l, P as R, R as g, L as p, S as y, g as T, i as L, q as b, c as B, Q as M, M as _, W as f, G as h, D as I, y as v, F as O, z as k, A, B as D, v as W, o as x, r as N, t as U, O as z, T as V, I as j, H as G, N as K, K as Y, p as q, s as w, j as F, m as H, V as J, k as Q, u as X, l as Z, n as $, U as ee, J as ae } from "./index-
|
|
1
|
+
import { x as c, w as n, C as u, a as C, b as m, h as S, E, f as P, d, e as l, P as R, R as g, L as p, S as y, g as T, i as L, q as b, c as B, Q as M, M as _, W as f, G as h, D as I, y as v, F as O, z as k, A, B as D, v as W, o as x, r as N, t as U, O as z, T as V, I as j, H as G, N as K, K as Y, p as q, s as w, j as F, m as H, V as J, k as Q, u as X, l as Z, n as $, U as ee, J as ae } from "./index-9OMDKaoz.mjs";
|
|
2
2
|
import "react/jsx-runtime";
|
|
3
3
|
import "react";
|
|
4
4
|
import { f as te, C as re, e as oe, d as ie, L as ce, h as ne, R as ue, g as Ce, b as me, j as Se, c as Ee, i as Pe, r as de, u as le, a as Re, v as ge } from "./CedrosContext-D7nh5-Zh.mjs";
|
package/package.json
CHANGED