@payconductor/react 1.2.5 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var ge=Object.defineProperty;var we=(e,a,t)=>a in e?ge(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t;var P=(e,a,t)=>we(e,typeof a!="symbol"?a+"":a,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const k=require("react/jsx-runtime"),I=require("react"),Se="https://app.payconductor.ai",pe="http://localhost:3000",V="https://iframe.payconductor.ai/v1",$="http://localhost:5175/v1",Pe=3e5,Ce="600px";var q=(e=>(e.Pix="Pix",e.CreditCard="CreditCard",e.DebitCard="DebitCard",e.BankSlip="BankSlip",e.Crypto="Crypto",e.ApplePay="ApplePay",e.NuPay="NuPay",e.PicPay="PicPay",e.AmazonPay="AmazonPay",e.SepaDebit="SepaDebit",e.GooglePay="GooglePay",e))(q||{}),W=(e=>(e.Grid="grid",e.Vertical="vertical",e.Horizontal="horizontal",e))(W||{}),J=(e=>(e.Succeeded="succeeded",e.Pending="pending",e.Failed="failed",e))(J||{}),X=(e=>(e.ThreeDsAwaitingChallenge="ThreeDsAwaitingChallenge",e))(X||{}),Z=(e=>(e.Authenticated="Authenticated",e.NotAuthenticated="NotAuthenticated",e.NeedChallenge="NeedChallenge",e))(Z||{}),Q=(e=>(e.Pending="Pending",e.Authenticated="Authenticated",e.Failed="Failed",e.NotEnrolled="NotEnrolled",e))(Q||{}),j=(e=>(e.Cpf="Cpf",e.Cnpj="Cnpj",e))(j||{}),v=(e=>(e.Asaas="Asaas",e.Sandbox="Sandbox",e.SandboxSplit="SandboxSplit",e.MercadoPago="MercadoPago",e.NuPay="NuPay",e.PicPay="PicPay",e.Woovi="Woovi",e.EfiBank="EfiBank",e.BrasPag="BrasPag",e.PagarMe="PagarMe",e.BancoDoBrasil="BancoDoBrasil",e.PagSeguro="PagSeguro",e.Ebanx="Ebanx",e.OnlyUp="OnlyUp",e.Barte="Barte",e.BarteSplit="BarteSplit",e.PagSmileA55="PagSmileA55",e.Avantti="Avantti",e.MonsterGateway="MonsterGateway",e.SAC="SAC",e.Lyra="Lyra",e))(v||{}),ee=(e=>(e.Visa="Visa",e.Mastercard="Mastercard",e.AmericanExpress="AmericanExpress",e.DinersClub="DinersClub",e.Discover="Discover",e.JCB="JCB",e.UnionPay="UnionPay",e.Maestro="Maestro",e.Mir="Mir",e.Elo="Elo",e.Hiper="Hiper",e.Hipercard="Hipercard",e.Verve="Verve",e.Unknown="Unknown",e))(ee||{}),x=(e=>(e.Production="Production",e.Sandbox="Sandbox",e))(x||{}),te=(e=>(e.USD="USD",e.EUR="EUR",e.BRL="BRL",e.ARS="ARS",e.CAD="CAD",e.COP="COP",e.GBP="GBP",e.JPY="JPY",e.MXN="MXN",e.MZN="MZN",e.CNY="CNY",e.SAR="SAR",e.ETH="ETH",e.BNB="BNB",e.BTC="BTC",e.USDT="USDT",e.USDC="USDC",e.DOGE="DOGE",e.SOL="SOL",e))(te||{}),ne=(e=>(e.Android="android",e.IOS="ios",e.Web="web",e.Chrome="chrome",e.Safari="safari",e))(ne||{}),ae=(e=>(e.Padding="padding",e.Radius="radius",e.Color="color",e.Background="background",e.Shadow="shadow",e))(ae||{}),M=(e=>(e.Init="Init",e.Config="Config",e.Update="Update",e.ConfirmPayment="ConfirmPayment",e.Validate="Validate",e.Reset="Reset",e))(M||{}),T=(e=>(e.Ready="Ready",e.Error="Error",e.CheckoutSessionCreated="CheckoutSessionCreated",e.PaymentComplete="PaymentComplete",e.PaymentFailed="PaymentFailed",e.PaymentPending="PaymentPending",e.ValidationError="ValidationError",e.PaymentMethodSelected="PaymentMethodSelected",e.Resize="Resize",e.ThreeDSChallenge="ThreeDSChallenge",e.ThreeDSComplete="ThreeDSComplete",e.ThreeDSFailed="ThreeDSFailed",e))(T||{}),ie=(e=>(e.InvalidClient="InvalidClient",e.InvalidToken="InvalidToken",e.NetworkError="NetworkError",e.IframeNotReady="IframeNotReady",e.PaymentDeclined="PaymentDeclined",e.ValidationError="ValidationError",e.Timeout="Timeout",e))(ie||{});const be={primaryColor:"#0066ff",secondaryColor:"#5a6b7c",backgroundColor:"transparent",surfaceColor:"#f8fafc",textColor:"#0f172a",textSecondaryColor:"#64748b",errorColor:"#ef4444",successColor:"#22c55e",warningColor:"#f59e0b",borderColor:"#e2e8f0",disabledColor:"#cbd5e1",fontFamily:'"Poppins", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',fontSize:{xs:"0.75rem",sm:"0.875rem",md:"1rem",lg:"1.125rem",xl:"1.25rem"},fontWeight:{normal:400,medium:500,bold:600},lineHeight:"1.5",spacing:{xs:"4px",sm:"8px",md:"16px",lg:"24px",xl:"32px"},borderRadius:"8px",borderWidth:"1px",boxShadow:"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",boxShadowHover:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",inputBackground:"#ffffff",inputBorderColor:"#cbd5e1",inputBorderRadius:"8px",inputHeight:"44px",inputPadding:"12px 16px",buttonHeight:"48px",buttonPadding:"16px 24px",buttonBorderRadius:"8px",transitionDuration:"0.2s",transitionTimingFunction:"ease"},re=typeof window<"u"&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1")&&!window.location.search.includes("production"),oe=re?$:V,_=`${re?pe:Se}/api/v1/sdk`,se=[$,V],B=Ce,de=Pe,S={INIT:M.Init,CONFIG:M.Config,UPDATE:M.Update,CONFIRM_PAYMENT:M.ConfirmPayment,VALIDATE:M.Validate,RESET:M.Reset,READY:T.Ready,ERROR:T.Error,PAYMENT_COMPLETE:T.PaymentComplete,PAYMENT_FAILED:T.PaymentFailed,PAYMENT_PENDING:T.PaymentPending,VALIDATION_ERROR:T.ValidationError,PAYMENT_METHOD_SELECTED:T.PaymentMethodSelected,RESIZE:T.Resize},Te={INVALID_CLIENT:"InvalidClient",INVALID_TOKEN:"InvalidToken",NETWORK_ERROR:"NetworkError",IFRAME_NOT_READY:"IframeNotReady",PAYMENT_DECLINED:"PaymentDeclined",VALIDATION_ERROR:"ValidationError",TIMEOUT:"Timeout"},K="payconductor-skeleton-style",ce=`
1
+ "use strict";var Se=Object.defineProperty;var Pe=(e,a,t)=>a in e?Se(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t;var C=(e,a,t)=>Pe(e,typeof a!="symbol"?a+"":a,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const k=require("react/jsx-runtime"),v=require("react"),Ce="https://app.payconductor.ai",be="http://localhost:3000",W="https://iframe.payconductor.ai/v1",J="http://localhost:5175/v1",Te=3e5,Ae="600px";var X=(e=>(e.Pix="Pix",e.CreditCard="CreditCard",e.DebitCard="DebitCard",e.BankSlip="BankSlip",e.Crypto="Crypto",e.ApplePay="ApplePay",e.NuPay="NuPay",e.PicPay="PicPay",e.AmazonPay="AmazonPay",e.SepaDebit="SepaDebit",e.GooglePay="GooglePay",e))(X||{}),Z=(e=>(e.Grid="grid",e.Vertical="vertical",e.Horizontal="horizontal",e))(Z||{}),_=(e=>(e.Succeeded="succeeded",e.Pending="pending",e.Failed="failed",e))(_||{}),U=(e=>(e.ThreeDsAwaitingChallenge="ThreeDsAwaitingChallenge",e))(U||{}),Q=(e=>(e.Authenticated="Authenticated",e.NotAuthenticated="NotAuthenticated",e.NeedChallenge="NeedChallenge",e))(Q||{}),ee=(e=>(e.Pending="Pending",e.Authenticated="Authenticated",e.Failed="Failed",e.NotEnrolled="NotEnrolled",e))(ee||{}),$=(e=>(e.Cpf="Cpf",e.Cnpj="Cnpj",e))($||{}),I=(e=>(e.Asaas="Asaas",e.Sandbox="Sandbox",e.SandboxSplit="SandboxSplit",e.MercadoPago="MercadoPago",e.NuPay="NuPay",e.PicPay="PicPay",e.Woovi="Woovi",e.EfiBank="EfiBank",e.BrasPag="BrasPag",e.PagarMe="PagarMe",e.BancoDoBrasil="BancoDoBrasil",e.PagSeguro="PagSeguro",e.Ebanx="Ebanx",e.OnlyUp="OnlyUp",e.Barte="Barte",e.BarteSplit="BarteSplit",e.PagSmileA55="PagSmileA55",e.Avantti="Avantti",e.MonsterGateway="MonsterGateway",e.SAC="SAC",e.Lyra="Lyra",e))(I||{}),te=(e=>(e.Visa="Visa",e.Mastercard="Mastercard",e.AmericanExpress="AmericanExpress",e.DinersClub="DinersClub",e.Discover="Discover",e.JCB="JCB",e.UnionPay="UnionPay",e.Maestro="Maestro",e.Mir="Mir",e.Elo="Elo",e.Hiper="Hiper",e.Hipercard="Hipercard",e.Verve="Verve",e.Unknown="Unknown",e))(te||{}),x=(e=>(e.Production="Production",e.Sandbox="Sandbox",e))(x||{}),ae=(e=>(e.USD="USD",e.EUR="EUR",e.BRL="BRL",e.ARS="ARS",e.CAD="CAD",e.COP="COP",e.GBP="GBP",e.JPY="JPY",e.MXN="MXN",e.MZN="MZN",e.CNY="CNY",e.SAR="SAR",e.ETH="ETH",e.BNB="BNB",e.BTC="BTC",e.USDT="USDT",e.USDC="USDC",e.DOGE="DOGE",e.SOL="SOL",e))(ae||{}),ne=(e=>(e.Android="android",e.IOS="ios",e.Web="web",e.Chrome="chrome",e.Safari="safari",e))(ne||{}),re=(e=>(e.Padding="padding",e.Radius="radius",e.Color="color",e.Background="background",e.Shadow="shadow",e))(re||{}),D=(e=>(e.Init="Init",e.Config="Config",e.Update="Update",e.ConfirmPayment="ConfirmPayment",e.Validate="Validate",e.Reset="Reset",e))(D||{}),A=(e=>(e.Ready="Ready",e.Error="Error",e.CheckoutSessionCreated="CheckoutSessionCreated",e.PaymentComplete="PaymentComplete",e.PaymentFailed="PaymentFailed",e.PaymentPending="PaymentPending",e.ValidationError="ValidationError",e.PaymentMethodSelected="PaymentMethodSelected",e.Resize="Resize",e.ThreeDSChallenge="ThreeDSChallenge",e.ThreeDSComplete="ThreeDSComplete",e.ThreeDSFailed="ThreeDSFailed",e))(A||{}),ie=(e=>(e.InvalidClient="InvalidClient",e.InvalidToken="InvalidToken",e.NetworkError="NetworkError",e.IframeNotReady="IframeNotReady",e.PaymentDeclined="PaymentDeclined",e.ValidationError="ValidationError",e.Timeout="Timeout",e))(ie||{});const pe={primaryColor:"#0066ff",secondaryColor:"#5a6b7c",backgroundColor:"transparent",surfaceColor:"#f8fafc",textColor:"#0f172a",textSecondaryColor:"#64748b",errorColor:"#ef4444",successColor:"#22c55e",warningColor:"#f59e0b",borderColor:"#e2e8f0",disabledColor:"#cbd5e1",fontFamily:'"Poppins", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',fontSize:{xs:"0.75rem",sm:"0.875rem",md:"1rem",lg:"1.125rem",xl:"1.25rem"},fontWeight:{normal:400,medium:500,bold:600},lineHeight:"1.5",spacing:{xs:"4px",sm:"8px",md:"16px",lg:"24px",xl:"32px"},borderRadius:"8px",borderWidth:"1px",boxShadow:"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",boxShadowHover:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",inputBackground:"#ffffff",inputBorderColor:"#cbd5e1",inputBorderRadius:"8px",inputHeight:"44px",inputPadding:"12px 16px",buttonHeight:"48px",buttonPadding:"16px 24px",buttonBorderRadius:"8px",transitionDuration:"0.2s",transitionTimingFunction:"ease"},oe=window.location.search.includes("development"),se=oe?J:W,M=`${oe?be:Ce}/api/v1/sdk`,de=[J,W],j=Ae,ce=Te,w={INIT:D.Init,CONFIG:D.Config,UPDATE:D.Update,CONFIRM_PAYMENT:D.ConfirmPayment,VALIDATE:D.Validate,RESET:D.Reset,READY:A.Ready,ERROR:A.Error,PAYMENT_COMPLETE:A.PaymentComplete,PAYMENT_FAILED:A.PaymentFailed,PAYMENT_PENDING:A.PaymentPending,VALIDATION_ERROR:A.ValidationError,PAYMENT_METHOD_SELECTED:A.PaymentMethodSelected,RESIZE:A.Resize},ve={INVALID_CLIENT:"InvalidClient",INVALID_TOKEN:"InvalidToken",NETWORK_ERROR:"NetworkError",IFRAME_NOT_READY:"IframeNotReady",PAYMENT_DECLINED:"PaymentDeclined",VALIDATION_ERROR:"ValidationError",TIMEOUT:"Timeout"},H="payconductor-skeleton-style",le=`
2
2
  @keyframes payconductor-shimmer {
3
3
  0% { background-position: -200% 0; }
4
4
  100% { background-position: 200% 0; }
@@ -10,7 +10,7 @@
10
10
  border-radius: 4px;
11
11
  width: 100%;
12
12
  }
13
- `;function le(e){const a=new URLSearchParams({publicKey:e.publicKey});return`${oe}?${a.toString()}`}function ue(){return crypto.randomUUID()}function he(e,a){return a.some(t=>{try{return new URL(t).origin===e}catch{return t===e}})}function z(){return new Map}function R(e,a,t,n){return new Promise((i,r)=>{if(!e||!("contentWindow"in e)){r(new Error("Iframe not defined"));return}if(!(e!=null&&e.contentWindow)){r(new Error("Iframe not ready"));return}if(!a){r(new Error("Pending requests not initialized"));return}const s=ue();a.set(s,{resolve:i,reject:r}),e.contentWindow.postMessage({type:t,data:n,requestId:s},"*"),setTimeout(()=>{a!=null&&a.has(s)&&(a.delete(s),r(new Error("Request timeout")))},de)})}function Ae(e,a,t){return R(e,a,S.CONFIRM_PAYMENT,t)}async function Ie(e,a,t){return await Ae(e,a,{orderId:t.orderId})}function ve(e,a,t){return R(e,a,S.VALIDATE,t)}function Me(e,a){return R(e,a,S.RESET)}function _e(e,a,t){return R(e,a,S.CONFIG,t)}function De(e,a,t){return R(e,a,S.INIT,t)}function xe(e,a,t,n,i,r,s,d,o,c,w,E){const m=e.data,{requestId:f,type:u,data:g,error:b}=m;if(u===S.READY){if(n==null||n(),f&&(a!=null&&a.has(f))){const{resolve:A}=a.get(f);a.delete(f),A(g)}return}if(he(e.origin,se)){if(f&&a&&a.has(f)){const{resolve:A,reject:O}=a.get(f);a.delete(f),b?O(new Error(String(b.message))):A(g);return}if(u===S.ERROR){t((b==null?void 0:b.message)||"Unknown error"),i==null||i(new Error(String(b==null?void 0:b.message)));return}if(u===S.PAYMENT_COMPLETE){g&&typeof g=="object"&&"status"in g&&(r==null||r(g));return}if(u===S.PAYMENT_FAILED){g&&typeof g=="object"&&"status"in g&&(s==null||s(g));return}if(u===S.PAYMENT_PENDING){g&&typeof g=="object"&&"status"in g&&(d==null||d(g));return}if(u===S.PAYMENT_METHOD_SELECTED){g&&typeof g=="object"&&"paymentMethod"in g&&(o==null||o(g.paymentMethod));return}if(u!==S.RESIZE){if(u===T.ThreeDSChallenge){c==null||c();return}if(u===T.ThreeDSComplete){w==null||w();return}if(u===T.ThreeDSFailed){E==null||E();return}}}}function me(e){const[a,t]=I.useState(()=>!1),[n,i]=I.useState(()=>null),[r,s]=I.useState(()=>""),[d,o]=I.useState(()=>null);return I.useEffect(()=>{const c=(...h)=>{e.debug&&console.log("[PayConductor]",...h)},w=le({publicKey:e.publicKey});s(w),t(!0);const E=z();let m=!1;c("init",e.publicKey),c("iframeUrl",w);const f=()=>{var C,l;const h=(l=(C=window.PayConductor)==null?void 0:C.frame)==null?void 0:l.iframe;if(h){if(h instanceof HTMLIFrameElement)return h;if(typeof h=="object"&&h!==null){const y=h;if("current"in y&&y.current instanceof HTMLIFrameElement)return y.current;if("value"in y&&y.value instanceof HTMLIFrameElement)return y.value}return h}return document.querySelector(".payconductor-element iframe")??void 0},u={get iframe(){return document.querySelector(".payconductor-element iframe")??null},set iframe(h){},iframeUrl:w,error:null},g={publicKey:e.publicKey,theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod},b={confirmPayment:h=>{var l;c("→ CONFIRM_PAYMENT",{orderId:h.orderId});const C=f();return C!=null&&C.contentWindow&&C.contentWindow.postMessage({type:S.CONFIG,data:{publicKey:e.publicKey,orderId:h.orderId,theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod,showPaymentButtons:e.showPaymentButtons,nuPayConfig:e.nuPayConfig}},"*"),g.orderId=h.orderId,(l=window.PayConductor)!=null&&l.config&&(window.PayConductor.config.orderId=h.orderId),Ie(C,E,h)},validate:h=>(c("→ VALIDATE",h),ve(f(),E,h)),reset:()=>(c("→ RESET"),Me(f(),E)),getSelectedPaymentMethod:()=>d};window.PayConductor={frame:u,config:g,api:b,selectedPaymentMethod:d},c("registered"),window.dispatchEvent(new CustomEvent("payconductor:registered",{detail:window.PayConductor}));const A=async()=>{if(!m){const h=f();if(!h){c("→ CONFIG skipped: iframe not found");return}m=!0,c("→ CONFIG",{theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod,showPaymentButtons:e.showPaymentButtons}),_e(h,E,{theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod,showPaymentButtons:e.showPaymentButtons,nuPayConfig:e.nuPayConfig})}},O=h=>{var C;(C=h.data)!=null&&C.type&&c("←",h.data.type,h.data.data??""),xe(h,E,l=>{var y;i(l),u.error=l,(y=window.PayConductor)!=null&&y.frame&&(window.PayConductor.frame.error=l)},()=>{var l;(l=e.onReady)==null||l.call(e),A()},l=>{var y;(y=e.onError)==null||y.call(e,l)},l=>{var y;(y=e.onPaymentComplete)==null||y.call(e,l)},l=>{var y;(y=e.onPaymentFailed)==null||y.call(e,l)},l=>{var y;(y=e.onPaymentPending)==null||y.call(e,l)},l=>{var y;o(l),window.PayConductor&&(window.PayConductor.selectedPaymentMethod=l),(y=e.onPaymentMethodSelected)==null||y.call(e,l)},()=>{var l;(l=e.onThreeDSChallenge)==null||l.call(e)},()=>{var l;(l=e.onThreeDSComplete)==null||l.call(e)},()=>{var l;(l=e.onThreeDSFailed)==null||l.call(e)})};window.addEventListener("message",O);const Ee=()=>{var C,l,y;const h=f();if(!h)return!1;try{if((((C=h.contentDocument)==null?void 0:C.readyState)??((y=(l=h.contentWindow)==null?void 0:l.document)==null?void 0:y.readyState))==="complete")return A(),!0}catch{}return!1},H=()=>{if(Ee())return;const h=f();if(h){h.addEventListener("load",()=>A(),{once:!0});return}setTimeout(H,50)};H()},[]),k.jsx("div",{className:"payconductor",id:"payconductor",style:{display:"contents"},children:e.children})}function Re(e){const a=I.useRef(null),[t,n]=I.useState(()=>""),[i,r]=I.useState(()=>!1),[s,d]=I.useState(()=>"");return I.useEffect(()=>{if(typeof document<"u"&&!document.getElementById(K)){const m=document.createElement("style");m.id=K,m.textContent=ce,document.head.appendChild(m)}const o=m=>{m!=null&&m.frame&&(n(m.frame.iframeUrl||""),r(!0),console.log("init",{PayConductor:window.PayConductor}))},c=typeof window<"u"?window.PayConductor:null;if(c)o(c);else{const m=f=>{o(f.detail),window.removeEventListener("payconductor:registered",m)};window.addEventListener("payconductor:registered",m)}let w=!1;const E=m=>{var f,u,g,b;if(((f=m.data)==null?void 0:f.type)===S.RESIZE&&((g=(u=m.data)==null?void 0:u.data)!=null&&g.height)&&d(m.data.data.height+"px"),((b=m.data)==null?void 0:b.type)===S.READY&&e.height&&!w){w=!0;const A=document.querySelector(".payconductor-element iframe");A!=null&&A.contentWindow&&A.contentWindow.postMessage({type:S.CONFIG,data:{height:e.height},requestId:"element-height"},"*")}};return window.addEventListener("message",E),()=>window.removeEventListener("message",E)},[]),k.jsxs("div",{className:"payconductor-element",style:{width:"100%"},children:[i?null:k.jsx("div",{className:"payconductor-skeleton",style:{height:e.height||B}}),i&&t?k.jsx("iframe",{allow:"payment",title:"PayConductor",ref:a,src:t,style:{width:"100%",height:e.height||s||B,border:"none"}}):null]})}function ke(e){const[a,t]=I.useState(()=>!1);return I.useEffect(()=>{const n=()=>{t(!0)},i=()=>{t(!1)};return window.addEventListener("payconductor:3ds:show",n),window.addEventListener("payconductor:3ds:hide",i),typeof window<"u"&&(window.PayConductor3DS={container:()=>document.getElementById("payconductor-3ds-container"),show:n,hide:i},window.dispatchEvent(new CustomEvent("payconductor:3ds:registered"))),()=>{window.removeEventListener("payconductor:3ds:show",n),window.removeEventListener("payconductor:3ds:hide",i),window.PayConductor3DS=null}},[]),k.jsx("div",{className:"payconductor-three-ds",id:"payconductor-3ds-container",style:{width:"100%",display:a?"block":"none",minHeight:a?e.height||"600px":"0"}})}function Ne(){const e=typeof window<"u"?window.PayConductor:null,a=e!=null&&e.config?{publicKey:e.config.publicKey,orderId:e.config.orderId,theme:e.config.theme,locale:e.config.locale}:{},t=e!=null&&e.frame?{iframe:e.frame.iframe,error:e.frame.error}:{iframe:null,error:null};return{...a,...t}}function U(e){var a;if((a=e==null?void 0:e.frame)!=null&&a.iframe){const t=e.frame.iframe;if(t instanceof HTMLIFrameElement)return t;if(t&&typeof t=="object"){if("current"in t){const n=t.current;if(n instanceof HTMLIFrameElement)return n}if("value"in t){const n=t.value;if(n instanceof HTMLIFrameElement)return n}}}return document.querySelector(".payconductor-element iframe")??null}function Le(){const e=()=>typeof window<"u"?window.PayConductor:null,a=(t,n)=>{const i=e();if(!i)return;const r=U(i);r!=null&&r.contentWindow&&r.contentWindow.postMessage({type:t,data:n},"*")};return{init:async t=>{const n=U(e()),i=z();return De(n||void 0,i,t)},confirmPayment:async t=>{if(!t.orderId)throw new Error("Order ID is required");const n=e();if(!(n!=null&&n.api))throw new Error("PayConductor not initialized");return n.api.confirmPayment(t)},validate:t=>{const n=e();return n?n.api.validate(t):Promise.resolve(!1)},reset:()=>{const t=e();return t?t.api.reset():Promise.resolve()},getSelectedPaymentMethod:()=>{var t;return((t=e())==null?void 0:t.selectedPaymentMethod)??null},updateConfig:t=>{var i;const n=(i=e())==null?void 0:i.config;a(S.CONFIG,{publicKey:n==null?void 0:n.publicKey,orderId:n==null?void 0:n.orderId,theme:t.theme??(n==null?void 0:n.theme),locale:t.locale??(n==null?void 0:n.locale),paymentMethods:t.paymentMethods??(n==null?void 0:n.paymentMethods)})},updateOrderId:t=>{var i;const n=(i=e())==null?void 0:i.config;a(S.CONFIG,{publicKey:n==null?void 0:n.publicKey,orderId:t,theme:n==null?void 0:n.theme,locale:n==null?void 0:n.locale,paymentMethods:n==null?void 0:n.paymentMethods})},update:t=>{a(S.UPDATE,t)},submit:async()=>{const t=U(e()),n=z();try{return await R(t||void 0,n,S.CONFIRM_PAYMENT,{}),{paymentMethod:void 0}}catch(i){return{error:{message:i instanceof Error?i.message:"Payment failed",code:"payment_error",type:"payment_error"}}}}}}var p=(e=>(e.Success="Success",e.Failed="Failed",e.Timeout="Timeout",e))(p||{}),D=(e=>(e.Authenticated="Y",e.Attempted="A",e.ChallengeRequired="C",e.NotAuthenticated="N",e.Unavailable="U",e.Rejected="R",e.InformationOnly="I",e))(D||{});class N{constructor(a,t){P(this,"overlay",null);P(this,"modalContent",null);this.data=a,this.options=t}get amountInCents(){return this.data.amount===void 0?void 0:Math.round(this.data.amount*100)}fail(a,t={}){var i,r;const n=new Error(a);return(r=(i=this.options).onError)==null||r.call(i,n),{...t,status:"Failed",error:n}}showModal(){return this.injectStyles(),this.overlay=document.createElement("div"),this.overlay.id="payconductor-3ds-overlay",this.modalContent=document.createElement("div"),this.modalContent.id="payconductor-3ds-modal",this.overlay.appendChild(this.modalContent),document.body.appendChild(this.overlay),this.modalContent}closeModal(){this.overlay&&(this.overlay.remove(),this.overlay=null,this.modalContent=null)}resolveContainer(){return this.modalContent??this.showModal()}injectStyles(){if(document.getElementById("payconductor-3ds-styles"))return;const a=document.createElement("style");a.id="payconductor-3ds-styles",a.textContent=`
13
+ `;function ue(e){const a=new URLSearchParams({publicKey:e.publicKey});return`${se}?${a.toString()}`}function he(){return crypto.randomUUID()}function me(e,a){return a.some(t=>{try{return new URL(t).origin===e}catch{return t===e}})}function G(){return new Map}function O(e,a,t,n){return new Promise((r,i)=>{if(!e||!("contentWindow"in e)){i(new Error("Iframe not defined"));return}if(!(e!=null&&e.contentWindow)){i(new Error("Iframe not ready"));return}if(!a){i(new Error("Pending requests not initialized"));return}const s=he();a.set(s,{resolve:r,reject:i}),e.contentWindow.postMessage({type:t,data:n,requestId:s},"*"),setTimeout(()=>{a!=null&&a.has(s)&&(a.delete(s),i(new Error("Request timeout")))},ce)})}function Ie(e,a,t){return O(e,a,w.CONFIRM_PAYMENT,t)}async function De(e,a,t){return await Ie(e,a,{orderId:t.orderId})}function Me(e,a,t){return O(e,a,w.VALIDATE,t)}function _e(e,a){return O(e,a,w.RESET)}function Re(e,a,t){return O(e,a,w.CONFIG,t)}function xe(e,a,t){return O(e,a,w.INIT,t)}function Oe(e,a,t,n,r,i,s,d,o,l,y,g){const c=e.data,{requestId:m,type:P,data:E,error:T}=c;if(P===w.READY){if(n==null||n(),m&&(a!=null&&a.has(m))){const{resolve:p}=a.get(m);a.delete(m),p(E)}return}if(me(e.origin,de)){if(m&&a&&a.has(m)){const{resolve:p,reject:B}=a.get(m);a.delete(m),T?B(new Error(String(T.message))):p(E);return}if(P===w.ERROR){t((T==null?void 0:T.message)||"Unknown error"),r==null||r(new Error(String(T==null?void 0:T.message)));return}if(P===w.PAYMENT_COMPLETE){E&&typeof E=="object"&&"status"in E&&(i==null||i(E));return}if(P===w.PAYMENT_FAILED){E&&typeof E=="object"&&"status"in E&&(s==null||s(E));return}if(P===w.PAYMENT_PENDING){E&&typeof E=="object"&&"status"in E&&(d==null||d(E));return}if(P===w.PAYMENT_METHOD_SELECTED){E&&typeof E=="object"&&"paymentMethod"in E&&(o==null||o(E.paymentMethod));return}if(P!==w.RESIZE){if(P===A.ThreeDSChallenge){l==null||l();return}if(P===A.ThreeDSComplete){y==null||y();return}if(P===A.ThreeDSFailed){g==null||g();return}}}}function fe(e){const[a,t]=v.useState(()=>!1),[n,r]=v.useState(()=>null),[i,s]=v.useState(()=>""),[d,o]=v.useState(()=>null);return v.useEffect(()=>{const l=(...h)=>{e.debug&&console.log("[PayConductor]",...h)},y=ue({publicKey:e.publicKey});s(y),t(!0);const g=G();let c=!1;l("init",e.publicKey),l("iframeUrl",y);const m=()=>{var b,u;const h=(u=(b=window.PayConductor)==null?void 0:b.frame)==null?void 0:u.iframe;if(h){if(h instanceof HTMLIFrameElement)return h;if(typeof h=="object"&&h!==null){const f=h;if("current"in f&&f.current instanceof HTMLIFrameElement)return f.current;if("value"in f&&f.value instanceof HTMLIFrameElement)return f.value}return h}return document.querySelector(".payconductor-element iframe")??void 0},P={get iframe(){return document.querySelector(".payconductor-element iframe")??null},set iframe(h){},iframeUrl:y,error:null},E={publicKey:e.publicKey,theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod},T={confirmPayment:h=>{var u;l("→ CONFIRM_PAYMENT",{orderId:h.orderId});const b=m();return b!=null&&b.contentWindow&&b.contentWindow.postMessage({type:w.CONFIG,data:{publicKey:e.publicKey,orderId:h.orderId,theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod,showPaymentButtons:e.showPaymentButtons,nuPayConfig:e.nuPayConfig}},"*"),E.orderId=h.orderId,(u=window.PayConductor)!=null&&u.config&&(window.PayConductor.config.orderId=h.orderId),De(b,g,h)},validate:h=>(l("→ VALIDATE",h),Me(m(),g,h)),reset:()=>(l("→ RESET"),_e(m(),g)),getSelectedPaymentMethod:()=>d};window.PayConductor={frame:P,config:E,api:T,selectedPaymentMethod:d},l("registered"),window.dispatchEvent(new CustomEvent("payconductor:registered",{detail:window.PayConductor}));const p=async()=>{if(!c){const h=m();if(!h){l("→ CONFIG skipped: iframe not found");return}c=!0,l("→ CONFIG",{theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod,showPaymentButtons:e.showPaymentButtons}),Re(h,g,{theme:e.theme,locale:e.locale,paymentMethods:e.paymentMethods,defaultPaymentMethod:e.defaultPaymentMethod,showPaymentButtons:e.showPaymentButtons,nuPayConfig:e.nuPayConfig})}},B=h=>{var b;(b=h.data)!=null&&b.type&&l("←",h.data.type,h.data.data??""),Oe(h,g,u=>{var f;r(u),P.error=u,(f=window.PayConductor)!=null&&f.frame&&(window.PayConductor.frame.error=u)},()=>{var u;(u=e.onReady)==null||u.call(e),p()},u=>{var f;(f=e.onError)==null||f.call(e,u)},u=>{var f;(f=e.onPaymentComplete)==null||f.call(e,u)},u=>{var f;(f=e.onPaymentFailed)==null||f.call(e,u)},u=>{var f;(f=e.onPaymentPending)==null||f.call(e,u)},u=>{var f;o(u),window.PayConductor&&(window.PayConductor.selectedPaymentMethod=u),(f=e.onPaymentMethodSelected)==null||f.call(e,u)},()=>{var u;(u=e.onThreeDSChallenge)==null||u.call(e)},()=>{var u;(u=e.onThreeDSComplete)==null||u.call(e)},()=>{var u;(u=e.onThreeDSFailed)==null||u.call(e)})};window.addEventListener("message",B);const we=()=>{var b,u,f;const h=m();if(!h)return!1;try{if((((b=h.contentDocument)==null?void 0:b.readyState)??((f=(u=h.contentWindow)==null?void 0:u.document)==null?void 0:f.readyState))==="complete")return p(),!0}catch{}return!1},q=()=>{if(we())return;const h=m();if(h){h.addEventListener("load",()=>p(),{once:!0});return}setTimeout(q,50)};q()},[]),k.jsx("div",{className:"payconductor",id:"payconductor",style:{display:"contents"},children:e.children})}function ke(e){const a=v.useRef(null),[t,n]=v.useState(()=>""),[r,i]=v.useState(()=>!1),[s,d]=v.useState(()=>"");return v.useEffect(()=>{if(typeof document<"u"&&!document.getElementById(H)){const c=document.createElement("style");c.id=H,c.textContent=le,document.head.appendChild(c)}const o=c=>{c!=null&&c.frame&&(n(c.frame.iframeUrl||""),i(!0),console.log("init",{PayConductor:window.PayConductor}))},l=typeof window<"u"?window.PayConductor:null;if(l)o(l);else{const c=m=>{o(m.detail),window.removeEventListener("payconductor:registered",c)};window.addEventListener("payconductor:registered",c)}let y=!1;const g=c=>{var m,P,E,T;if(((m=c.data)==null?void 0:m.type)===w.RESIZE&&((E=(P=c.data)==null?void 0:P.data)!=null&&E.height)&&d(c.data.data.height+"px"),((T=c.data)==null?void 0:T.type)===w.READY&&e.height&&!y){y=!0;const p=document.querySelector(".payconductor-element iframe");p!=null&&p.contentWindow&&p.contentWindow.postMessage({type:w.CONFIG,data:{height:e.height},requestId:"element-height"},"*")}};return window.addEventListener("message",g),()=>window.removeEventListener("message",g)},[]),k.jsxs("div",{className:"payconductor-element",style:{width:"100%"},children:[r?null:k.jsx("div",{className:"payconductor-skeleton",style:{height:e.height||j}}),r&&t?k.jsx("iframe",{allow:"payment",title:"PayConductor",ref:a,src:t,style:{width:"100%",height:e.height||s||j,border:"none"}}):null]})}function Ne(e){const[a,t]=v.useState(()=>!1);return v.useEffect(()=>{const n=()=>{t(!0)},r=()=>{t(!1)};return window.addEventListener("payconductor:3ds:show",n),window.addEventListener("payconductor:3ds:hide",r),typeof window<"u"&&(window.PayConductor3DS={container:()=>document.getElementById("payconductor-3ds-container"),show:n,hide:r},window.dispatchEvent(new CustomEvent("payconductor:3ds:registered"))),()=>{window.removeEventListener("payconductor:3ds:show",n),window.removeEventListener("payconductor:3ds:hide",r),window.PayConductor3DS=null}},[]),k.jsx("div",{className:"payconductor-three-ds",id:"payconductor-3ds-container",style:{width:"100%",display:a?"block":"none",minHeight:a?e.height||"600px":"0"}})}function Le(){const e=typeof window<"u"?window.PayConductor:null,a=e!=null&&e.config?{publicKey:e.config.publicKey,orderId:e.config.orderId,theme:e.config.theme,locale:e.config.locale}:{},t=e!=null&&e.frame?{iframe:e.frame.iframe,error:e.frame.error}:{iframe:null,error:null};return{...a,...t}}function K(e){var a;if((a=e==null?void 0:e.frame)!=null&&a.iframe){const t=e.frame.iframe;if(t instanceof HTMLIFrameElement)return t;if(t&&typeof t=="object"){if("current"in t){const n=t.current;if(n instanceof HTMLIFrameElement)return n}if("value"in t){const n=t.value;if(n instanceof HTMLIFrameElement)return n}}}return document.querySelector(".payconductor-element iframe")??null}function Ue(){const e=()=>typeof window<"u"?window.PayConductor:null,a=(t,n)=>{const r=e();if(!r)return;const i=K(r);i!=null&&i.contentWindow&&i.contentWindow.postMessage({type:t,data:n},"*")};return{init:async t=>{const n=K(e()),r=G();return xe(n||void 0,r,t)},confirmPayment:async t=>{if(!t.orderId)throw new Error("Order ID is required");const n=e();if(!(n!=null&&n.api))throw new Error("PayConductor not initialized");return n.api.confirmPayment(t)},validate:t=>{const n=e();return n?n.api.validate(t):Promise.resolve(!1)},reset:()=>{const t=e();return t?t.api.reset():Promise.resolve()},getSelectedPaymentMethod:()=>{var t;return((t=e())==null?void 0:t.selectedPaymentMethod)??null},updateConfig:t=>{var r;const n=(r=e())==null?void 0:r.config;a(w.CONFIG,{publicKey:n==null?void 0:n.publicKey,orderId:n==null?void 0:n.orderId,theme:t.theme??(n==null?void 0:n.theme),locale:t.locale??(n==null?void 0:n.locale),paymentMethods:t.paymentMethods??(n==null?void 0:n.paymentMethods)})},updateOrderId:t=>{var r;const n=(r=e())==null?void 0:r.config;a(w.CONFIG,{publicKey:n==null?void 0:n.publicKey,orderId:t,theme:n==null?void 0:n.theme,locale:n==null?void 0:n.locale,paymentMethods:n==null?void 0:n.paymentMethods})},update:t=>{a(w.UPDATE,t)},submit:async()=>{const t=K(e()),n=G();try{return await O(t||void 0,n,w.CONFIRM_PAYMENT,{}),{paymentMethod:void 0}}catch(r){return{error:{message:r instanceof Error?r.message:"Payment failed",code:"payment_error",type:"payment_error"}}}}}}var F=(e=>(e.Auto="Auto",e.Manual="Manual",e.Agnostic="Agnostic",e))(F||{}),S=(e=>(e.Success="Success",e.Failed="Failed",e.Timeout="Timeout",e))(S||{}),R=(e=>(e.Authenticated="Y",e.Attempted="A",e.ChallengeRequired="C",e.NotAuthenticated="N",e.Unavailable="U",e.Rejected="R",e.InformationOnly="I",e))(R||{});class N{constructor(a,t){C(this,"overlay",null);C(this,"modalContent",null);this.data=a,this.options=t}get amountInCents(){return this.data.amount===void 0?void 0:Math.round(this.data.amount*100)}fail(a,t={}){const n=new Error(a);return{...t,status:"Failed",error:n}}showModal(){return this.injectStyles(),this.overlay=document.createElement("div"),this.overlay.id="payconductor-3ds-overlay",this.modalContent=document.createElement("div"),this.modalContent.id="payconductor-3ds-modal",this.overlay.appendChild(this.modalContent),document.body.appendChild(this.overlay),this.modalContent}closeModal(){this.overlay&&(this.overlay.remove(),this.overlay=null,this.modalContent=null)}resolveContainer(){return this.modalContent??this.showModal()}injectStyles(){if(document.getElementById("payconductor-3ds-styles"))return;const a=document.createElement("style");a.id="payconductor-3ds-styles",a.textContent=`
14
14
  #payconductor-3ds-overlay {
15
15
  position: fixed;
16
16
  inset: 0;
@@ -45,5 +45,5 @@
45
45
  height: 440px;
46
46
  }
47
47
  }
48
- `,document.head.appendChild(a)}}const Oe=5*60*1e3;class Ue extends N{constructor(){super(...arguments);P(this,"iframe",null);P(this,"messageListener",null);P(this,"timeoutId",null)}async authenticate(){const{threeDsUrl:t,creq:n}=this.data;if(!t||!n)return this.fail("Missing threeDsUrl or creq");const i=this.resolveContainer();return new Promise(r=>{var c;this.iframe=document.createElement("iframe"),this.iframe.name="payconductor-3ds-challenge",this.iframe.id="payconductor-3ds-challenge",i.appendChild(this.iframe),this.messageListener=w=>{var E,m,f;((E=w.data)==null?void 0:E.status)==="COMPLETE"&&(this.cleanup(),(f=(m=this.options).onComplete)==null||f.call(m),r({status:p.Success}))},window.addEventListener("message",this.messageListener),this.timeoutId=setTimeout(()=>{var w,E;this.cleanup(),(E=(w=this.options).onTimeout)==null||E.call(w),r({status:p.Timeout})},this.options.timeoutMs??Oe);const s=(c=this.iframe.contentWindow)==null?void 0:c.document;if(!s){this.cleanup(),r(this.fail("Cannot access iframe document"));return}const d=s.createElement("form");d.name="threeDsChallengeForm",d.setAttribute("target","payconductor-3ds-challenge"),d.setAttribute("method","post"),d.setAttribute("action",t);const o=s.createElement("input");o.setAttribute("type","hidden"),o.setAttribute("name","creq"),o.setAttribute("value",n),d.appendChild(o),this.iframe.appendChild(d),d.submit()})}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null),this.iframe&&(this.iframe.remove(),this.iframe=null),this.closeModal()}}const F=new Map;function L(e){const a=F.get(e);if(a)return a;const t=new Promise((n,i)=>{if(document.querySelector(`script[src="${e}"]`)){n();return}const r=document.createElement("script");r.src=e,r.async=!0,r.onload=()=>n(),r.onerror=()=>{F.delete(e),i(new Error(`Failed to load script: ${e}`))},(document.head||document.body).appendChild(r)});return F.set(e,t),t}const Fe="https://static.payzen.lat/static/js/authenticate-client/V1.0/kr-authenticate.umd.js",Be=10*60*1e3;class Ke extends N{constructor(){super(...arguments);P(this,"timeoutId",null)}async authenticate(){const{operationUrl:t,publicKey:n}=this.data;if(!t||!n)return this.fail("Missing operationUrl or publicKey");try{await L(Fe)}catch{return this.fail("Failed to load 3DS SDK")}const i=window.KrAuthenticate;return i?new Promise(r=>{this.timeoutId=setTimeout(()=>{var d,o;this.cleanup(),(o=(d=this.options).onTimeout)==null||o.call(d),r({status:p.Timeout})},this.options.timeoutMs??Be),new i(n).authenticate(t,()=>{var d,o;this.cleanup(),(o=(d=this.options).onComplete)==null||o.call(d),r({status:p.Success})})}):this.fail("KrAuthenticate not available")}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}}const ze={[x.Production]:"https://3ds-nx-js.stone.com.br/live/v2/3ds2.min.js",[x.Sandbox]:"https://3ds-nx-js.stone.com.br/test/v2/3ds2.min.js"},je=5*60*1e3;function He(){const e=window.innerWidth;return e<=480?"01":e<=768?"02":e<=1024?"03":"04"}class Ye extends N{constructor(){super(...arguments);P(this,"timeoutId",null);P(this,"methodContainer",null)}async authenticate(){const{authToken:t,card:n}=this.data;if(!t)return this.fail("Missing authToken for PagarMe 3DS");if(!n)return this.fail("Missing card data for PagarMe 3DS");const i=this.data.environment??x.Production;try{await L(ze[i])}catch{return this.fail("Failed to load Stone 3DS SDK")}const r=window.TDS;if(!r)return this.fail("Stone TDS SDK not available");const s=this.resolveContainer();return this.methodContainer=document.createElement("div"),this.methodContainer.style.display="none",document.body.appendChild(this.methodContainer),new Promise(d=>{this.timeoutId=setTimeout(()=>{var o,c;this.cleanup(),(c=(o=this.options).onTimeout)==null||c.call(o),d({status:p.Timeout})},this.options.timeoutMs??je),r.init({token:t,tds_method_container_element:this.methodContainer,challenge_container_element:s,use_default_challenge_iframe_style:!0,challenge_window_size:He()},this.buildOrderData()).then(o=>{var m,f;if(this.cleanup(),!(o!=null&&o.length)){d(this.fail("PagarMe 3DS returned no response"));return}const c=o[0],w=Object.values(D).find(u=>u===c.trans_status),E={transStatus:w,providerTransactionId:c.tds_server_trans_id,challengeCanceled:c.challenge_canceled};if(c.challenge_canceled){d(this.fail("3DS challenge canceled by user",E));return}w===D.Authenticated||w===D.Attempted?((f=(m=this.options).onComplete)==null||f.call(m),d({...E,status:p.Success,dsTransactionId:c.tds_server_trans_id})):d(this.fail(`3DS failed with status: ${c.trans_status}`,E))}).catch(o=>{this.cleanup(),d(this.fail(o instanceof Error?o.message:"PagarMe 3DS failed"))})})}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.methodContainer&&(this.methodContainer.remove(),this.methodContainer=null),this.closeModal()}buildOrderData(){var r;const{card:t,customer:n,billingAddress:i}=this.data;return{payments:[{payment_method:"credit_card",credit_card:{card:{number:t==null?void 0:t.number,holder_name:t==null?void 0:t.holderName,exp_month:Number(t==null?void 0:t.expMonth),exp_year:Number(t==null?void 0:t.expYear),billing_address:i?{country:i.country,state:i.state,city:i.city,zip_code:i.zipCode,line_1:`${i.number}, ${i.street}${i.district?`, ${i.district}`:""}`,line_2:i.complement??""}:void 0}},amount:this.amountInCents}],...n?{customer:{name:n.name,email:n.email,...n.document?{document:n.document}:{},...(r=n.phones)!=null&&r.length?{phones:Object.fromEntries(n.phones.map(s=>[s.type==="HOME"?"home_phone":"mobile_phone",{country_code:s.countryCode,area_code:s.areaCode,number:s.number}]))}:{}}}:{}}}}const Ge="https://assets.pagseguro.com.br/checkout-sdk-js/rc/dist/browser/pagseguro.min.js";class Ve extends N{async authenticate(){var E,m,f;const{authToken:a,card:t,customer:n,currency:i,billingAddress:r}=this.data,s=this.amountInCents;if(!a)return this.fail("Missing authToken (session) for PagSeguro 3DS");if(!t)return this.fail("Missing card data for PagSeguro 3DS");if(!n)return this.fail("Missing customer data for PagSeguro 3DS");if(!s)return this.fail("Missing amount for PagSeguro 3DS");if(!r)return this.fail("Missing billingAddress for PagSeguro 3DS");const d=this.data.environment===x.Sandbox?"SANDBOX":"PROD";try{await L(Ge)}catch{return this.fail("Failed to load PagSeguro SDK")}const o=window.PagSeguro;if(!o)return this.fail("PagSeguro SDK not available");o.setUp({session:a,env:d});const c=((E=n.phones)==null?void 0:E.map(u=>({country:u.countryCode,area:u.areaCode,number:u.number,type:u.type??"MOBILE"})))??[{country:"55",area:"11",number:"999999999",type:"MOBILE"}];c.some(u=>u.type==="MOBILE")||(c[0].type="MOBILE");try{const u=await o.authenticate3DS({data:{customer:{name:n.name,email:n.email,phones:c},paymentMethod:{type:this.data.installments===0?"DEBIT_CARD":"CREDIT_CARD",installments:this.data.installments??1,card:{number:t.number,expMonth:t.expMonth,expYear:t.expYear,holder:{name:t.holderName}}},amount:{value:s,currency:i??"BRL"},billingAddress:{street:r.street,number:r.number,complement:r.complement,regionCode:r.state,country:r.country.length===2?this.toAlpha3(r.country):r.country,city:r.city,postalCode:r.zipCode.replace(/\D/g,"")},dataOnly:!1}});return u.status==="AUTH_FLOW_COMPLETED"||u.status==="AUTH_NOT_SUPPORTED"?((f=(m=this.options).onComplete)==null||f.call(m),{status:p.Success,dsTransactionId:u.id}):u.status==="CHANGE_PAYMENT_METHOD"?this.fail("PagSeguro requires a different payment method"):{status:p.Success,dsTransactionId:u.id}}catch(u){return this.fail(u instanceof Error?u.message:"PagSeguro 3DS failed")}}cleanup(){}toAlpha3(a){return{BR:"BRA",US:"USA",AR:"ARG",CL:"CHL",CO:"COL",MX:"MEX",PE:"PER",UY:"URY"}[a.toUpperCase()]??a}}const $e=5*60*1e3,Y="payconductor-3ds-sandbox-title";class G extends N{constructor(){super(...arguments);P(this,"timeoutId",null)}async authenticate(){const{authToken:t}=this.data;if(!t)return this.fail("Missing authToken for 3DS challenge");const n=this.resolveContainer();return new Promise(i=>{this.timeoutId=setTimeout(()=>{var r,s;this.cleanup(),(s=(r=this.options).onTimeout)==null||s.call(r),i({status:p.Timeout})},this.options.timeoutMs??$e),this.renderChallenge(n,{onConfirm:()=>{var r,s;this.cleanup(),(s=(r=this.options).onComplete)==null||s.call(r),i({status:p.Success,transStatus:D.Authenticated,providerTransactionId:t})},onCancel:()=>{this.cleanup(),i(this.fail("3DS challenge canceled by user",{challengeCanceled:!0}))}})})}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.closeModal()}renderChallenge(t,n){const i=document.createElement("div");i.setAttribute("role","dialog"),i.setAttribute("aria-modal","true"),i.setAttribute("aria-labelledby",Y),i.style.cssText="min-height:inherit;box-sizing:border-box;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:16px;padding:32px;font-family:system-ui,-apple-system,sans-serif;text-align:center;color:#111827";const r=document.createElement("h2");r.id=Y,r.textContent="Autenticação 3DS (sandbox)",r.style.cssText="margin:0;font-size:20px";const s=document.createElement("p");s.textContent="Simulação do desafio do banco emissor. Confirme para aprovar a autenticação ou cancele para simular a desistência do comprador.",s.style.cssText="margin:0 0 8px;max-width:360px;font-size:14px;line-height:1.5;color:#4b5563";const d=this.createButton("Confirmar autenticação","background:#111827;color:#fff;border-color:#111827",n.onConfirm),o=this.createButton("Cancelar","background:#fff;color:#111827;border-color:#d1d5db",n.onCancel);i.append(r,s,d,o),t.appendChild(i),d.focus()}createButton(t,n,i){const r=document.createElement("button");return r.type="button",r.textContent=t,r.style.cssText=`width:100%;max-width:320px;padding:12px 16px;border:1px solid;border-radius:6px;font:inherit;font-size:14px;font-weight:600;cursor:pointer;${n}`,r.addEventListener("click",i),r}}const qe={[v.Lyra]:Ke,[v.MercadoPago]:Ue,[v.PagarMe]:Ye,[v.PagSeguro]:Ve,[v.Sandbox]:G,[v.SandboxSplit]:G};class We extends Error{constructor(a,t){super(a),this.title=t,this.name="PayConductorThreeDSApiError"}}class Je{constructor(a){this.publicKey=a}async completeManualChallenge(a,t){const n=await fetch(`${_}/three-ds/complete/${a}`,{method:"POST",headers:this.headers,body:JSON.stringify({providerTransactionId:t})});n.ok||await this.parseResponseError("Failed to complete native 3DS challenge",n)}async getThreeDSecureData(a){const t=await fetch(`${_}/three-ds/challenge/${a}`,{method:"GET",headers:this.headers});t.ok||await this.parseResponseError("Failed to fetch 3DS data",t);const n=await t.json();return Object.fromEntries(Object.entries(n).filter(([,i])=>i!=null))}async parseResponseError(a,t){var i,r,s,d;let n="";try{const o=await t.json();o!=null&&o.message?n=o.message:(i=o==null?void 0:o.error)!=null&&i.message?n=o.error:(s=(r=o==null?void 0:o.error)==null?void 0:r.value)!=null&&s.message?n=o.error.value.message:(d=o==null?void 0:o.value)!=null&&d.message?n=o.value.message:n=JSON.stringify(o)}catch{}throw new We(n,a)}get headers(){return{Authorization:`Basic ${btoa(`${this.publicKey}:x`)}`,"Content-Type":"application/json"}}}const Xe=[v.PagSeguro];class fe{constructor(a){P(this,"data");P(this,"provider",null);P(this,"api");this.data=a,this.api=new Je(this.data.publicKey)}get needsChallenge(){return this.data.status==="NeedChallenge"||this.data.statusDetail==="ThreeDsAwaitingChallenge"}get acquirer(){return this.data.acquirer}async authenticate(a){var d;const t=await this.api.getThreeDSecureData(this.data.orderId);if(this.data={...this.data,...t},!this.needsChallenge)return{status:p.Success};const{acquirer:n}=this.data;if(!n)return{status:p.Failed,error:new Error("Missing 3DS acquirer")};const i=qe[n];if(!i)return{status:p.Failed,error:new Error(`Unsupported 3DS provider: ${n}`)};(d=a==null?void 0:a.onChallenge)==null||d.call(a);const r={...a,threeDSecure:this.data};this.provider=new i(this.data,r);const s=await this.provider.authenticate();return s.status===p.Success&&s.dsTransactionId&&Xe.includes(n)&&await this.api.completeManualChallenge(this.data.orderId,s.dsTransactionId),s}destroy(){this.provider&&(this.provider.cleanup(),this.provider=null)}}function Ze(e){let a=null;return{handleChallenge:async i=>{const r=new fe(i);a=r;try{return await r.authenticate({onChallenge:e==null?void 0:e.onChallenge,onComplete:e==null?void 0:e.onComplete,onError:e==null?void 0:e.onError,onTimeout:e==null?void 0:e.onTimeout})}finally{r.destroy(),a=null}},destroy:()=>{a==null||a.destroy(),a=null}}}class Qe extends Error{constructor(a,t){super(a),this.title=t,this.name="PayConductorTokenizerApiError"}}class et{constructor(a){this.publicKey=a}async getSettings(){const a=await fetch(`${_}/card-tokenization/settings`,{method:"GET",headers:this.headers});return a.ok||await this.parseResponseError("Failed to fetch settings",a),await a.json()}async createToken(a){const t=await fetch(`${_}/card-tokenization/tokenize`,{method:"POST",headers:this.headers,body:JSON.stringify(a)});return t.ok||await this.parseResponseError("Failed to generate token",t),await t.json()}async saveTokens(a,t,n){const i=await fetch(`${_}/card-tokenization/save-tokens/${t}/${n}`,{method:"POST",headers:this.headers,body:JSON.stringify(a)});i.ok||await this.parseResponseError("Failed to save tokens",i)}async parseResponseError(a,t){var i,r,s,d;let n="";try{const o=await t.json();o!=null&&o.message?n=o.message:(i=o==null?void 0:o.error)!=null&&i.message?n=o.error:(s=(r=o==null?void 0:o.error)==null?void 0:r.value)!=null&&s.message?n=o.error.value.message:(d=o==null?void 0:o.value)!=null&&d.message?n=o.value.message:n=JSON.stringify(o)}catch{}throw new Qe(n,a)}get headers(){return{Authorization:`Basic ${btoa(`${this.publicKey}:x`)}`,"Content-Type":"application/json"}}}class tt{constructor(a){this.input=a}}class nt extends tt{constructor(){super(...arguments);P(this,"scriptUrl","https://sdk.mercadopago.com/js/v2")}async tokenize(){const{publicKey:t}=this.input.setting;if(typeof t!="string"||!t.trim())throw new Error("MercadoPago public key is missing in settings");if(!this.input.customer.documentNumber)throw new Error("Customer document number is required for tokenization");const n=window.MercadoPago;if(!n)throw new Error("MercadoPago SDK not available");const i=new n(t.trim()),{expiration:r,cvv:s,number:d,holderName:o}=this.input.card,c=await i.createCardToken({cardExpirationMonth:String(r.month).padStart(2,"0"),cardExpirationYear:String(r.year),cardholderName:o,cardNumber:d,securityCode:s,identificationType:this.input.customer.documentType===j.Cpf?"CPF":"CNPJ",identificationNumber:this.input.customer.documentNumber}).catch(w=>{throw new Error(this.describeMercadoPagoError(w))});if("id"in c&&c.id)return c.id;throw new Error(this.describeMercadoPagoError(c))}describeMercadoPagoError(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(n=>this.describeMercadoPagoError(n)).join("; ");if(typeof t=="object"&&t!==null){if("cause"in t&&Array.isArray(t.cause)&&t.cause.length>0)return this.describeMercadoPagoError(t.cause);if("message"in t&&typeof t.message=="string")return t.message;if("description"in t&&typeof t.description=="string")return t.description}return"Failed to tokenize card"}}const at={[v.MercadoPago]:nt};class ye{constructor(a){P(this,"api");this.publicKey=a,this.api=new et(this.publicKey)}async tokenizeCard(a){this.validateCard(a);const{customerId:t,token:n}=await this.api.createToken({card:a.card,customer:a.customer,saveCard:!1}),{settings:i}=await this.api.getSettings(),s=(await Promise.all(i.map(async d=>{const o=at[d.key];if(!o)return null;const c=new o({...a,setting:d.settings});return await L(c.scriptUrl),{token:await c.tokenize(),integrationId:d.integrationId,providerKey:d.key}}))).filter(d=>d!==null);return s.length>0&&await this.api.saveTokens(s,t,n),n}validateCard(a){const{number:t,cvv:n,expiration:i,holderName:r}=a.card;if(!t||!n||!(i!=null&&i.month)||!(i!=null&&i.year)||!r)throw new Error("Invalid card data")}}function it(e){const a=new ye(e.publicKey);return{tokenizeCard:async n=>{var i,r;try{const s=await a.tokenizeCard(n);return(i=e.onSuccess)==null||i.call(e,s),s}catch(s){const d=s instanceof Error?s:new Error("Tokenization failed");return(r=e.onError)==null||r.call(e,d),null}}}}exports.ALLOWED_ORIGINS=se;exports.CardBrand=ee;exports.ChargeStatusDetail=X;exports.CurrencyType=te;exports.DeviceType=ne;exports.DocumentType=j;exports.ERROR_CODES=Te;exports.ErrorCode=ie;exports.IFRAME_BASE_URL=oe;exports.IFRAME_DEFAULT_HEIGHT_VALUE=B;exports.IncomingMessage=T;exports.InputStyleKey=ae;exports.IntegrationProvider=v;exports.OrganizationEnvironment=x;exports.OutgoingMessage=M;exports.POST_MESSAGES=S;exports.PayConductor=me;exports.PayConductor3DSSDK=fe;exports.PayConductorCheckoutElement=Re;exports.PayConductorThreeDSElement=ke;exports.PayConductorTokenizerSDK=ye;exports.PaymentMethod=q;exports.PaymentMethodLayout=W;exports.PaymentStatus=J;exports.REQUEST_TIMEOUT=de;exports.SDK_API_BASE_URL=_;exports.SKELETON_CSS=ce;exports.SKELETON_STYLE_ID=K;exports.ThreeDSResultStatus=Q;exports.ThreeDSTransStatus=D;exports.ThreeDSecureResultStatus=p;exports.ThreeDsAuthenticationStatus=Z;exports.buildIframeUrl=le;exports.default=me;exports.defaultTheme=be;exports.generateRequestId=ue;exports.isValidOrigin=he;exports.loadScript=L;exports.usePayConductor=Ne;exports.usePayconductorElement=Le;exports.useThreeDS=Ze;exports.useTokenizer=it;
48
+ `,document.head.appendChild(a)}}const Fe=5*60*1e3;class Be extends N{constructor(){super(...arguments);C(this,"iframe",null);C(this,"messageListener",null);C(this,"timeoutId",null)}async authenticate(){const{threeDsUrl:t,creq:n}=this.data;if(!t||!n)return this.fail("Missing threeDsUrl or creq");const r=this.resolveContainer();return new Promise(i=>{var l;this.iframe=document.createElement("iframe"),this.iframe.name="payconductor-3ds-challenge",this.iframe.id="payconductor-3ds-challenge",r.appendChild(this.iframe),this.messageListener=y=>{var g;((g=y.data)==null?void 0:g.status)==="COMPLETE"&&(this.cleanup(),i({status:S.Success}))},window.addEventListener("message",this.messageListener),this.timeoutId=setTimeout(()=>{this.cleanup(),i({status:S.Timeout})},this.options.timeoutMs??Fe);const s=(l=this.iframe.contentWindow)==null?void 0:l.document;if(!s){this.cleanup(),i(this.fail("Cannot access iframe document"));return}const d=s.createElement("form");d.name="threeDsChallengeForm",d.setAttribute("target","payconductor-3ds-challenge"),d.setAttribute("method","post"),d.setAttribute("action",t);const o=s.createElement("input");o.setAttribute("type","hidden"),o.setAttribute("name","creq"),o.setAttribute("value",n),d.appendChild(o),this.iframe.appendChild(d),d.submit()})}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null),this.iframe&&(this.iframe.remove(),this.iframe=null),this.closeModal()}}const z=new Map;function L(e){const a=z.get(e);if(a)return a;const t=new Promise((n,r)=>{if(document.querySelector(`script[src="${e}"]`)){n();return}const i=document.createElement("script");i.src=e,i.async=!0,i.onload=()=>n(),i.onerror=()=>{z.delete(e),r(new Error(`Failed to load script: ${e}`))},(document.head||document.body).appendChild(i)});return z.set(e,t),t}const Ke="https://static.payzen.lat/static/js/authenticate-client/V1.0/kr-authenticate.umd.js",ze=10*60*1e3;class je extends N{constructor(){super(...arguments);C(this,"timeoutId",null)}async authenticate(){const{operationUrl:t,publicKey:n}=this.data;if(!t||!n)return this.fail("Missing operationUrl or publicKey");try{await L(Ke)}catch{return this.fail("Failed to load 3DS SDK")}const r=window.KrAuthenticate;return r?new Promise(i=>{this.timeoutId=setTimeout(()=>{this.cleanup(),i({status:S.Timeout})},this.options.timeoutMs??ze),new r(n).authenticate(t,()=>{this.cleanup(),i({status:S.Success})})}):this.fail("KrAuthenticate not available")}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}}const He={[x.Production]:"https://3ds-nx-js.stone.com.br/live/v2/3ds2.min.js",[x.Sandbox]:"https://3ds-nx-js.stone.com.br/test/v2/3ds2.min.js"},Ge=5*60*1e3;function $e(){const e=window.innerWidth;return e<=480?"01":e<=768?"02":e<=1024?"03":"04"}class qe extends N{constructor(){super(...arguments);C(this,"timeoutId",null);C(this,"methodContainer",null)}async authenticate(){const{authToken:t,card:n}=this.data;if(!t)return this.fail("Missing authToken for PagarMe 3DS");if(!n)return this.fail("Missing card data for PagarMe 3DS");const r=this.data.environment??x.Production;try{await L(He[r])}catch{return this.fail("Failed to load Stone 3DS SDK")}const i=window.TDS;if(!i)return this.fail("Stone TDS SDK not available");const s=this.resolveContainer();return this.methodContainer=document.createElement("div"),this.methodContainer.style.display="none",document.body.appendChild(this.methodContainer),new Promise(d=>{this.timeoutId=setTimeout(()=>{this.cleanup(),d({status:S.Timeout})},this.options.timeoutMs??Ge),i.init({token:t,tds_method_container_element:this.methodContainer,challenge_container_element:s,use_default_challenge_iframe_style:!0,challenge_window_size:$e()},this.buildOrderData()).then(o=>{if(this.cleanup(),!(o!=null&&o.length)){d(this.fail("PagarMe 3DS returned no response"));return}const l=o[0],y=Object.values(R).find(c=>c===l.trans_status),g={transStatus:y,providerTransactionId:l.tds_server_trans_id,challengeCanceled:l.challenge_canceled};if(l.challenge_canceled){d(this.fail("3DS challenge canceled by user",g));return}y===R.Authenticated||y===R.Attempted?d({...g,status:S.Success,dsTransactionId:l.tds_server_trans_id}):d(this.fail(`3DS failed with status: ${l.trans_status}`,g))}).catch(o=>{this.cleanup(),d(this.fail(o instanceof Error?o.message:"PagarMe 3DS failed"))})})}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.methodContainer&&(this.methodContainer.remove(),this.methodContainer=null),this.closeModal()}buildOrderData(){var i;const{card:t,customer:n,billingAddress:r}=this.data;return{payments:[{payment_method:"credit_card",credit_card:{card:{number:t==null?void 0:t.number,holder_name:t==null?void 0:t.holderName,exp_month:Number(t==null?void 0:t.expiration.month),exp_year:Number(t==null?void 0:t.expiration.year),billing_address:r?{country:r.country,state:r.state,city:r.city,zip_code:r.zipCode,line_1:`${r.number}, ${r.street}${r.district?`, ${r.district}`:""}`,line_2:r.complement??""}:void 0}},amount:this.amountInCents}],...n?{customer:{name:n.name,email:n.email,...n.document?{document:n.document}:{},...(i=n.phones)!=null&&i.length?{phones:Object.fromEntries(n.phones.map(s=>[s.type==="HOME"?"home_phone":"mobile_phone",{country_code:s.countryCode,area_code:s.areaCode,number:s.number}]))}:{}}}:{}}}}const Ve="https://assets.pagseguro.com.br/checkout-sdk-js/rc/dist/browser/pagseguro.min.js";class Ye extends N{async authenticate(){var g;const{authToken:a,card:t,customer:n,currency:r,billingAddress:i}=this.data,s=this.amountInCents;if(!a)return this.fail("Missing authToken (session) for PagSeguro 3DS");if(!t)return this.fail("Missing card data for PagSeguro 3DS");if(!n)return this.fail("Missing customer data for PagSeguro 3DS");if(!s)return this.fail("Missing amount for PagSeguro 3DS");if(!i)return this.fail("Missing billingAddress for PagSeguro 3DS");const d=this.data.environment===x.Sandbox?"SANDBOX":"PROD";try{await L(Ve)}catch{return this.fail("Failed to load PagSeguro SDK")}const o=window.PagSeguro;if(!o)return this.fail("PagSeguro SDK not available");o.setUp({session:a,env:d});const l=((g=n.phones)==null?void 0:g.map(c=>({country:c.countryCode,area:c.areaCode,number:c.number,type:c.type??"MOBILE"})))??[{country:"55",area:"11",number:"999999999",type:"MOBILE"}];l.some(c=>c.type==="MOBILE")||(l[0].type="MOBILE");try{const c=await o.authenticate3DS({data:{customer:{name:n.name,email:n.email,phones:l},paymentMethod:{type:this.data.installments===0?"DEBIT_CARD":"CREDIT_CARD",installments:this.data.installments??1,card:{number:t.number,expMonth:t.expiration.month,expYear:t.expiration.year,holder:{name:t.holderName}}},amount:{value:s,currency:r??"BRL"},billingAddress:{street:i.street,number:i.number,complement:i.complement,regionCode:i.state,country:i.country.length===2?this.toAlpha3(i.country):i.country,city:i.city,postalCode:i.zipCode.replace(/\D/g,"")},dataOnly:!1}});return c.status==="AUTH_FLOW_COMPLETED"||c.status==="AUTH_NOT_SUPPORTED"?{status:S.Success,dsTransactionId:c.id}:c.status==="CHANGE_PAYMENT_METHOD"?this.fail("PagSeguro requires a different payment method"):{status:S.Success,dsTransactionId:c.id}}catch(c){return this.fail(c instanceof Error?c.message:"PagSeguro 3DS failed")}}cleanup(){}toAlpha3(a){return{BR:"BRA",US:"USA",AR:"ARG",CL:"CHL",CO:"COL",MX:"MEX",PE:"PER",UY:"URY"}[a.toUpperCase()]??a}}const We=5*60*1e3,V="payconductor-3ds-sandbox-title";class Y extends N{constructor(){super(...arguments);C(this,"timeoutId",null)}async authenticate(){const{authToken:t}=this.data;if(!t)return this.fail("Missing authToken for 3DS challenge");const n=this.resolveContainer();return new Promise(r=>{this.timeoutId=setTimeout(()=>{this.cleanup(),r({status:S.Timeout})},this.options.timeoutMs??We),this.renderChallenge(n,{onConfirm:()=>{this.cleanup(),r({status:S.Success,transStatus:R.Authenticated,providerTransactionId:t})},onCancel:()=>{this.cleanup(),r(this.fail("3DS challenge canceled by user",{challengeCanceled:!0}))}})})}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.closeModal()}renderChallenge(t,n){const r=document.createElement("div");r.setAttribute("role","dialog"),r.setAttribute("aria-modal","true"),r.setAttribute("aria-labelledby",V),r.style.cssText="min-height:inherit;box-sizing:border-box;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:16px;padding:32px;font-family:system-ui,-apple-system,sans-serif;text-align:center;color:#111827";const i=document.createElement("h2");i.id=V,i.textContent="Autenticação 3DS (sandbox)",i.style.cssText="margin:0;font-size:20px";const s=document.createElement("p");s.textContent="Simulação do desafio do banco emissor. Confirme para aprovar a autenticação ou cancele para simular a desistência do comprador.",s.style.cssText="margin:0 0 8px;max-width:360px;font-size:14px;line-height:1.5;color:#4b5563";const d=this.createButton("Confirmar autenticação","background:#111827;color:#fff;border-color:#111827",n.onConfirm),o=this.createButton("Cancelar","background:#fff;color:#111827;border-color:#d1d5db",n.onCancel);r.append(i,s,d,o),t.appendChild(r),d.focus()}createButton(t,n,r){const i=document.createElement("button");return i.type="button",i.textContent=t,i.style.cssText=`width:100%;max-width:320px;padding:12px 16px;border:1px solid;border-radius:6px;font:inherit;font-size:14px;font-weight:600;cursor:pointer;${n}`,i.addEventListener("click",r),i}}const Je={[I.Lyra]:je,[I.MercadoPago]:Be,[I.PagarMe]:qe,[I.PagSeguro]:Ye,[I.Sandbox]:Y,[I.SandboxSplit]:Y},Xe=M.replace(/\/sdk\/?$/,"");class ye extends Error{constructor(a,t){super(a),this.title=t,this.name="PayConductorThreeDSApiError"}}class Ze{constructor(a){this.publicKey=a}async completeChallenge(a,t){const n=await fetch(`${M}/three-ds/complete/${a}`,{method:"POST",headers:this.headers,body:JSON.stringify(t)});n.ok||await this.parseResponseError("Falha ao concluir a autenticação 3DS",n)}async getOrderStatus(a){const t=await fetch(`${Xe}/orders/${a}/status`,{method:"GET",headers:this.headers});return t.ok||await this.parseResponseError("Falha ao consultar o status do pedido",t),et(await t.json())}async pollOrderStatus(a,{maxAttempts:t=30,intervalMs:n=2e3,mode:r}={}){let i=null;for(let s=0;s<t;s++){if(i=await this.getOrderStatus(a),!(i.status===_.Pending&&(i.statusDetail===U.ThreeDsAwaitingChallenge||r===F.Auto)))return{order:i,timedOut:!1};await new Promise(o=>setTimeout(o,n))}return{order:i,timedOut:!0}}async getThreeDSecureData(a){const t=await fetch(`${M}/three-ds/challenge/${a}`,{method:"GET",headers:this.headers});t.ok||await this.parseResponseError("Falha ao buscar dados 3DS",t);const n=await t.json(),r=Object.fromEntries(Object.entries(n.threeDSecure??{}).filter(([,i])=>i!=null));return{...r,...n.mode?{mode:n.mode}:{},statusDetail:r.statusDetail??n.statusDetail??void 0}}async parseResponseError(a,t){var r,i,s,d;let n="";try{const o=await t.json();o!=null&&o.message?n=o.message:(r=o==null?void 0:o.error)!=null&&r.message?n=o.error:(s=(i=o==null?void 0:o.error)==null?void 0:i.value)!=null&&s.message?n=o.error.value.message:(d=o==null?void 0:o.value)!=null&&d.message?n=o.value.message:n=JSON.stringify(o)}catch{}throw new ye(n,a)}get headers(){return{Authorization:`Basic ${btoa(`${this.publicKey}:x`)}`,"Content-Type":"application/json"}}}function Qe(e){switch(e){case"Completed":return _.Succeeded;case"Pending":case"Generating":return _.Pending;default:return _.Failed}}function et(e){const a=e??{};return{...a,orderId:a.id??"",status:Qe(a.status),statusDetail:a.statusDetail??void 0,amount:a.amount??0,currency:a.currency??"BRL",errorCode:a.errorCode??void 0,errorMessage:a.errorMessage??void 0,message:a.errorMessage??void 0}}class Ee{constructor(a){C(this,"data");C(this,"provider",null);C(this,"api");this.data=a,this.api=new Ze(this.data.publicKey)}get needsChallenge(){return this.data.status==="NeedChallenge"||this.data.statusDetail==="ThreeDsAwaitingChallenge"}get acquirer(){return this.data.acquirer}static requiresChallenge(a){var t,n,r;return a.statusDetail==="ThreeDsAwaitingChallenge"||((t=a.threeDSecure)==null?void 0:t.status)==="NeedChallenge"||((r=(n=a.creditCard)==null?void 0:n.threeDSecure)==null?void 0:r.status)==="NeedChallenge"}async authenticate(a){var c;try{const m=await this.api.getThreeDSecureData(this.data.orderId);this.data={...this.data,...m}}catch(m){if(m instanceof ye)return{status:S.Failed,error:m};throw m}if(!this.needsChallenge)return{status:S.Success};const{acquirer:t,mode:n}=this.data;if(!t)return this.finish({status:S.Failed,error:new Error("Adquirente 3DS não informada na cobrança"),failureReason:"Adquirente 3DS não informada na cobrança"},a);const r=Je[t];if(!r){const m=`Provedor 3DS não suportado: ${t}`;return this.finish({status:S.Failed,error:new Error(m),failureReason:m},a)}(c=a==null?void 0:a.onChallenge)==null||c.call(a);const i=new r(this.data,{threeDSecure:this.data,timeoutMs:a==null?void 0:a.timeoutMs});this.provider=i;let s;try{s=await i.authenticate()}finally{i.cleanup(),this.provider=null}const d={...s},o=this.deriveFailureReason(s);d.failureReason=o;const l=n?n===F.Manual:this.data.statusDetail===U.ThreeDsAwaitingChallenge;let y;if(l&&(a==null?void 0:a.complete)!==!1)try{await this.api.completeChallenge(this.data.orderId,this.buildCompletionPayload(s,o))}catch(m){y=m}if((a==null?void 0:a.poll)!==!1&&s.status===S.Success){const{order:m,timedOut:P}=await this.api.pollOrderStatus(this.data.orderId,{...a==null?void 0:a.polling,mode:n});d.order=m??void 0,d.timedOut=P}else y&&!d.error&&(d.error=this.toError(y));return this.finish(d,a)}destroy(){this.provider&&(this.provider.cleanup(),this.provider=null)}deriveFailureReason(a){var t;if(a.status!==S.Success)return a.status===S.Timeout?"Tempo da autenticação 3DS esgotado":((t=a.error)==null?void 0:t.message)||"Falha na autenticação 3DS"}buildCompletionPayload(a,t){const n=a.challengeCanceled===!0,r=a.transStatus;return{providerTransactionId:a.providerTransactionId??a.dsTransactionId,transStatus:r,challengeCanceled:n,failureReason:!!t&&!r&&!n?t:void 0}}finish(a,t){var n,r,i;return(n=t==null?void 0:t.onComplete)==null||n.call(t,a),a.failureReason&&((r=t==null?void 0:t.onError)==null||r.call(t,new Error(a.failureReason))),(a.status===S.Timeout||a.timedOut)&&((i=t==null?void 0:t.onTimeout)==null||i.call(t)),a}toError(a){return a instanceof Error?a:new Error("Falha ao concluir a autenticação 3DS")}}function tt(e){let a=null;return{authenticate:async r=>{const i=new Ee(r);a=i;try{return await i.authenticate({onChallenge:e==null?void 0:e.onChallenge,onComplete:e==null?void 0:e.onComplete,onError:e==null?void 0:e.onError,onTimeout:e==null?void 0:e.onTimeout,complete:e==null?void 0:e.complete,poll:e==null?void 0:e.poll,polling:e==null?void 0:e.polling})}finally{i.destroy(),a=null}},destroy:()=>{a==null||a.destroy(),a=null}}}class at extends Error{constructor(a,t){super(a),this.title=t,this.name="PayConductorTokenizerApiError"}}class nt{constructor(a){this.publicKey=a}async getSettings(){const a=await fetch(`${M}/card-tokenization/settings`,{method:"GET",headers:this.headers});return a.ok||await this.parseResponseError("Failed to fetch settings",a),await a.json()}async createToken(a){const t=await fetch(`${M}/card-tokenization/tokenize`,{method:"POST",headers:this.headers,body:JSON.stringify(a)});return t.ok||await this.parseResponseError("Failed to generate token",t),await t.json()}async saveTokens(a,t,n){const r=await fetch(`${M}/card-tokenization/save-tokens/${t}/${n}`,{method:"POST",headers:this.headers,body:JSON.stringify(a)});r.ok||await this.parseResponseError("Failed to save tokens",r)}async parseResponseError(a,t){var r,i,s,d;let n="";try{const o=await t.json();o!=null&&o.message?n=o.message:(r=o==null?void 0:o.error)!=null&&r.message?n=o.error:(s=(i=o==null?void 0:o.error)==null?void 0:i.value)!=null&&s.message?n=o.error.value.message:(d=o==null?void 0:o.value)!=null&&d.message?n=o.value.message:n=JSON.stringify(o)}catch{}throw new at(n,a)}get headers(){return{Authorization:`Basic ${btoa(`${this.publicKey}:x`)}`,"Content-Type":"application/json"}}}class rt{constructor(a){this.input=a}}class it extends rt{constructor(){super(...arguments);C(this,"scriptUrl","https://sdk.mercadopago.com/js/v2")}async tokenize(){const{publicKey:t}=this.input.setting;if(typeof t!="string"||!t.trim())throw new Error("MercadoPago public key is missing in settings");if(!this.input.customer.documentNumber)throw new Error("Customer document number is required for tokenization");const n=window.MercadoPago;if(!n)throw new Error("MercadoPago SDK not available");const r=new n(t.trim()),{expiration:i,cvv:s,number:d,holderName:o}=this.input.card,l=await r.createCardToken({cardExpirationMonth:String(i.month).padStart(2,"0"),cardExpirationYear:String(i.year),cardholderName:o,cardNumber:d,securityCode:s,identificationType:this.input.customer.documentType===$.Cpf?"CPF":"CNPJ",identificationNumber:this.input.customer.documentNumber}).catch(y=>{throw new Error(this.describeMercadoPagoError(y))});if("id"in l&&l.id)return l.id;throw new Error(this.describeMercadoPagoError(l))}describeMercadoPagoError(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(n=>this.describeMercadoPagoError(n)).join("; ");if(typeof t=="object"&&t!==null){if("cause"in t&&Array.isArray(t.cause)&&t.cause.length>0)return this.describeMercadoPagoError(t.cause);if("message"in t&&typeof t.message=="string")return t.message;if("description"in t&&typeof t.description=="string")return t.description}return"Failed to tokenize card"}}const ot={[I.MercadoPago]:it};class ge{constructor(a){C(this,"api");this.publicKey=a,this.api=new nt(this.publicKey)}async tokenizeCard(a){this.validateCard(a);const{customerId:t,token:n}=await this.api.createToken({card:a.card,customer:a.customer,saveCard:!1}),{settings:r}=await this.api.getSettings(),s=(await Promise.all(r.map(async d=>{const o=ot[d.key];if(!o)return null;const l=new o({...a,setting:d.settings});return await L(l.scriptUrl),{token:await l.tokenize(),integrationId:d.integrationId,providerKey:d.key}}))).filter(d=>d!==null);return s.length>0&&await this.api.saveTokens(s,t,n),n}validateCard(a){const{number:t,cvv:n,expiration:r,holderName:i}=a.card;if(!t||!n||!(r!=null&&r.month)||!(r!=null&&r.year)||!i)throw new Error("Invalid card data")}}function st(e){const a=new ge(e.publicKey);return{tokenizeCard:async n=>{var r,i;try{const s=await a.tokenizeCard(n);return(r=e.onSuccess)==null||r.call(e,s),s}catch(s){const d=s instanceof Error?s:new Error("Tokenization failed");return(i=e.onError)==null||i.call(e,d),null}}}}exports.ALLOWED_ORIGINS=de;exports.CardBrand=te;exports.ChargeStatusDetail=U;exports.CurrencyType=ae;exports.DeviceType=ne;exports.DocumentType=$;exports.ERROR_CODES=ve;exports.ErrorCode=ie;exports.IFRAME_BASE_URL=se;exports.IFRAME_DEFAULT_HEIGHT_VALUE=j;exports.IncomingMessage=A;exports.InputStyleKey=re;exports.IntegrationProvider=I;exports.OrganizationEnvironment=x;exports.OutgoingMessage=D;exports.POST_MESSAGES=w;exports.PayConductor=fe;exports.PayConductor3DSSDK=Ee;exports.PayConductorCheckoutElement=ke;exports.PayConductorThreeDSElement=Ne;exports.PayConductorTokenizerSDK=ge;exports.PaymentMethod=X;exports.PaymentMethodLayout=Z;exports.PaymentStatus=_;exports.REQUEST_TIMEOUT=ce;exports.SDK_API_BASE_URL=M;exports.SKELETON_CSS=le;exports.SKELETON_STYLE_ID=H;exports.ThreeDSMode=F;exports.ThreeDSResultStatus=ee;exports.ThreeDSTransStatus=R;exports.ThreeDSecureResultStatus=S;exports.ThreeDsAuthenticationStatus=Q;exports.buildIframeUrl=ue;exports.default=fe;exports.defaultTheme=pe;exports.generateRequestId=he;exports.isValidOrigin=me;exports.loadScript=L;exports.usePayConductor=Le;exports.usePayconductorElement=Ue;exports.useThreeDS=tt;exports.useTokenizer=st;
49
49
  //# sourceMappingURL=index.cjs.js.map