@flopay/react 1.20.14 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +107 -390
  2. package/dist/card-setup-entry.cjs +1 -6
  3. package/dist/card-setup-entry.d.ts +4 -10
  4. package/dist/card-setup-entry.mjs +1 -1
  5. package/dist/chunk-KPRDVWZP.mjs +1 -0
  6. package/dist/chunk-XRYDC367.mjs +1 -0
  7. package/dist/flopay-runtime-card-setup.d.ts +4 -5
  8. package/dist/flopay-runtime-checkout.d.ts +2 -0
  9. package/dist/hosted-runtime-components.d.ts +75 -0
  10. package/dist/index.cjs +1 -47
  11. package/dist/index.d.ts +3 -21
  12. package/dist/index.mjs +1 -21
  13. package/dist/payment-method-setup-entry.cjs +1 -27
  14. package/dist/payment-method-setup-entry.d.ts +5 -12
  15. package/dist/payment-method-setup-entry.mjs +1 -1
  16. package/dist/runtime-context.d.ts +10 -0
  17. package/package.json +3 -6
  18. package/dist/account-bound-elements.d.ts +0 -31
  19. package/dist/automatic-payment-button.d.ts +0 -88
  20. package/dist/buyer-identity-fallback.d.ts +0 -43
  21. package/dist/card-button-content.d.ts +0 -11
  22. package/dist/card-setup-surface.d.ts +0 -12
  23. package/dist/card-setup-theme.d.ts +0 -32
  24. package/dist/checkout-utils.d.ts +0 -172
  25. package/dist/chunk-BU7THP6H.mjs +0 -1
  26. package/dist/chunk-FGCZOMML.mjs +0 -22
  27. package/dist/chunk-ITRFSHZP.mjs +0 -6
  28. package/dist/chunk-PCIHQY3X.mjs +0 -1
  29. package/dist/chunk-VK67324N.mjs +0 -1
  30. package/dist/context.d.ts +0 -46
  31. package/dist/direct-paypal-button.d.ts +0 -155
  32. package/dist/error-banner.d.ts +0 -21
  33. package/dist/external-method-recovery.d.ts +0 -1
  34. package/dist/external-method-telemetry.d.ts +0 -17
  35. package/dist/flopay-card-setup.d.ts +0 -114
  36. package/dist/flopay-checkout.d.ts +0 -292
  37. package/dist/flopay-payment-method-setup-main.d.ts +0 -10
  38. package/dist/flopay-payment-method-setup.d.ts +0 -11
  39. package/dist/hooks.d.ts +0 -36
  40. package/dist/in-app-browser.d.ts +0 -5
  41. package/dist/inline-session-cache.d.ts +0 -1
  42. package/dist/instruments.d.ts +0 -5
  43. package/dist/more-payment-options.d.ts +0 -19
  44. package/dist/one-click-warnings.d.ts +0 -12
  45. package/dist/payment-logos.generated.d.ts +0 -1
  46. package/dist/payment-method-layout-placeholder.d.ts +0 -10
  47. package/dist/payment-method-setup-advertisement.d.ts +0 -36
  48. package/dist/payment-method-setup-paypal-CLV7JDJH.mjs +0 -1
  49. package/dist/payment-method-setup-paypal.d.ts +0 -25
  50. package/dist/payment-method-setup-stripe-526L4P5X.mjs +0 -1
  51. package/dist/payment-method-setup-stripe.d.ts +0 -31
  52. package/dist/payment-method-setup-surface.d.ts +0 -90
  53. package/dist/popup-capability.d.ts +0 -12
  54. package/dist/processing-overlay.d.ts +0 -33
  55. package/dist/provider-callback-ignored.d.ts +0 -8
  56. package/dist/provider.d.ts +0 -40
  57. package/dist/recent-completion.d.ts +0 -1
  58. package/dist/run-latest-abortable-action.d.ts +0 -5
  59. package/dist/saved-payment-flow.d.ts +0 -140
  60. package/dist/split-card-form.d.ts +0 -393
  61. package/dist/stripe-method-presentation.d.ts +0 -115
  62. package/dist/telemetry-bridge.d.ts +0 -41
  63. package/dist/use-external-attempt-reconciliation.d.ts +0 -27
  64. package/dist/use-isomorphic-layout-effect.d.ts +0 -3
  65. package/dist/use-payment-method-layout.d.ts +0 -27
  66. package/dist/vault-card-fields.d.ts +0 -97
  67. package/dist/vault-theme.d.ts +0 -1
@@ -1,27 +1 @@
1
- "use strict";var jt=Object.create;var xe=Object.defineProperty;var $t=Object.getOwnPropertyDescriptor;var Zt=Object.getOwnPropertyNames;var Jt=Object.getPrototypeOf,Qt=Object.prototype.hasOwnProperty;var Se=(e,r,t)=>()=>{if(t)throw t[0];try{return e&&(r=e(e=0)),r}catch(o){throw t=[o],o}};var Oe=(e,r)=>{for(var t in r)xe(e,t,{get:r[t],enumerable:!0})},dt=(e,r,t,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of Zt(r))!Qt.call(e,s)&&s!==t&&xe(e,s,{get:()=>r[s],enumerable:!(o=$t(r,s))||o.enumerable});return e};var er=(e,r,t)=>(t=e!=null?jt(Jt(e)):{},dt(r||!e||!e.__esModule?xe(t,"default",{value:e,enumerable:!0}):t,e)),tr=e=>dt(xe({},"__esModule",{value:!0}),e);var b,Ve=Se(()=>{"use strict";b=require("@flopay/shared")});var mr,we,Te,Ne=Se(()=>{"use strict";mr=require("@flopay/shared"),we=require("@flopay/shared"),Te=require("@flopay/shared")});var Ct,Pt=Se(()=>{"use strict";Ct={alipay:"https://cdn.flopay.com/sdk-logos/v1/alipay.svg",bancontact:"https://cdn.flopay.com/sdk-logos/v1/bancontact.svg",blik:"https://cdn.flopay.com/sdk-logos/v1/blik.svg",eps:"https://cdn.flopay.com/sdk-logos/v1/eps.svg",giropay:"https://cdn.flopay.com/sdk-logos/v1/giropay.svg",ideal:"https://cdn.flopay.com/sdk-logos/v1/ideal.svg",klarna:"https://cdn.flopay.com/sdk-logos/v1/klarna.svg",p24:"https://cdn.flopay.com/sdk-logos/v1/p24.svg",sepa_debit:"https://cdn.flopay.com/sdk-logos/v1/sepa_debit.svg",wechat_pay:"https://cdn.flopay.com/sdk-logos/v1/wechat_pay.svg"}});function Et(){return(0,x.jsx)("style",{children:yr})}function wt(e,r){let t=e.availablePaymentMethods;return t&&r.some(o=>t[o])?"ready":"unavailable"}function Rt({state:e,placeholderTestId:r,borderRadius:t=8,children:o}){return e==="unavailable"||e==="load_error"?null:(0,x.jsxs)("div",{style:{position:"relative",minHeight:44},children:[(0,x.jsx)("div",{"data-testid":r,"aria-hidden":e==="ready",style:{position:"absolute",inset:0,height:44,borderRadius:t,background:"#e5e7eb",animation:e==="ready"?void 0:"flopay-pulse 1.5s ease-in-out infinite",opacity:e==="ready"?0:1,transform:e==="ready"?"scale(0.985)":"scale(1)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:"none"}}),(0,x.jsx)("div",{style:{minHeight:44,opacity:e==="ready"?1:0,transform:e==="ready"?"translateY(0)":"translateY(2px)",transition:"opacity 140ms ease-out, transform 140ms ease-out",pointerEvents:e==="ready"?"auto":"none"},children:o})]})}function kt({method:e,themeId:r,submitting:t=!1,disabled:o=!1,highlighted:s=!1,hasNextStep:u=!1,onClick:i,backgroundColor:c,borderColor:y,textColor:_,borderRadius:L,fontFamily:Y}){let v=(0,ne.resolveStripeMethodBrandVariant)(e,r),B=Ct[e],[C,F]=(0,bt.useState)(!1),m=!!B&&!C,T=v?.backgroundColor??c??"#ffffff",f=v?.borderColor??y??"#d1d5db",A=v?.textColor??_??"#262833";return(0,x.jsx)("button",{type:"button","data-testid":`flopay-stripe-method-button-${e}`,"data-method":e,onClick:()=>{!t&&!o&&i()},disabled:t||o,"aria-busy":t||void 0,style:{position:"relative",width:"100%",boxSizing:"border-box",height:fr,padding:"0 1rem",backgroundColor:T,color:A,border:`1px solid ${f}`,borderRadius:L??8,fontSize:"0.95rem",fontWeight:600,fontFamily:Y,cursor:t||o?"not-allowed":"pointer",opacity:o&&!t?.55:1,animation:t?"flopay-pulse 1.5s ease-in-out infinite":void 0,display:"flex",alignItems:"center",justifyContent:"center",gap:8,transition:"transform 0.1s, opacity 140ms ease-out, border-color 140ms ease-out",boxShadow:s?"0 0 0 2px rgba(74, 73, 255, 0.15)":void 0},children:t?(0,x.jsx)("span",{style:{margin:"0 auto"},children:`Connecting to ${(0,ne.getStripeMethodDisplayName)(e)}\u2026`}):(0,x.jsxs)(x.Fragment,{children:[(0,x.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:(0,ne.hasVendoredStripeMethodLogo)(e)?8:0},children:[m?(0,x.jsx)("img",{src:B,alt:"","aria-hidden":"true",onError:()=>F(!0),loading:"lazy",decoding:"async",width:30,height:20,style:{width:30,height:20,flexShrink:0,borderRadius:3,objectFit:"contain",display:"inline-flex"}}):null,!m&&v?.logoSvg?(0,x.jsx)("span",{"aria-hidden":"true",style:{width:30,height:20,flexShrink:0,display:"inline-flex",borderRadius:3,overflow:"hidden"},dangerouslySetInnerHTML:{__html:v.logoSvg}}):null,(0,x.jsx)("span",{children:(0,ne.getStripeMethodDisplayName)(e)})]}),u&&(0,x.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:A,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{position:"absolute",right:"1rem",top:"50%",transform:"translateY(-50%)",flexShrink:0,opacity:.7},"aria-hidden":"true",children:(0,x.jsx)("path",{d:"M9 18l6-6-6-6"})})]})})}function xt(e){let r=new Set(e.map(ne.stripeExpressMethodToOptionKey));return Object.fromEntries(["applePay","googlePay","paypal","link","amazonPay","klarna"].map(t=>[t,r.has(t)?"auto":"never"]))}function Ft({testId:e,attributes:r,disabled:t,onClick:o,color:s,borderRadius:u,style:i,children:c}){return(0,x.jsx)("button",{type:"button","data-testid":e,...r,onClick:o,disabled:t,style:{width:"100%",marginTop:"0.75rem",padding:"0.875rem",backgroundColor:s,color:"white",border:"none",borderRadius:u,fontSize:"1rem",fontWeight:600,cursor:t?"not-allowed":"pointer",opacity:t?.5:1,transition:"opacity 120ms ease-out",...i??{}},children:c})}var ne,bt,x,yr,fr,Mt,_t,Tt=Se(()=>{"use strict";ne=require("@flopay/shared"),bt=require("react");Pt();x=require("react/jsx-runtime"),yr=`
2
- .paypal-buttons { margin: 0 !important; vertical-align: top !important; }
3
- @keyframes flopay-spin { to { transform: rotate(360deg); } }
4
- @keyframes flopay-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
5
- @keyframes flopay-fade-in { 0% { opacity: 0; } 100% { opacity: 1; } }
6
- @keyframes flopay-buttons-enter {
7
- 0% { opacity: 0; transform: translateX(-16px) scale(0.97); }
8
- 100% { opacity: 1; transform: translateX(0) scale(1); }
9
- }
10
- @keyframes flopay-buttons-exit {
11
- 0% { opacity: 1; transform: translateX(0) scale(1); }
12
- 100% { opacity: 0; transform: translateX(-16px) scale(0.97); }
13
- }
14
- @keyframes flopay-card-enter {
15
- 0% { opacity: 0; transform: translateX(16px) scale(0.97); }
16
- 100% { opacity: 1; transform: translateX(0) scale(1); }
17
- }
18
- @keyframes flopay-card-exit {
19
- 0% { opacity: 1; transform: translateX(0) scale(1); }
20
- 100% { opacity: 0; transform: translateX(16px) scale(0.97); }
21
- }
22
- `,fr=44;Mt={buttonType:{applePay:"plain",googlePay:"plain"},layout:{maxColumns:1,overflow:"never"}},_t={type:"accordion",defaultCollapsed:!1,radios:"never"}});var It={};Oe(It,{StripeSetupMethod:()=>Pr});function hr(e){let r=Ye.get(e);if(r)return r;let t=(0,Lt.loadStripe)(e).catch(o=>{throw Ye.delete(e),o});return Ye.set(e,t),t}function gr(e){return e?(0,K.toStripeAppearance)(e):void 0}function Sr(e){return(0,b.isProviderDecline)(e)||e.code==="setup_intent_authentication_failure"||e.code==="payment_method_provider_decline"}function At(e){return e==="paypal"?"PayPal":(0,K.getStripeMethodDisplayName)(e)}function vr(){return typeof window>"u"?"":window.location.href}function Pr(e){let{publishableKey:r,method:t,currency:o,futureUse:s,futureUseUnsupported:u,appearance:i}=e,[c]=(0,V.useState)(()=>hr(r)),y=(0,V.useMemo)(()=>{let _=gr(i),L=(0,K.resolveSetupFutureUsage)({futureUse:s,futureUseUnsupported:u},t,"setup");return{mode:"setup",currency:o.toLowerCase(),allowedPaymentMethodTypes:Bt[t]?.types??[t],...L?{setupFutureUsage:L}:{},..._?{appearance:_}:{}}},[i,o,s,u,t]);return(0,O.jsx)(ee.Elements,{stripe:c,options:y,children:(0,O.jsx)(br,{...e})})}function br({method:e,category:r,sessionId:t,nonce:o,billingApiUrl:s,telemetry:u,appearance:i,themeId:c,buttonsLayout:y,onSubmitting:_,onConfirmed:L,onDeclined:Y,onFailed:v,onValidation:B,onUnavailable:C}){let F=(0,ee.useStripe)(),m=(0,ee.useElements)(),[T,f]=(0,V.useState)(!1),[A,W]=(0,V.useState)("loading"),[N,E]=(0,V.useState)(!1),[g,w]=(0,V.useState)(!1),q=(0,V.useRef)(!1),[J]=(0,V.useState)(()=>(0,we.detectPayPalEnvironment)()),[ye,te]=(0,V.useState)(!1),R=(0,V.useCallback)((M,I)=>{if((0,b.classifyExternalMethodFailure)(M,{inAppBrowser:J.inAppBrowser,handoffObserved:!1}).popupBlocked){te(!0),v(new Error((0,b.buildExternalMethodRecoveryMessage)(At(e),!0,J.inAppBrowser)),{code:"popup_blocked",retryable:!0});return}v(I.message===void 0?M:new Error(I.message),{code:I.code,retryable:!0})},[J.inAppBrowser,e,v]),z=(0,V.useCallback)(async M=>{let I=!1,ie=!1,le=()=>{!M||I||ie||(ie=!0,M.paymentFailed({reason:"fail"}))};if(!F||!m||q.current){le();return}q.current=!0,f(!0);try{let oe=await m.submit();if(oe.error){le(),B(oe.error.message??null);return}_();let $=await new Ot.PaymentAPI(s,{telemetry:u}).createSessionIntent(t,o,{provider:"stripe",paymentMethodCategory:r,paymentMethodType:e,paymentMethodId:null,intentKind:"setup"});if((0,K.isSettledSessionIntent)($))throw(0,K.settledSessionIntentError)(t);if($.provider!=="stripe"||$.intentKind!=="setup")throw new K.FloPayError("The billing API returned a non-setup intent.","api_error",{code:"InvalidSessionIntentResponse"});I=!0;let G=await F.confirmSetup({elements:m,clientSecret:$.clientSecret,confirmParams:{return_url:vr()},redirect:"if_required"});if(G.error){Sr(G.error)?Y({...G.error.decline_code||G.error.code?{reason:G.error.decline_code??G.error.code}:{},...G.error.message?{message:G.error.message}:{}}):R(G.error,{code:"payment_method_setup_provider_failed",message:G.error.message??"The payment method could not be saved."});return}L()}catch(oe){le(),R(oe,{code:"payment_method_setup_failed"})}finally{q.current=!1,f(!1)}},[s,r,m,e,o,L,Y,_,B,R,t,F,u]),se=Bt[e]?.wallet,re=se==="paypal"&&(0,Te.resolveStripePayPalPresentation)(J,"auto",ye?"blocked":J.popupCapability)==="redirect",fe=i?.variables?.borderRadius??y?.cardButton?.borderRadius??8;if(r==="wallet"&&se&&!re)return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(Et,{}),(0,O.jsx)(Rt,{state:A,borderRadius:fe,children:(0,O.jsx)(ee.ExpressCheckoutElement,{options:{...Mt,paymentMethods:xt([e])},onReady:M=>{let I=wt(M,[se]);W(I),I==="unavailable"&&C()},onLoadError:()=>{W("load_error"),C()},onConfirm:M=>{z(M)}})})]});let j=At(e);return(0,O.jsxs)(O.Fragment,{children:[N?(0,O.jsx)(kt,{method:e,themeId:c,hasNextStep:!0,highlighted:g,disabled:T,onClick:()=>w(M=>!M),backgroundColor:y?.cardButton?.backgroundColor,borderColor:y?.cardInputBorder,textColor:y?.cardButton?.color,borderRadius:fe}):null,(0,O.jsxs)("div",{"data-testid":`flopay-stripe-method-form-${e}`,"aria-hidden":!g,style:g?{display:"flex",flexDirection:"column"}:Cr,children:[(0,O.jsx)(ee.PaymentElement,{options:{layout:_t},onReady:()=>E(!0),onLoadError:()=>C(),onChange:M=>{M.complete&&B(null)}}),(0,O.jsx)(Ft,{testId:`flopay-payment-method-save-${e}`,attributes:{"data-flopay-payment-method-save":e},disabled:!F||!m||T||!g,onClick:()=>{z()},color:i?.variables?.colorPrimary??"#4A49FF",borderRadius:i?.variables?.borderRadius??"8px",style:y?.submitButton,children:T?"Saving\u2026":`Save ${j}`})]})]})}var Ot,K,ee,Lt,V,O,Bt,Ye,Cr,Ut=Se(()=>{"use strict";Ot=require("@flopay/js/card-setup"),K=require("@flopay/shared"),ee=require("@stripe/react-stripe-js"),Lt=require("@stripe/stripe-js"),V=require("react");Ve();Ne();Tt();O=require("react/jsx-runtime"),Bt={apple_pay:{types:["card"],wallet:"applePay"},google_pay:{types:["card"],wallet:"googlePay"},link:{types:["link"],wallet:"link"},paypal:{types:["paypal"],wallet:"paypal"},amazon_pay:{types:["amazon_pay"],wallet:"amazonPay"}},Ye=new Map;Cr={position:"absolute",width:"100%",height:0,overflow:"hidden",visibility:"hidden",pointerEvents:"none"}});var Nt={};Oe(Nt,{PayPalSetupMethod:()=>Er});function Er({clientId:e,environment:r,currency:t,sessionId:o,nonce:s,billingApiUrl:u,telemetry:i,customer:{userId:c,email:y},onSubmitting:_,onConfirmed:L,onFailed:Y,onAbandoned:v}){let B=(0,me.useRef)(null),C=(0,me.useRef)({onSubmitting:_,onConfirmed:L,onFailed:Y,onAbandoned:v});C.current={onSubmitting:_,onConfirmed:L,onFailed:Y,onAbandoned:v};let[F]=(0,me.useState)(()=>(0,we.detectPayPalEnvironment)().inAppBrowser);return(0,me.useEffect)(()=>{let m=!0,T,f=new Dt.PaymentAPI(u,{telemetry:i}),A={userId:c,email:y};return(async()=>{try{let W=await(0,Vt.loadScript)({clientId:e,...t?{currency:t.toUpperCase()}:{},components:"buttons",...r==="sandbox"||r==="production"?{environment:r}:{}}),N=B.current;if(!m||!N)return;if(!W?.Buttons)throw new X.FloPayError("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let E=W.Buttons({createVaultSetupToken:async()=>{C.current.onSubmitting();let g=await f.createSessionIntent(o,s,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:X.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE,paymentMethodId:null,intentKind:"setup"});if((0,X.isSettledSessionIntent)(g))throw(0,X.settledSessionIntentError)(o);if(g.provider!=="paypal"||g.providerObjectType!=="setup_token")throw new X.FloPayError("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return g.providerObjectId},onApprove:async g=>{let w=g.vaultSetupToken;if(!w)throw new X.FloPayError("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let q=await f.processPayment(A.userId,{sessionId:o,nonce:s,paymentMethodCategory:"paypal",tokenizedData:{id:w,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:X.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE},accountData:A});if(!q.ok)throw new X.FloPayError("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:q.status});m&&C.current.onConfirmed()},onCancel:()=>{m&&C.current.onAbandoned()},onError:g=>{if(!m)return;let{popupBlocked:w}=(0,b.classifyExternalMethodFailure)(g,{inAppBrowser:F,handoffObserved:!1});C.current.onFailed(w?new Error((0,b.buildExternalMethodRecoveryMessage)("PayPal",!0,F)):g,{code:w?"popup_blocked":"paypal_setup_failed",retryable:!0})}});T=()=>E.close(),await E.render(N)}catch(W){if(!m)return;C.current.onFailed(W,{code:"paypal_unavailable",retryable:!0})}})(),()=>{m=!1,T?.().catch(()=>{}),f.destroy()}},[u,e,t,y,r,F,s,o,i,c]),(0,Yt.jsx)("div",{ref:B,"data-flopay-paypal-setup":""})}var Dt,X,Vt,me,Yt,Wt=Se(()=>{"use strict";Dt=require("@flopay/js/card-setup"),X=require("@flopay/shared"),Vt=require("@paypal/paypal-js"),me=require("react");Ve();Ne();Yt=require("react/jsx-runtime")});var Rr={};Oe(Rr,{FloPayCardSetupError:()=>be,FloPayPaymentMethodSetup:()=>zt});module.exports=tr(Rr);var gt=require("@flopay/js/card-setup"),pe=require("@flopay/shared"),_e=require("react");var Le=require("@flopay/shared"),rr=new Set(["animationIterationCount","aspectRatio","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","columns","flex","flexGrow","flexPositive","flexShrink","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","fontWeight","lineClamp","lineHeight","opacity","order","orphans","scale","tabSize","widows","zIndex","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth"]);function or(e){let r=e.replace(/^(Webkit|Moz|ms)(?=[A-Z])/,"");return rr.has(r.charAt(0).toLowerCase()+r.slice(1))}function nr(e,r){return typeof r=="number"&&r!==0&&!or(e)?`${r}px`:String(r).trim()}function pt(e,r){if(e.style.cssText="",!!r){for(let[t,o]of Object.entries(r))if(!(o==null||o==="")){if(t.startsWith("--")){e.style.setProperty(t,String(o));continue}e.style[t]=nr(t,o)}}}var Be=require("@flopay/shared"),ar=require("@flopay/shared");function ct(e){let r=(0,Be.resolveCardSetupTheme)(e);return{...r,surface:r.surface,overlayTheme:r.overlayTheme}}var Q=require("@flopay/shared");var S=require("react/jsx-runtime");var sr={panel:{background:"white"},spinnerTrackColor:"#e5e7eb",spinnerAccentColor:"#4A49FF",labelColors:{processing:"#374151",success:"#16a34a",error:"#dc2626"},noteColor:"#6b7280"};function mt({status:e,errorMessage:r,authorized:t=!1,processingLabel:o="PROCESSING...",successLabel:s,errorLabel:u="PAYMENT FAILED",successNote:i="You will be automatically redirected, do not close or navigate away from this window.",theme:c=sr}){let y={fontSize:13,color:c.noteColor,fontWeight:400,maxWidth:260,lineHeight:1.4,margin:0};return(0,S.jsx)("div",{"data-testid":"flopay-processing-overlay","data-status":e,role:"dialog","aria-modal":"true",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,backdropFilter:"blur(2px)"},children:(0,S.jsxs)("div",{"data-testid":"flopay-processing-overlay-panel",style:{borderRadius:12,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",...c.panel,padding:"2rem 2.5rem",textAlign:"center",minWidth:240,display:"flex",flexDirection:"column",alignItems:"center",gap:16},children:[(0,S.jsxs)("div",{style:{width:48,height:48,position:"relative"},children:[e==="processing"&&(0,S.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{animation:"flopay-spin 0.8s linear infinite"},children:[(0,S.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:c.spinnerTrackColor,strokeWidth:"3"}),(0,S.jsx)("path",{d:"M4 12a8 8 0 018-8v3a5 5 0 00-5 5H4z",fill:c.spinnerAccentColor})]}),e==="success"&&(0,S.jsx)("div",{style:{animation:"flopay-pop 0.4s cubic-bezier(0.34,1.56,0.64,1)"},children:(0,S.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,S.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#22c55e"}),(0,S.jsx)("path",{d:"M7 12.5l3 3 7-7",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:20,strokeDashoffset:20,animation:"flopay-draw 0.4s 0.15s ease forwards"}})]})}),e==="error"&&(0,S.jsx)("div",{style:{animation:"flopay-shake 0.4s ease"},children:(0,S.jsxs)("svg",{"aria-hidden":"true",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[(0,S.jsx)("circle",{cx:"12",cy:"12",r:"11",fill:"#ef4444"}),(0,S.jsx)("path",{d:"M8 8l8 8M16 8l-8 8",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",style:{strokeDasharray:12,strokeDashoffset:12,animation:"flopay-draw 0.3s 0.1s ease forwards"}})]})})]}),(0,S.jsxs)("span",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.05em",color:c.labelColors[e]},children:[e==="processing"&&o,e==="success"&&(s??(t?"PAYMENT AUTHORISED":"PAYMENT SUCCESSFUL")),e==="error"&&u]}),e==="success"&&i!==null&&(0,S.jsx)("p",{style:y,children:i}),e==="error"&&r&&(0,S.jsx)("p",{style:y,children:r}),(0,S.jsx)("style",{children:`
23
- @keyframes flopay-spin { to { transform: rotate(360deg); } }
24
- @keyframes flopay-pop { 0% { transform: scale(0); } 100% { transform: scale(1); } }
25
- @keyframes flopay-draw { to { stroke-dashoffset: 0; } }
26
- @keyframes flopay-shake { 0%,100% { transform: translateX(0); } 20%,60% { transform: translateX(-4px); } 40%,80% { transform: translateX(4px); } }
27
- `})]})})}var H=require("react");var Me=require("react"),yt=typeof window>"u"?Me.useEffect:Me.useLayoutEffect;var de=require("react/jsx-runtime"),Ie=new WeakSet;function ft({capture:e,html:r,messageToken:t,expectedOrigin:o,expiresAt:s,verificationRequired:u,theme:i,submitLabel:c,containerStyle:y,onReady:_,onError:L,onValidation:Y}){let v=(0,H.useRef)(null),B=(0,H.useRef)(_),C=(0,H.useRef)(L),F=(0,H.useRef)(Y);B.current=_,C.current=L,F.current=Y;let m=(0,H.useRef)(i);m.current=i;let T=(0,H.useRef)(null),f=c??void 0,A=(0,H.useRef)(f);A.current=f;let W=(0,H.useRef)(void 0);return(0,H.useEffect)(()=>{let N=v.current;if(!N)return;let E=!0,g=!1,w=()=>{!E||g||(g=!0,B.current?.())},q=e.on("ready",()=>{w()}),J=e.on("error",z=>{C.current?.(z.message??"There was a problem loading the secure card form.")}),ye=e.on("validation",z=>{F.current?.(z.message??null)}),te=A.current??(Ie.has(e)?null:void 0),R={html:r,...t?{messageToken:t}:{},...o?{expectedOrigin:o}:{},...typeof s=="string"?{expiresAt:s}:{},...u?{verificationRequired:!0}:{},...m.current?{theme:m.current}:{},...te===void 0?{}:{submitLabel:te}};return T.current=m.current??null,W.current=A.current,A.current!==void 0&&Ie.add(e),e.mount(N,R).then(()=>{w()}).catch(z=>{E&&C.current?.(z instanceof Error?z.message:"Failed to load the secure card form.")}),()=>{E=!1,q(),J(),ye(),e.unmount()}},[e,r,t,o,s,u]),yt(()=>{let N=v.current;N&&pt(N,y)},[y]),(0,H.useEffect)(()=>{i!==void 0&&(i===null&&T.current===null||(T.current=i,e.applyTheme?.(i)))},[e,i]),(0,H.useEffect)(()=>{f!==W.current&&(W.current=f,f!==void 0&&Ie.add(e),e.setSubmitLabel?.(f??null))},[e,f]),(0,de.jsx)("div",{ref:v,"data-testid":"flopay-vault-card-fields"})}function ht({label:e}){return(0,de.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem",margin:"0.5rem 0 0.75rem",color:"#999",fontSize:"0.85rem"},children:[(0,de.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}}),(0,de.jsx)("span",{children:e}),(0,de.jsx)("div",{style:{flex:1,height:1,backgroundColor:"#ddd"}})]})}var Ue=require("react/jsx-runtime"),be=class extends pe.FloPayError{constructor(r,t,o){super(r,t,o),this.name="FloPayCardSetupError",this.retryable=o.retryable}};function ce(e,r={}){let t=e instanceof pe.FloPayError?e:void 0,o=t?.statusCode,s=r.retryable??(t?.type==="network_error"||t?.type==="rate_limit_error"||typeof o=="number"&&o>=500||t?.code==="vault_capture_timeout"||!t);return new be(t?.message??(e instanceof Error?e.message:"Failed to load the secure card form."),t?.type??"api_error",{code:r.code??t?.code??"card_setup_load_failed",retryable:s,...t?.param?{param:t.param}:{},...o===void 0?{}:{statusCode:o}})}var We=require("react");var Ee=require("@flopay/js/card-setup"),P=require("@flopay/shared"),a=er(require("react"),1);var ve=require("@flopay/js/card-setup"),k=require("@flopay/shared");var h=require("react/jsx-runtime"),lr=15,ur=2e3;function dr(e){return{userId:e.customer?.id??"",email:e.customer?.email??""}}function De(e){return new Promise(r=>setTimeout(r,e))}async function pr(e,r,t){if(!r.trim())throw new P.FloPayError("FloPayPaymentMethodSetup requires a sessionId.","validation_error",{code:"MissingCheckoutSessionId",param:"sessionId"});if(!t.trim())throw new P.FloPayError("FloPayPaymentMethodSetup requires a session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=await e.getUnifiedCheckoutSession(r,t),s=o.data.session;if(!s||!(0,P.isCardSetupCheckoutSession)(s))throw new P.FloPayError("FloPayPaymentMethodSetup only accepts a zero-amount, productless setup session.","validation_error",{code:"InvalidPaymentMethodSetupSession",param:"sessionId"});let u=(0,k.readSetupAdvertisement)(o);if(!(0,k.advertisesAnyMethod)(u)){let{skippedForMissingCurrency:i}=u,c=i.length>0?`FloPay: this setup session advertises only Stripe methods (${i.join(", ")}), and they need the session's currency, which the setup-session read did not carry.`:"FloPay: this setup session advertises no payment method.";throw new P.FloPayError(c,"validation_error",{code:"NoAdvertisedPaymentMethods",param:"sessionId"})}return{session:s,advertisement:u}}async function cr(e,r,t,o,s){let u=r.vault??null;(0,P.isMountableVaultBlock)(u)||(u=await e.getVaultCapture(t,o));let i=(0,P.resolveVaultMountOptions)(u,{billingApiUrl:s,sessionId:t,nonce:o});if(!i)throw new P.FloPayError("FloPay: this setup session has no vault card capability. Upgrade the billing backend integration.","api_error",{code:"UnsupportedBackendVaultCapability"});return i}var Fe=class extends a.default.Component{constructor(){super(...arguments);this.state={failed:!1}}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(t){this.props.onFailed(t,{code:"payment_method_setup_load_failed",retryable:!1})}render(){return this.state.failed?null:this.props.children}};function vt({branches:{StripeSetupMethod:e,PayPalSetupMethod:r},sessionId:t,nonce:o,billingApiUrl:s,telemetry:u,theme:i="modern-light",containerStyle:c,appearance:y,buttonsStyles:_,loading:L=null,onReady:Y,onComplete:v,onDecline:B,onCancel:C,onValidation:F,onError:m}){let[T]=(0,a.useState)(ve.readSetupRedirectReturn),[f,A]=(0,a.useState)(null),[W,N]=(0,a.useState)(!1),[E,g]=(0,a.useState)(null),[w,q]=(0,a.useState)(null),[J,ye]=(0,a.useState)(null),[te,R]=(0,a.useState)(null),[z,se]=(0,a.useState)(()=>new Set),re=(0,a.useRef)(z),fe=(0,a.useRef)(null);fe.current=f;let j=(0,a.useRef)(!1),M=(0,a.useRef)(!1),I=(0,a.useRef)(!1),ie=(0,a.useRef)(!1),le=(0,a.useRef)(0),oe=(0,a.useRef)(0),$=(0,a.useRef)(!1),{vaultTheme:G,surface:ze,overlayTheme:He,appearance:Ge,buttonsLayout:Ke}=(0,a.useMemo)(()=>ct({theme:i,appearance:y,buttonsStyles:_}),[i,y,_]),Gt=(0,a.useMemo)(()=>(0,Le.mergeCardSetupSurface)(ze,c),[ze,c]),U=(0,a.useRef)({sessionId:t,nonce:o,billingApiUrl:s,telemetry:u,onReady:Y,onComplete:v,onDecline:B,onCancel:C,onValidation:F,onError:m});U.current={sessionId:t,nonce:o,billingApiUrl:s,telemetry:u,onReady:Y,onComplete:v,onDecline:B,onCancel:C,onValidation:F,onError:m},(0,a.useEffect)(()=>{$.current=!0;let n=le.current+1;return le.current=n,()=>{$.current=!1,oe.current+=1,queueMicrotask(()=>{le.current===n&&(I.current||ie.current||(ie.current=!0,(0,Q.invokeMerchantCallback)(()=>{U.current.onCancel?.({status:"cancelled",sessionId:t})})))})}},[t]);let he=(0,a.useCallback)((n,l)=>{I.current=!0,j.current=!1,R({status:"success",wording:n,message:null}),(async()=>(await De(600),!M.current&&(M.current=!0,(0,Q.invokeMerchantCallback)(()=>{U.current.onComplete?.({status:"succeeded",sessionId:U.current.sessionId,...l?{paymentMethod:l}:{}})}),$.current&&R(null))))()},[]),ge=(0,a.useCallback)((n,l)=>{I.current=!0,j.current=!1,R({status:"error",wording:n,message:l.message??null}),(0,Q.invokeMerchantCallback)(()=>{U.current.onDecline?.({status:"declined",sessionId:U.current.sessionId,...l.reason?{reason:l.reason}:{},...l.message?{message:l.message}:{}})}),(async()=>(await De(400),$.current&&R(null)))()},[]),ae=(0,a.useCallback)((n,l)=>{j.current?(j.current=!1,R({status:"error",wording:n,message:l.message}),setTimeout(()=>{$.current&&R(null)},400)):R(null),(0,Q.invokeMerchantCallback)(()=>U.current.onError?.(l))},[]),Re=(0,a.useCallback)(async n=>{let l=oe.current+1;oe.current=l;let p=()=>!$.current||l!==oe.current;j.current=!0,R({status:"processing",wording:"payment_method",message:null});let D=new Ee.PaymentAPI((0,P.resolveBillingApiUrl)(U.current.billingApiUrl),{telemetry:U.current.telemetry});try{for(let d=0;d<lr;d+=1){if((d>0||n.waitFirst)&&await De(ur),p())return;let Z=await D.getUnifiedCheckoutSession(U.current.sessionId,U.current.nonce);if(p())return;let ue=Z.data.session?.status;if(ue==="complete"){N(!0),he("payment_method");return}if(ue==="expired")throw new P.FloPayError("This setup session expired before the payment method was saved.","validation_error",{code:"payment_method_setup_expired"})}throw new P.FloPayError("The payment method could not be confirmed yet. Please try again.","api_error",{code:"payment_method_setup_unverified"})}catch(d){if(p())return;let Z=d instanceof P.FloPayError&&d.code==="payment_method_setup_unverified";ae("payment_method",ce(d,Z?{retryable:!0}:{}))}finally{D.destroy()}},[ae,he]);(0,a.useEffect)(()=>{let n=!0,l=(0,P.resolveBillingApiUrl)(s),p=new Ee.PaymentAPI(l,{telemetry:u});A(null),N(!1),g(null),q(null),ye(null);let D=new Set;return re.current=D,se(D),I.current=!1,ie.current=!1,M.current=!1,(async()=>{try{let{session:d,advertisement:Z}=await pr(p,t,o);if(!n)return;let ue={advertisement:Z,customer:dr(d),...d.futureUse?{futureUse:d.futureUse}:{},...d.futureUseUnsupported?{futureUseUnsupported:d.futureUseUnsupported}:{}};if(T){if((0,ve.clearSetupRedirectParams)(),d.status==="complete"){N(!0),A(ue),he("payment_method");return}T.failed?ge("payment_method",{reason:"redirect_failed"}):Re({waitFirst:!0})}let ut=Z.card?await cr(p,d,t,o,l):null;if(!n)return;A(ue),ut&&(q(ut),g(new Ee.PciVaultCardCapture({sessionId:t,operation:"card_setup",telemetry:u})))}catch(d){if(!n)return;let Z=ce(d);I.current=!0,ye(Z),(0,Q.invokeMerchantCallback)(()=>U.current.onError?.(Z))}})(),()=>{n=!1,p.destroy()}},[s,o,T,ge,he,t,u,Re]),(0,a.useEffect)(()=>{if(!E)return;j.current=!1;let n=E.on("submitting",()=>{j.current=!0,R({status:"processing",wording:"card",message:null})}),l=E.on("complete",d=>{he("card",d.paymentMethod)}),p=E.on("decline",d=>{ge("card",{...d.declineReason?{reason:d.declineReason}:{},...d.message?{message:d.message}:{}})}),D=E.on("challenge_dismissed",()=>{R(null)});return()=>{n(),l(),p(),D()}},[E,ge,he]);let Xe=(0,a.useCallback)((n,l,p)=>{if(p.retryable){ae("payment_method",ce(l,p));return}if(re.current.has(n))return;let D=new Set(re.current);D.add(n),re.current=D,se(D);let d=fe.current?.advertisement,Z=d?(0,k.advertisedMethodKeys)(d).some(ue=>!D.has(ue)):!1;ae("payment_method",ce(l,{code:p.code,retryable:Z}))},[ae]),qe=(0,a.useMemo)(()=>({onSubmitting:()=>{j.current=!0,R({status:"processing",wording:"payment_method",message:null})},onConfirmed:()=>{Re({waitFirst:!1})},onDeclined:n=>ge("payment_method",n),onValidation:n=>{(0,Q.invokeMerchantCallback)(()=>U.current.onValidation?.(n))},onAbandoned:()=>{j.current=!1,R(null)}}),[ge,Re]),je=(0,a.useRef)(Xe);je.current=Xe;let $e=(0,a.useRef)(new Map),ke=n=>{let l=$e.current.get(n);if(l)return l;let p=(D,d)=>je.current(n,D,d);return $e.current.set(n,p),p},Ze=(0,a.useCallback)(n=>{if(re.current.has(n))return;let l=new Set(re.current);l.add(n),re.current=l,se(l);let p=fe.current?.advertisement;p&&(0,k.advertisedMethodKeys)(p).some(d=>!l.has(d))||ae("payment_method",ce(new Error("FloPay: none of the advertised payment methods can be used here."),{code:"payment_method_setup_unavailable",retryable:!1}))},[ae]),Je=(0,a.useRef)(Ze);Je.current=Ze;let Qe=(0,a.useRef)(new Map),et=n=>{let l=Qe.current.get(n);if(l)return l;let p=()=>Je.current(n);return Qe.current.set(n,p),p},tt=te?(0,h.jsx)(mt,{status:te.status,errorMessage:te.message,...(0,k.setupOverlayLabels)(te.wording),successNote:null,...He?{theme:He}:{}}):null;if(J)return(0,h.jsx)("div",{role:"alert",children:J.message});if(!f||W)return(0,h.jsxs)(h.Fragment,{children:[tt,f?null:L]});let{advertisement:Ce,customer:Kt,futureUse:rt,futureUseUnsupported:ot}=f,nt=(0,P.resolveBillingApiUrl)(s),at=u===void 0?{}:{telemetry:u},Ae=Ce.stripe.filter(({method:n})=>!z.has(n)),Pe=z.has("paypal")?null:Ce.paypal,st=!!(Ce.card&&E&&w?.html),it=({method:n,publishableKey:l,currency:p})=>(0,h.jsx)("div",{"data-flopay-payment-method":n,style:{display:"contents"},children:(0,h.jsx)(Fe,{onFailed:ke(n),children:(0,h.jsx)(a.Suspense,{fallback:null,children:(0,h.jsx)(e,{method:n,category:(0,k.stripeMethodCategory)(n),publishableKey:l,currency:p,...rt?{futureUse:rt}:{},...ot?{futureUseUnsupported:ot}:{},sessionId:t,nonce:o,billingApiUrl:nt,...at,...Ge?{appearance:Ge}:{},...Ke?{buttonsLayout:Ke}:{},...typeof i=="string"?{themeId:i}:{},...qe,onFailed:ke(n),onUnavailable:et(n)})})})},n),Xt=Ae.filter(({method:n})=>(0,k.stripeMethodCategory)(n)==="wallet"),qt=Ae.filter(({method:n})=>(0,k.stripeMethodCategory)(n)!=="wallet"),lt=Ae.length>0||Pe!==null;return(0,h.jsxs)(h.Fragment,{children:[tt,lt?(0,h.jsxs)("div",{"data-flopay-payment-methods":"",style:{position:"relative",display:"flex",flexDirection:"column",gap:"0.5rem"},children:[Xt.map(it),Pe?(0,h.jsx)("div",{"data-flopay-payment-method":"paypal",children:(0,h.jsx)(Fe,{onFailed:ke("paypal"),children:(0,h.jsx)(a.Suspense,{fallback:null,children:(0,h.jsx)(r,{clientId:Pe.clientId,...Pe.environment?{environment:Pe.environment}:{},...Ce.currency?{currency:Ce.currency}:{},sessionId:t,nonce:o,billingApiUrl:nt,customer:Kt,...at,...qe,onFailed:ke("paypal"),onUnavailable:et("paypal")})})})}):null,qt.map(it)]}):null,st&&lt?(0,h.jsx)(ht,{label:"or add a card"}):null,st&&E&&w?.html?(0,h.jsx)("div",{"data-flopay-payment-method":"card",children:(0,h.jsx)(ft,{capture:E,html:w.html,messageToken:w.messageToken,expectedOrigin:w.expectedOrigin,expiresAt:w.expiresAt,verificationRequired:w.verificationRequired,theme:G,containerStyle:Gt,onReady:()=>{(0,Q.invokeMerchantCallback)(()=>U.current.onReady?.())},onValidation:n=>{(0,Q.invokeMerchantCallback)(()=>U.current.onValidation?.(n))},onError:n=>{n&&ae("card",ce(new Error(n),{code:"card_setup_widget_failed",retryable:!0}))}})}):null]})}var Ht=require("react/jsx-runtime"),wr={StripeSetupMethod:(0,We.lazy)(()=>Promise.resolve().then(()=>(Ut(),It)).then(e=>({default:e.StripeSetupMethod}))),PayPalSetupMethod:(0,We.lazy)(()=>Promise.resolve().then(()=>(Wt(),Nt)).then(e=>({default:e.PayPalSetupMethod})))};function zt(e){return(0,Ht.jsx)(vt,{...e,branches:wr})}0&&(module.exports={FloPayCardSetupError,FloPayPaymentMethodSetup});
1
+ "use strict";var C=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var O=Object.prototype.hasOwnProperty;var V=(e,t)=>{for(var n in t)C(e,n,{get:t[n],enumerable:!0})},A=(e,t,n,p)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of I(t))!O.call(e,a)&&a!==n&&C(e,a,{get:()=>t[a],enumerable:!(p=D(t,a))||p.enumerable});return e};var j=e=>A(C({},"__esModule",{value:!0}),e);var L={};V(L,{FloPayPaymentMethodSetup:()=>_});module.exports=j(L);var g=require("@flopay/js"),E=require("@flopay/shared"),s=require("react");var i=require("@flopay/shared");var M=require("react/jsx-runtime"),J="2.4.0";function v(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var K=new Set(["validation_error","api_error","authentication_error","rate_limit_error","network_error"]);function S(e,t,n,p={}){return Object.assign(new E.FloPayError(e,t,p),{retryable:n})}function N(e){let t=v(e)?e:{},n=typeof t.type=="string"&&K.has(t.type)?t.type:"";return S(typeof t.message=="string"?t.message:"The setup failed.",n||"api_error",t.retryable===!0,{...typeof t.code=="string"?{code:t.code}:{},...typeof t.param=="string"?{param:t.param}:{},...typeof t.statusCode=="number"?{statusCode:t.statusCode}:{}})}function H(e){return e instanceof E.FloPayError?S(e.message,e.type,!0,{code:e.code??"runtime_load_failed",cause:e}):S("The checkout runtime failed to load.","network_error",!0,{code:"runtime_load_failed",cause:e})}function h(e){return{...e.theme===void 0?{}:{theme:e.theme},...e.appearance===void 0?{}:{appearance:e.appearance},...e.buttonsStyles===void 0?{}:{buttonsStyles:e.buttonsStyles},...e.containerStyle===void 0?{}:{containerStyle:e.containerStyle},...e.strings===void 0?{}:{strings:e.strings}}}function k({kind:e,props:t}){let{sessionId:n,nonce:p,runtimeUrl:a,runtimeTimeoutMs:f}=t,F=(0,s.useRef)(null),y=(0,s.useRef)(null),c=(0,s.useRef)(t);c.current=t;let T=h(t),d=JSON.stringify(T),P=(0,s.useRef)(d);return(0,s.useEffect)(()=>{let m=F.current;if(!m)return;let o=!0,R=r=>{(0,i.invokeMerchantCallback)(()=>c.current.onError?.(r))},w=r=>{let u=c.current,l=r.payload;switch(r.name){case"setupReady":(0,i.invokeMerchantCallback)(()=>u.onReady?.());return;case"setupValidation":{let x=v(l)&&typeof l.message=="string"?l.message:null;(0,i.invokeMerchantCallback)(()=>u.onValidation?.(x));return}case"complete":(0,i.invokeMerchantCallback)(()=>u.onComplete?.(l));return;case"decline":(0,i.invokeMerchantCallback)(()=>u.onDecline?.(l));return;case"cancel":(0,i.invokeMerchantCallback)(()=>u.onCancel?.(l));return;case"error":R(N(l));return;default:return}};return(0,g.loadCheckoutRuntime)({runtimeUrl:a,...f===void 0?{}:{timeoutMs:f}}).then(r=>{if(!o)return;if(typeof r.mountSetup!="function"){R(S("The checkout runtime on this page is too old to run setup.","api_error",!1,{code:"runtime_setup_unsupported"}));return}let u=h(c.current);P.current=JSON.stringify(u),y.current=r.mountSetup(m,{setup:e,sessionId:n,nonce:p,contractVersion:J,...u,onEvent:w})},r=>{o&&R(H(r))}),()=>{o=!1;let r=y.current;y.current=null,r?.unmount()}},[e,n,p,a,f]),(0,s.useEffect)(()=>{let m=y.current;if(!m||P.current===d)return;P.current=d;let o=c.current;m.update({theme:o.theme,appearance:o.appearance,buttonsStyles:o.buttonsStyles,containerStyle:o.containerStyle,strings:o.strings})},[d]),(0,M.jsx)("div",{ref:F})}var b=require("react/jsx-runtime");function _(e){return(0,b.jsx)(k,{kind:"payment_method",props:e})}0&&(module.exports={FloPayPaymentMethodSetup});
@@ -1,14 +1,7 @@
1
1
  /**
2
- * Stripe-free entry for the payment-method setup surface
3
- * (`@flopay/react/payment-method-setup`).
4
- *
5
- * The main entry's module graph reaches `@flopay/js`'s Stripe adapter, whose
6
- * eager `@stripe/stripe-js` import starts downloading Stripe.js at evaluation
7
- * time. Import `FloPayPaymentMethodSetup` from here instead: a session that
8
- * advertises only cards (or only PayPal) then never requests Stripe.js, and
9
- * Stripe loads lazily only when the session advertises a Stripe wallet or APM.
10
- * The main entry exports the same surface with the same props and callbacks,
11
- * with its wallet/APM and PayPal branches bound statically instead.
2
+ * Entry for the payment-method setup surface (`@flopay/react/payment-method-setup`): the setup
3
+ * that mounts from the Flo-hosted runtime, with nothing else from the main entry.
12
4
  */
13
- export { FloPayCardSetupError } from './flopay-card-setup.js';
14
- export { FloPayPaymentMethodSetup, type FloPayPaymentMethodSetupCancelEvent, type FloPayPaymentMethodSetupCompleteEvent, type FloPayPaymentMethodSetupDeclineEvent, type FloPayPaymentMethodSetupProps, } from './flopay-payment-method-setup.js';
5
+ export type { FloPayRuntimeSetupCancelEvent as FloPayPaymentMethodSetupCancelEvent, FloPayRuntimeSetupCompleteEvent as FloPayPaymentMethodSetupCompleteEvent, FloPayRuntimeSetupDeclineEvent as FloPayPaymentMethodSetupDeclineEvent, FloPayRuntimeSetupError as FloPayCardSetupError, } from './flopay-runtime-card-setup.js';
6
+ export type { FloPayRuntimePaymentMethodSetupProps as FloPayPaymentMethodSetupProps } from './flopay-runtime-payment-method-setup.js';
7
+ export { FloPayRuntimePaymentMethodSetup as FloPayPaymentMethodSetup } from './flopay-runtime-payment-method-setup.js';
@@ -1 +1 @@
1
- import{a as t}from"./chunk-PCIHQY3X.mjs";import{h as a}from"./chunk-ITRFSHZP.mjs";import{lazy as o}from"react";import{jsx as P}from"react/jsx-runtime";var p={StripeSetupMethod:o(()=>import("./payment-method-setup-stripe-526L4P5X.mjs").then(e=>({default:e.StripeSetupMethod}))),PayPalSetupMethod:o(()=>import("./payment-method-setup-paypal-CLV7JDJH.mjs").then(e=>({default:e.PayPalSetupMethod})))};function y(e){return P(t,{...e,branches:p})}export{a as FloPayCardSetupError,y as FloPayPaymentMethodSetup};
1
+ import{a as e}from"./chunk-KPRDVWZP.mjs";import"./chunk-XRYDC367.mjs";export{e as FloPayPaymentMethodSetup};
@@ -0,0 +1,10 @@
1
+ /**
2
+ * What `FloPayProvider` hands the components below it: the publishable key and the Flo-origin
3
+ * runtime script, used when a component is not given its own. It holds no FloPay instance and
4
+ * loads nothing.
5
+ */
6
+ export interface FloPayRuntimeContextValue {
7
+ publishableKey?: string;
8
+ runtimeUrl?: string;
9
+ }
10
+ export declare const FloPayRuntimeContext: import("react").Context<FloPayRuntimeContextValue>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flopay/react",
3
- "version": "1.20.14",
3
+ "version": "2.0.0",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "publishConfig": {
@@ -36,11 +36,8 @@
36
36
  "dist"
37
37
  ],
38
38
  "dependencies": {
39
- "@flopay/js": "1.20.14",
40
- "@flopay/shared": "1.20.14",
41
- "@paypal/paypal-js": "^11.3.0",
42
- "@stripe/react-stripe-js": "^7.1.0",
43
- "@stripe/stripe-js": "^10.3.0"
39
+ "@flopay/js": "2.0.0",
40
+ "@flopay/shared": "2.0.0"
44
41
  },
45
42
  "peerDependencies": {
46
43
  "react": ">=18.0.0",
@@ -1,31 +0,0 @@
1
- import { Elements } from '@stripe/react-stripe-js';
2
- import type { ComponentProps, ReactElement } from 'react';
3
- /**
4
- * Records that a checkout is moving its Elements groups from the `current`
5
- * Stripe instances to the `next` ones, because a claim moved it to another
6
- * Stripe account. Call it before the new instances reach any group.
7
- *
8
- * Each `next` instance that is not already in use gets a fresh group key, so
9
- * every `<AccountBoundElements>` handed it mounts a new group on the new
10
- * account, even when the page switched to that account before. An instance
11
- * still in use (an account that did not change, such as an unchanged PayPal
12
- * account) keeps its key, so its groups stay mounted.
13
- */
14
- export declare function bindSwitchedStripeAccounts(next: unknown[], current: unknown[]): void;
15
- /**
16
- * Stripe's `<Elements>`, re-mounted when the checkout switches Stripe account.
17
- *
18
- * `<Elements>` binds to the first `stripe` it is given and ignores a later one.
19
- * When a claim moves a checkout to another Stripe account, `FloPayCheckout`
20
- * records the new account's instances (`bindSwitchedStripeAccounts`) before it
21
- * hands them to its groups. The group key then changes in the same render as
22
- * the `stripe` prop, so React unmounts the old group, and the wallet buttons
23
- * inside it, and mounts a fresh group on the new account: no button keeps
24
- * confirming on the old account.
25
- *
26
- * Only that switch changes the key. Any other render, including one that
27
- * passes another instance for the same account or moves the group within the
28
- * layout, keeps the group, and everything in it, mounted exactly as plain
29
- * `<Elements>` would.
30
- */
31
- export declare function AccountBoundElements(props: ComponentProps<typeof Elements>): ReactElement;
@@ -1,88 +0,0 @@
1
- import type { ButtonsLayoutStyles, ButtonsLayoutTheme, CheckoutButtonMethod, CheckoutItem, CheckoutProduct, CheckoutSession, CheckoutSubscription, DeclineEvent, FloPayAppearance, InlineSessionDraft, OneClickSession, PaymentResult, ThemeId } from '@flopay/shared';
2
- import { FloPayError } from '@flopay/shared';
3
- import type React from 'react';
4
- export interface FloPayAutomaticPaymentSuccessEvent {
5
- result: PaymentResult;
6
- session: CheckoutSession | null;
7
- sessionId: string | null;
8
- autoCompleted: boolean;
9
- }
10
- export interface FloPayAutomaticPaymentButtonProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'children' | 'onError'> {
11
- sessionId?: string;
12
- /**
13
- * Session-bound checkout token for a consumer-supplied {@link sessionId}
14
- * (the `nonce` returned when that session was created). Post-#640 backends
15
- * require it as `x-checkout-session-token` to read the session and to
16
- * `/process` it; without it the existing-session path 401s with
17
- * "Missing checkout session token.". Ignored on the create-session path,
18
- * where the SDK mints and threads the nonce itself.
19
- */
20
- nonce?: string;
21
- createSession?: InlineSessionDraft;
22
- /**
23
- * Called on click to fetch a server-minted one-click session (`{ sessionId, nonce }`).
24
- * Give exactly one of `sessionId`, `getSession` or an inline draft.
25
- */
26
- getSession?: (options: {
27
- signal: AbortSignal;
28
- }) => Promise<OneClickSession>;
29
- /**
30
- * @deprecated Ignored. The backend now picks the customer's most recent
31
- * vaulted payment method via `getLatestByUserId` and rebinds the session's
32
- * gateway to match it (see `apps/api`'s `createSingle` auto-checkout
33
- * branch). Passing this prop has no effect — it is retained only to avoid
34
- * breaking existing integrations.
35
- */
36
- paymentMethodId?: string;
37
- /**
38
- * @deprecated Ignored. The backend orchestrates gateway routing — clients
39
- * no longer choose between card and PayPal at the SDK boundary. Passing
40
- * this prop has no effect.
41
- */
42
- checkoutMethod?: CheckoutButtonMethod;
43
- clientId?: string;
44
- /**
45
- * Unified products array (TeamFloPay/backend#760). When supplied,
46
- * `items`/`subscriptions` are ignored. The SDK folds the legacy fields
47
- * into this shape internally.
48
- */
49
- products?: CheckoutProduct[];
50
- items?: CheckoutItem[];
51
- subscriptions?: CheckoutSubscription[];
52
- account?: InlineSessionDraft['account'];
53
- successUrl?: string;
54
- cancelUrl?: string;
55
- couponCodes?: string[];
56
- tagsData?: InlineSessionDraft['tagsData'];
57
- utmMetadata?: InlineSessionDraft['utmMetadata'];
58
- billingApiUrl?: string;
59
- locale?: string;
60
- /**
61
- * High-level theme bundle that styles the button (and the fallback
62
- * `FloPayCheckout` modal that opens when the saved-payment charge needs
63
- * user interaction). One of: `'classic'`, `'modern-light'`, `'modern-dark'`,
64
- * `'bold-light'`, `'bold-dark'`, `'glass-light'`, `'glass-dark'`. Explicit
65
- * `buttonsStyles` still wins for fine-grained overrides.
66
- */
67
- theme?: ThemeId;
68
- /**
69
- * Per-checkout appearance overrides layered on top of the chosen `theme`
70
- * (same shape as {@link FloPayCheckout}'s `appearance`). Its `colorPrimary` /
71
- * `colorPrimaryHover` / `borderRadius` re-skin the button — and the fallback
72
- * `FloPayCheckout` modal — so the auto-pay button matches the rest of the
73
- * themed checkout. Without this the button only saw the bundle's defaults.
74
- */
75
- appearance?: FloPayAppearance;
76
- /**
77
- * @deprecated Use `theme` instead. Legacy buttons-layout preset
78
- * (`'default' | 'minimal' | 'rounded' | 'dark'`). Still honored for
79
- * back-compat.
80
- */
81
- buttonsTheme?: ButtonsLayoutTheme;
82
- buttonsStyles?: ButtonsLayoutStyles;
83
- onSuccess?: (event: FloPayAutomaticPaymentSuccessEvent) => void;
84
- onError?: (error: FloPayError) => void;
85
- onDecline?: (decline: DeclineEvent) => void;
86
- children?: React.ReactNode;
87
- }
88
- export declare function FloPayAutomaticPaymentButton({ sessionId, nonce, createSession, getSession, paymentMethodId: _deprecatedPaymentMethodId, checkoutMethod: _deprecatedCheckoutMethod, clientId, products, items, subscriptions, account, successUrl, cancelUrl, couponCodes, tagsData, utmMetadata, billingApiUrl, locale, theme, appearance, buttonsTheme, buttonsStyles: stylesOverride, onSuccess, onError, onDecline, children, disabled, type, style, ...buttonProps }: FloPayAutomaticPaymentButtonProps): React.JSX.Element;
@@ -1,43 +0,0 @@
1
- import type { InlineSessionPatch } from '@flopay/shared';
2
- export { compactBuyerIdentity } from '@flopay/shared';
3
- export type MaybePromise<T> = T | Promise<T>;
4
- export type BuyerIdentity = NonNullable<InlineSessionPatch['account']>;
5
- export type BuyerIdentityReadyHandler = (identity: BuyerIdentity) => MaybePromise<void>;
6
- export type BuyerIdentityFallbackRequest = {
7
- id: number;
8
- methodLabel: string;
9
- identity: BuyerIdentity;
10
- };
11
- /**
12
- * Single-request identity collector shared by the express (wallet/PayPal)
13
- * surfaces. `collect(methodLabel, identity)` opens a panel seeded with whatever
14
- * the provider returned and resolves with the buyer's edited identity, or
15
- * `null` if they cancel (or the component unmounts). A new request supersedes
16
- * any pending one.
17
- */
18
- export declare function useBuyerIdentityFallback(): {
19
- request: BuyerIdentityFallbackRequest | null;
20
- collect: (methodLabel: string, identity: BuyerIdentity) => Promise<BuyerIdentity | null>;
21
- finish: (identity: BuyerIdentity | null) => void;
22
- };
23
- /**
24
- * Buyer-identity collection panel shared by every express surface that has to
25
- * gather a missing email before it can continue (wallets, the ECE PayPal
26
- * button, and the direct PayPal button). Provider- or merchant-supplied names
27
- * are preserved, but the SDK never asks the buyer for a name itself.
28
- *
29
- * - `methodLabel` drives both the heading and the submit copy
30
- * ("Continue with {methodLabel}").
31
- * - `submitting` disables the submit while a continuation is in flight (used by
32
- * the direct-PayPal preflight path).
33
- * - `onCancel` renders a Cancel button only when provided.
34
- * - `testId` overrides the container test id for surface-specific assertions.
35
- */
36
- export declare function BuyerIdentityFallbackPanel({ identity, methodLabel, onComplete, onCancel, submitting, testId, }: {
37
- identity: BuyerIdentity;
38
- methodLabel: string;
39
- onComplete: (identity: BuyerIdentity) => void;
40
- onCancel?: () => void;
41
- submitting?: boolean;
42
- testId?: string;
43
- }): import("react").JSX.Element;
@@ -1,11 +0,0 @@
1
- import type React from 'react';
2
- export declare function isEmptySlotContent(content: React.ReactNode | undefined): boolean;
3
- export declare function CardButtonContentSlot({ content, }: {
4
- content?: React.ReactNode;
5
- }): React.ReactElement;
6
- export declare function BackButtonContentSlot({ content, }: {
7
- content?: React.ReactNode;
8
- }): React.ReactElement;
9
- export declare function TitleContentSlot({ content }: {
10
- content?: React.ReactNode;
11
- }): React.ReactElement;
@@ -1,12 +0,0 @@
1
- import type React from 'react';
2
- export { mergeCardSetupSurface } from '@flopay/shared';
3
- /**
4
- * Apply a `React.CSSProperties` object to an element in declaration order,
5
- * replacing whatever inline style it had. Rewriting the whole declaration list
6
- * on every change (rather than diffing property by property, as a React
7
- * `style` prop does) is what keeps the shorthand/longhand precedence above
8
- * deterministic across live theme switches: a preset `border` that changes
9
- * underneath a merchant `borderColor` is re-cascaded, not silently reset.
10
- * Values are serialized exactly as React would serialize a `style` prop.
11
- */
12
- export declare function applyInlineStyle(element: HTMLElement, style: React.CSSProperties | undefined): void;
@@ -1,32 +0,0 @@
1
- import type { ButtonsLayoutStyles, CardSetupOverlaySource, CardSetupThemeSource, FloPayAppearance, VaultCardThemeColors } from '@flopay/shared';
2
- import type React from 'react';
3
- import type { ProcessingOverlayTheme } from './processing-overlay.js';
4
- export { mergeButtonsStyles } from '@flopay/shared';
5
- /**
6
- * The card-setup processing / success / error modal for a named preset (or a
7
- * stored theme resolved over one), from `@flopay/shared`; this only types its
8
- * framework-free panel style as React's.
9
- */
10
- export declare function computeCardSetupOverlayTheme(source: CardSetupOverlaySource): ProcessingOverlayTheme;
11
- /** Everything the card-setup surface paints, resolved from one stored theme. */
12
- interface CardSetupThemeResolution {
13
- /**
14
- * The hosted-widget directive: computed colors, raw colors passed through
15
- * untouched, or `null` — the explicit classic reset.
16
- */
17
- vaultTheme: VaultCardThemeColors | null;
18
- /** The pane surface laid beneath the merchant's `containerStyle`, if any. */
19
- surface: React.CSSProperties | undefined;
20
- /** The outcome overlay's theme; `undefined` keeps the neutral modal. */
21
- overlayTheme: ProcessingOverlayTheme | undefined;
22
- /** The effective appearance, for the Stripe Elements and method tiles beside the hosted form. */
23
- appearance: FloPayAppearance | undefined;
24
- /** The effective buttons layout, for the wallet, PayPal and APM buttons and tiles. */
25
- buttonsLayout: ButtonsLayoutStyles | undefined;
26
- }
27
- /**
28
- * Resolve the `FloPayCardSetup` theming props the way `FloPayCheckout`
29
- * resolves its own (`resolveCardSetupTheme` in `@flopay/shared`), typing the
30
- * surface and overlay as React's.
31
- */
32
- export declare function resolveCardSetupTheme(source: CardSetupThemeSource): CardSetupThemeResolution;
@@ -1,172 +0,0 @@
1
- import type { PaymentAPI } from '@flopay/js';
2
- import type { CaptureMethod, CardSetupFutureUse, CheckoutAccount, CheckoutButtonMethod, CheckoutMode, CheckoutSession, DeclineEvent, FutureUseSessionFields, InlineSessionDraft, InlineSessionPatch, NormalizedCheckoutSession, PaymentResult, TelemetryErrorCode, TelemetryFailureCategory, TelemetryProvider, TelemetryRequestCategory, TelemetryStatusClass, TokenizedBody } from '@flopay/shared';
3
- import { FloPayError } from '@flopay/shared';
4
- export interface CheckoutMountFailureResolution {
5
- errorCode: TelemetryErrorCode;
6
- stage: 'checkout_mount' | 'provider_load' | 'session_read';
7
- failureCategory?: TelemetryFailureCategory;
8
- provider?: TelemetryProvider;
9
- requestCategory?: TelemetryRequestCategory;
10
- statusClass?: TelemetryStatusClass;
11
- }
12
- export interface CheckoutProviderFailureTelemetry {
13
- errorCode: 'PROVIDER_LOAD_FAILED';
14
- stage: 'provider_load';
15
- failureCategory: 'invalid_response' | 'provider_runtime';
16
- provider: 'stripe';
17
- requestCategory: 'provider_sdk';
18
- }
19
- /** Resolve the fixed Stripe provider-load tuple without inspecting free-form data. */
20
- export declare function resolveCheckoutProviderFailureTelemetry(error: unknown): CheckoutProviderFailureTelemetry;
21
- export { canRecoverHostedCardForm, hasServerSideCardGateway } from '@flopay/shared';
22
- export declare function canRenderWithoutStripe(unified: NormalizedCheckoutSession | null, showPayPal: boolean, showStripe: boolean): boolean;
23
- /**
24
- * Classify an existing-session mount failure only from SDK-owned control-flow
25
- * state and closed error discriminants. Free-form messages are never inspected
26
- * or forwarded. UI fallback decisions remain separate so this helper only
27
- * carries telemetry fields into the reporter.
28
- */
29
- export declare function resolveCheckoutMountFailure(error: unknown, sessionReadCompleted: boolean): CheckoutMountFailureResolution | undefined;
30
- /**
31
- * Single-flight buyer-only claim for a still-anonymous checkout session.
32
- * Resolves with the identified session once `PATCH /claim` lands; every call
33
- * after the first returns the same promise (a claim cannot change the bound
34
- * buyer, so re-firing would only desync it from the submit-time snapshot).
35
- */
36
- export type BuyerClaim = (account?: Partial<NonNullable<InlineSessionPatch['account']>>) => Promise<NormalizedCheckoutSession>;
37
- /**
38
- * Build the single-flight buyer-only claim for an anonymous session that has
39
- * no detached-create closure to hand: a session restored from sessionStorage
40
- * after a remount, a one-shot (`deferDataAttachment: false`) create without an
41
- * email, an existing session loaded by `sessionId` + `nonce` that the billing
42
- * API returned as `buyerIdentified: false`, or a standalone `SplitCardForm`
43
- * composed by the merchant. Everything the replay-safe backend operation needs
44
- * is still available — session id, nonce, and whatever account draft the
45
- * merchant supplied (none for a session loaded by id).
46
- *
47
- * Without this closure the card form's collected email never reaches
48
- * `PATCH /claim`, only the best-effort submit-time `PATCH /account` snapshot —
49
- * which writes the email but does not bind a buyer, so the hosted vault charge
50
- * is refused server-side and the widget times out waiting for an outcome.
51
- */
52
- export declare function createBuyerClaim(api: Pick<PaymentAPI, 'claimCheckoutSession'>, sessionId: string, nonce: string, baseAccount?: Partial<InlineSessionDraft['account']>): BuyerClaim;
53
- export declare function mergeInlineSessionPatches(base: InlineSessionPatch | undefined, patch: InlineSessionPatch | undefined): InlineSessionPatch | undefined;
54
- export declare function mergeInlineSessionPatch(params: InlineSessionDraft, patch: InlineSessionPatch | undefined): InlineSessionDraft;
55
- export declare function buildSyntheticSession(params: InlineSessionDraft, checkoutModeOverride?: CheckoutMode): CheckoutSession;
56
- export { splitFullName } from '@flopay/shared';
57
- export declare function mergeAccountPatch<T extends {
58
- userId?: string;
59
- email?: string;
60
- firstName?: string;
61
- lastName?: string;
62
- country?: string | null;
63
- zip?: string | null;
64
- }>(base: T, patch: Partial<CheckoutAccount> | undefined): T;
65
- export declare function buildDeclineEvent(method: CheckoutButtonMethod, input: string | FloPayError, overrides?: {
66
- code?: string;
67
- declineCode?: string;
68
- }): DeclineEvent;
69
- /**
70
- * Mark an error thrown while a created session's provider scripts loaded, so
71
- * the create path can report it as `provider_load_failed` rather than as a
72
- * session-create failure. Returns the same error, for rethrowing.
73
- */
74
- export declare function markProviderLoadFailure(error: unknown, sessionId?: string | null): unknown;
75
- /** The session a provider-load failure belongs to, when `error` is one. */
76
- export declare function readProviderLoadFailure(error: unknown): {
77
- sessionId?: string;
78
- } | undefined;
79
- /**
80
- * Record which checkout session a failure belongs to (sdk#396), so the error
81
- * and any decline event built from it carry the id. Returns the same error;
82
- * an empty id or one already set is left alone. Never pass the session nonce.
83
- */
84
- export declare function withCheckoutSessionId<T extends FloPayError>(error: T, sessionId: string | null | undefined): T;
85
- export { applyFriendlyMessageOverride } from '@flopay/shared';
86
- /** Build the merchant-facing terminal result from a completed checkout session. */
87
- export declare function buildAuthorizedOrSucceededResult(session: Pick<CheckoutSession, 'status' | 'id' | 'paymentId' | 'authorizationExpiresAt'>, fallbackSessionId?: string | null): PaymentResult;
88
- /** Whether the checkout reached a buyer-success terminal state. */
89
- export declare function isCheckoutSessionTerminalSuccess(session: CheckoutSession | null | undefined): session is CheckoutSession & {
90
- status: 'authorized' | 'complete';
91
- };
92
- /**
93
- * Reconcile a status-only hard-cap outcome with the complete session a React flow already holds.
94
- * The status endpoint omits amount and currency, so those fields must come from the prior session
95
- * rather than placeholder values in a public merchant callback.
96
- */
97
- export declare function resolveCheckoutCompletionSession(completion: NormalizedCheckoutSession, priorSession: CheckoutSession): CheckoutSession | undefined;
98
- /** Preserve the public error contract for an expired checkout session. */
99
- export declare function createExpiredCheckoutSessionError(session: CheckoutSession): FloPayError;
100
- /** Read a `code` off a thrown value: FloPayError's own, or a plain `{ code }` shape. */
101
- export declare function readErrorCode(err: unknown): string | undefined;
102
- /** Preserve the public error contract when automatic checkout polling does not succeed. */
103
- export declare function createAutomaticPaymentSessionError(session: CheckoutSession | null | undefined): FloPayError;
104
- /**
105
- * The Stripe PaymentIntent statuses the checkout can advance from.
106
- * `requires_capture` remains accepted for legacy automatic/PayPal sessions,
107
- * but is not a settled payment for an explicit manual-capture session.
108
- */
109
- export declare function isSuccessfulPaymentIntentStatus(status: string | null | undefined, captureMethod?: CaptureMethod): boolean;
110
- export declare function mapPayPalIntentStatusToPaymentResult(status: string | null | undefined): PaymentResult['status'];
111
- export type StripePaymentIntentLike = {
112
- id?: string;
113
- status?: string;
114
- payment_method?: string | {
115
- id?: string | null;
116
- } | null;
117
- };
118
- export declare function retrievePaymentIntentFromProvider(provider: unknown, clientSecret: string): Promise<StripePaymentIntentLike | null>;
119
- /**
120
- * Deferred Stripe Elements mode for the wallet / Express Checkout row
121
- * (Apple Pay, Google Pay).
122
- *
123
- * The mode, amount and capture method come from the shared
124
- * {@link resolveWalletModeOptions} (setup mode for a $0-today cart, so the
125
- * wallet sheet never shows a placeholder charge), which `@flopay/vue` uses too.
126
- *
127
- * The usage comes from {@link resolveSetupFutureUsage} (future use is platform
128
- * policy): the read's `futureUse` when it carries one, none when Apple Pay or
129
- * Google Pay is listed in `futureUseUnsupported`, and the historic
130
- * `off_session` on a legacy read.
131
- *
132
- * @param amountInMinorUnits cart total due today, in the smallest currency unit.
133
- * @param captureMethod capture contract used by the subsequently created intent.
134
- * @param session the session read's future-use fields.
135
- */
136
- export declare function resolveWalletElementsMode(amountInMinorUnits: number | undefined, captureMethod?: CaptureMethod, session?: FutureUseSessionFields | null): {
137
- mode: 'setup';
138
- allowedPaymentMethodTypes: ['card'];
139
- setupFutureUsage?: CardSetupFutureUse;
140
- } | {
141
- mode: 'payment';
142
- amount: number;
143
- captureMethod: 'automatic_async' | 'manual';
144
- allowedPaymentMethodTypes: ['card'];
145
- setupFutureUsage?: CardSetupFutureUse;
146
- };
147
- /** Bounded cause of a wallet confirmation the provider rejected as invalid. */
148
- type WalletConfirmationRejectionReason = 'deferred_contract_mismatch' | 'intent_unexpected_state' | 'invalid_request';
149
- export type WalletConfirmationRejection = {
150
- errorCode: 'CONFIGURATION_INVALID';
151
- failureCategory: 'invalid_response';
152
- reason: WalletConfirmationRejectionReason;
153
- } | {
154
- errorCode: 'PROVIDER_RUNTIME_FAILED';
155
- failureCategory: 'provider_runtime';
156
- };
157
- /**
158
- * Reduce a rejected Stripe confirmation to Flo's closed telemetry taxonomy.
159
- * Provider strings are inspected only for an allowlisted classification and
160
- * are never forwarded to telemetry.
161
- *
162
- * Invalid confirmations carry a bounded `reason`, in precedence order:
163
- * - `deferred_contract_mismatch`: the deferred Elements options disagree with
164
- * the intent (Stripe.js `IntegrationError` or `elements_intent_mismatch`).
165
- * - `intent_unexpected_state`: the intent was already confirmed, cancelled or
166
- * changed when confirmation landed.
167
- * - `invalid_request`: any other `invalid_request_error`.
168
- *
169
- * Runtime failures stay reason-less.
170
- */
171
- export declare function classifyWalletConfirmationRejection(error: unknown): WalletConfirmationRejection;
172
- export declare function resolveTokenizedPaymentMethodId(tokenizedBody: TokenizedBody | null | undefined): string | undefined;
@@ -1 +0,0 @@
1
- import{a as T,b as A,j as I}from"./chunk-VK67324N.mjs";import{PaymentAPI as C}from"@flopay/js/card-setup";import{FloPayError as s,isSettledSessionIntent as x,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as R,settledSessionIntentError as D}from"@flopay/shared";import{loadScript as O}from"@paypal/paypal-js";import{useEffect as F,useRef as B,useState as L}from"react";import{jsx as Y}from"react/jsx-runtime";function N({clientId:d,environment:o,currency:i,sessionId:n,nonce:l,billingApiUrl:y,telemetry:f,customer:{userId:m,email:P},onSubmitting:h,onConfirmed:_,onFailed:v,onAbandoned:w}){let b=B(null),t=B({onSubmitting:h,onConfirmed:_,onFailed:v,onAbandoned:w});t.current={onSubmitting:h,onConfirmed:_,onFailed:v,onAbandoned:w};let[c]=L(()=>I().inAppBrowser);return F(()=>{let a=!0,k,u=new C(y,{telemetry:f}),g={userId:m,email:P};return(async()=>{try{let p=await O({clientId:d,...i?{currency:i.toUpperCase()}:{},components:"buttons",...o==="sandbox"||o==="production"?{environment:o}:{}}),S=b.current;if(!a||!S)return;if(!p?.Buttons)throw new s("PayPal could not be loaded.","api_error",{code:"paypal_unavailable"});let E=p.Buttons({createVaultSetupToken:async()=>{t.current.onSubmitting();let e=await u.createSessionIntent(n,l,{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:R,paymentMethodId:null,intentKind:"setup"});if(x(e))throw D(n);if(e.provider!=="paypal"||e.providerObjectType!=="setup_token")throw new s("The billing API did not return a PayPal setup token.","api_error",{code:"InvalidSessionIntentResponse"});return e.providerObjectId},onApprove:async e=>{let r=e.vaultSetupToken;if(!r)throw new s("PayPal approved without a setup token.","api_error",{code:"paypal_setup_token_missing"});let M=await u.processPayment(g.userId,{sessionId:n,nonce:l,paymentMethodCategory:"paypal",tokenizedData:{id:r,type:"paypal_setup_token",isPaypal:!0,gateway:"paypal",paymentMethodType:R},accountData:g});if(!M.ok)throw new s("PayPal could not be saved.","api_error",{code:"paypal_setup_failed",statusCode:M.status});a&&t.current.onConfirmed()},onCancel:()=>{a&&t.current.onAbandoned()},onError:e=>{if(!a)return;let{popupBlocked:r}=A(e,{inAppBrowser:c,handoffObserved:!1});t.current.onFailed(r?new Error(T("PayPal",!0,c)):e,{code:r?"popup_blocked":"paypal_setup_failed",retryable:!0})}});k=()=>E.close(),await E.render(S)}catch(p){if(!a)return;t.current.onFailed(p,{code:"paypal_unavailable",retryable:!0})}})(),()=>{a=!1,k?.().catch(()=>{}),u.destroy()}},[y,d,i,P,o,c,l,n,f,m]),Y("div",{ref:b,"data-flopay-paypal-setup":""})}export{N as a};