@lockerverse/react 0.2.75 → 0.2.76
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/README.md +75 -33
- package/dist/immutable-resource-identity.js +2 -0
- package/dist/immutable-resource-identity.js.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/lockerverse-donate-launcher.d.ts +1 -1
- package/dist/lockerverse-donate-launcher.d.ts.map +1 -1
- package/dist/lockerverse-donate-launcher.js +1 -1
- package/dist/lockerverse-donate-launcher.js.map +1 -1
- package/dist/lockerverse-payment.d.ts +1 -1
- package/dist/lockerverse-payment.d.ts.map +1 -1
- package/dist/lockerverse-payment.js +1 -1
- package/dist/lockerverse-payment.js.map +1 -1
- package/dist/signup.d.ts +17 -4
- package/dist/signup.d.ts.map +1 -1
- package/dist/signup.js +1 -1
- package/dist/signup.js.map +1 -1
- package/dist/types.d.ts +6 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/use-lockerverse-widget.d.ts +4 -8
- package/dist/use-lockerverse-widget.d.ts.map +1 -1
- package/dist/use-lockerverse-widget.js +1 -1
- package/dist/use-lockerverse-widget.js.map +1 -1
- package/dist/widget.d.ts +2 -2
- package/package.json +11 -9
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as e,c as t,d as n,f as r,i,l as a,o,s,t as c,u as l}from"./contact-validation.js";import{LockerverseSdkError as u,createLockerverseCheckoutClient as d}from"@lockerverse/sdk/checkout";import{createContext as f,useCallback as p,useContext as m,useEffect as h,useId as g,useLayoutEffect as _,useMemo as v,useReducer as y,useRef as b,useState as x}from"react";import{AddressElement as S,Elements as C,PaymentElement as w,useElements as T,useStripe as E}from"@stripe/react-stripe-js";import{loadStripe as D}from"@stripe/stripe-js";import{array as O,minLength as k,minValue as A,nonEmpty as j,number as M,object as N,pipe as P,regex as F,safeInteger as ee,safeParse as I,strictObject as L,string as R,trim as z,union as te}from"valibot";import{Fragment as B,jsx as V,jsxs as H}from"react/jsx-runtime";import{Select as U}from"@base-ui/react/select";const W=f(void 0);function G({children:e,container:t}){return V(W.Provider,{value:t,children:e})}function ne(){return V(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 16 16`,children:V(`path`,{d:`m4 6 4 4 4-4`})})}function K(){return V(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 16 16`,children:V(`path`,{d:`m3 8 3 3 7-7`})})}function q({ariaDescribedBy:e,ariaLabel:t,ariaLabelledBy:n,className:r,id:i,invalid:a=!1,name:o,onValueChange:s,options:c,value:l}){let u=m(W),d=[`lockerverse-payment__select`,r].filter(Boolean).join(` `);return V(`div`,{className:d,children:H(U.Root,{id:i,items:c,name:o,onValueChange:e=>{e!==null&&s(e)},value:l,children:[H(U.Trigger,{"aria-describedby":e,"aria-invalid":a||void 0,"aria-label":t,"aria-labelledby":n,className:`lockerverse-payment__select-trigger`,children:[V(U.Value,{}),V(U.Icon,{"aria-hidden":`true`,className:`lockerverse-payment__select-icon`,children:V(ne,{})})]}),V(U.Portal,{container:u,children:V(U.Positioner,{alignItemWithTrigger:!1,className:`lockerverse-payment__select-positioner`,sideOffset:6,children:V(U.Popup,{className:`lockerverse-payment__select-popup`,children:V(U.List,{className:`lockerverse-payment__select-list`,children:c.map(e=>H(U.Item,{className:`lockerverse-payment__select-item`,value:e.value,children:[V(U.ItemText,{children:e.label}),V(U.ItemIndicator,{"aria-hidden":`true`,className:`lockerverse-payment__select-item-indicator`,children:V(K,{})})]},e.value))})})})})]})})}const J=[`XS`,`S`,`M`,`L`,`XL`,`XXL`,`XXXL`],re=[`15`,`12`,`10`,`5`],Y=[...re,`custom`];function ie({enabled:e,error:t,errorId:n,onChange:r,values:i}){if(!e)return null;let a=e=>r({...i,...e}),o=(e,t)=>{let n=Y.indexOf(t),r;switch(e.key){case`ArrowDown`:case`ArrowRight`:r=(n+1)%Y.length;break;case`ArrowLeft`:case`ArrowUp`:r=(n-1+Y.length)%Y.length;break;case`Home`:r=0;break;case`End`:r=Y.length-1;break;default:return}e.preventDefault();let i=Y[r];i&&((e.currentTarget.closest(`[role="radiogroup"]`)?.querySelectorAll(`input[type="radio"]`))?.[r]?.focus(),a({tipPercent:i}))};return H(`div`,{className:`lockerverse-payment__tip-box`,children:[V(`p`,{children:`Add a tip to support the Lockerverse platform`}),H(`div`,{"aria-label":`Tip amount`,role:`radiogroup`,children:[re.map(e=>H(`label`,{className:`lockerverse-payment__tip-choice`,children:[V(`input`,{checked:i.tipPercent===e,name:`tipPercent`,onChange:()=>a({tipPercent:e}),onKeyDown:t=>o(t,e),tabIndex:i.tipPercent===e?0:-1,type:`radio`,value:e}),H(`span`,{children:[e,`%`]})]},e)),H(`label`,{className:`lockerverse-payment__tip-choice`,children:[V(`input`,{checked:i.tipPercent===`custom`,name:`tipPercent`,onChange:()=>a({tipPercent:`custom`}),onKeyDown:e=>o(e,`custom`),tabIndex:i.tipPercent===`custom`?0:-1,type:`radio`,value:`custom`}),V(`span`,{children:`Other`})]})]}),i.tipPercent===`custom`?H(`label`,{children:[V(`span`,{children:`Custom tip`}),H(`span`,{className:`lockerverse-payment__money-input`,children:[V(`span`,{"aria-hidden":`true`,children:`$`}),V(`input`,{"aria-describedby":t?n:void 0,"aria-invalid":t?`true`:void 0,inputMode:`decimal`,name:`tip`,onChange:e=>a({customTip:e.currentTarget.value}),placeholder:`0.00`,value:i.customTip})]}),t?V(`span`,{className:`lockerverse-payment__field-message`,id:n,children:t}):null]}):V(`input`,{name:`tip`,type:`hidden`,value:i.tipPercent})]})}function ae({checked:e,children:t,name:n,onChange:r}){return H(`label`,{className:`lockerverse-payment__check-row`,children:[V(`input`,{checked:e,name:n,onChange:e=>r(e.currentTarget.checked),type:`checkbox`}),V(`span`,{children:t})]})}function oe({customFields:e,errors:t,fields:n,idPrefix:r,isPromoApplying:i,onChange:a,onApplyPromo:o,promoError:c,values:l}){let u=e=>a({...l,...e});return H(`div`,{className:`lockerverse-payment__additional-fields`,children:[n.memberId?H(`label`,{children:[V(`span`,{children:`Member ID`}),V(`input`,{name:`memberId`,onChange:e=>u({memberId:e.currentTarget.value}),placeholder:`Optional`,value:l.memberId})]}):null,n.merchSize?H(`div`,{className:`lockerverse-payment__field`,children:[V(`span`,{id:`${r}-merch-size-label`,children:`Size`}),V(q,{ariaLabelledBy:`${r}-merch-size-label`,name:`merchSize`,onValueChange:e=>u({merchSize:e}),options:J.map(e=>({label:e,value:e})),value:l.merchSize})]}):null,n.promoCode?H(`div`,{className:`lockerverse-payment__field`,children:[V(`span`,{id:`${r}-promo-code-label`,children:`Promo code`}),H(`div`,{className:`lockerverse-payment__promo-control`,children:[V(`input`,{"aria-describedby":c?`${r}-promo-code-error`:void 0,"aria-invalid":c?`true`:void 0,"aria-labelledby":`${r}-promo-code-label`,name:`promoCode`,onChange:e=>u({promoCode:e.currentTarget.value}),placeholder:`Optional`,value:l.promoCode}),V(`button`,{disabled:!l.promoCode.trim()||i,onClick:o,type:`button`,children:i?`Applying…`:`Apply`})]}),c?V(`p`,{className:`lockerverse-payment__field-message`,id:`${r}-promo-code-error`,role:`alert`,children:c}):null]}):null,V(s,{choiceClassName:`lockerverse-payment__check-row`,errorClassName:`lockerverse-payment__field-message`,errors:t,fields:e,idPrefix:r,onChange:e=>u({customFields:e}),values:l.customFields})]})}function X({amountCents:e,enabled:t,onChange:n,values:r}){return t?H(ae,{checked:r.includeServiceFee,name:`includeServiceFee`,onChange:e=>n({...r,includeServiceFee:e}),children:[`Add `,se(e),` to help cover processing fees`]}):null}function se(e){return new Intl.NumberFormat(`en-US`,{currency:`USD`,style:`currency`}).format(e/100)}function ce(e){return c(e)}function le(t,n){let r=n?{...t,phone:ce(t.phone)}:t,a=N(n?{email:i,phone:e}:{email:i}),o=I(a,r);if(o.success)return{errors:{},value:o.output};let s={};for(let e of o.issues){let t=e.path?.[0]?.key;(t===`email`||t===`phone`)&&!s[t]&&(s[t]=e.message)}return{errors:s,value:null}}const ue=P(R(),z(),j()),de=P(M(),ee(),A(1)),fe=P(O(te([L({amountCents:de,productSlug:ue}),L({productSlug:ue,quantity:de}),L({productSlug:ue})])),k(1)),pe=P(R(),z(),F(/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/,`Enter a valid tip amount.`));function me(e){let t=I(pe,e);if(!t.success)return{message:t.issues[0]?.message??`Enter a valid tip amount.`,success:!1};let[n=`0`,r=``]=t.output.split(`.`),i=BigInt(n)*100n+BigInt(r.padEnd(2,`0`));return i>BigInt(2**53-1)?{message:`Enter a valid tip amount.`,success:!1}:{cents:Number(i),success:!0}}function he(e){let t=I(fe,e);return t.success?{success:!0,value:t.output}:{message:`Lockerverse payment configuration is invalid.`,success:!1}}function ge(e,t){switch(t.type){case`loading`:return{configuration:t.configuration,phase:`loading`,revision:e.revision,selectionKey:t.selectionKey};case`ready`:return{catalog:t.catalog,checkoutItems:t.checkoutItems,client:t.client,configuration:t.configuration,phase:`ready`,preparedCheckout:t.preparedCheckout,revision:e.revision+1,selectionKey:t.selectionKey};case`error`:return{configuration:t.configuration,failure:t.failure,phase:`error`,revision:e.revision,selectionKey:t.selectionKey};case`checkout`:return e.phase===`ready`?{...e,preparedCheckout:t.preparedCheckout}:e;case`retry`:return{phase:`idle`,revision:e.revision+1};default:return e}}function _e(e,t){let{apiBaseUrl:n,catalog:r,communitySlug:i,environment:a,fetch:o,requestTimeoutMs:s,sentryDsn:c,widgetSlug:l}=e,u={communitySlug:i,...r?{preloadedCatalog:r}:{},widgetSlug:l,...o?{fetch:o}:{},...t?{onError:t}:{},...s===void 0?{}:{requestTimeoutMs:s},...c===void 0?{}:{sentryDsn:c}};if(n===void 0){if(a===`development`)throw TypeError(`Lockerverse development checkout requires an API base URL.`);return{...u,...a===`production`?{environment:a}:{}}}return{...u,apiBaseUrl:n,...a===void 0?{}:{environment:a}}}function ve(e,t,n){return e?.configuration===t&&e.selectionKey===n}function ye({apiBaseUrl:e,catalog:t,communitySlug:n,environment:r,fetch:i,onError:a,paymentState:o,requestTimeoutMs:s,selection:c,sentryDsn:l,widgetSlug:u}){let f=v(()=>({apiBaseUrl:e,catalog:t??void 0,communitySlug:n,environment:r,fetch:i,requestTimeoutMs:s,sentryDsn:l,widgetSlug:u}),[e,t,n,r,i,s,l,u]),p=he(c),m=p.success?JSON.stringify(p.value):`invalid-selection`,g=v(()=>p.success?JSON.parse(m):[],[p.success,m]),[_,x]=y(ge,{phase:`idle`,revision:0}),S=b(void 0),C=b(void 0),w=b(a);return w.current=a,h(()=>{if(!p.success||o===`submitting`||o===`success`||o===`unresolved`||ve(C.current,f,m)||ve(S.current,f,m))return;let e=!0,t={configuration:f,selectionKey:m};S.current=t,x({configuration:f,selectionKey:m,type:`loading`});async function n(){try{let n=d(_e(f,e=>w.current?.(e))),{catalog:r,checkout:i}=await n.bootstrapCheckout({items:g}),a=[...i.items];e&&(S.current=void 0,C.current=t,x({catalog:r,checkoutItems:a,client:n,configuration:f,preparedCheckout:i,selectionKey:m,type:`ready`}))}catch(n){e&&(S.current=void 0,C.current=t,x({configuration:f,failure:n instanceof Error?n.message:`Lockerverse payment could not load.`,selectionKey:m,type:`error`}))}}return n(),()=>{e=!1,ve(S.current,f,m)&&(S.current=void 0)}},[f,p.success,o,m,_.revision,g]),{retryCheckout:()=>{S.current=void 0,C.current=void 0,x({type:`retry`})},selectionError:p.success?void 0:p.message,session:_,updateCheckout:e=>x({preparedCheckout:e,type:`checkout`})}}const be=[`amountCents`,`discountableSubtotalCents`,`discountCents`,`serviceFeeCents`,`subtotalCents`,`tipCents`,`totalCents`],xe=[`discountableSubtotalCents`,`discountCents`,`subtotalCents`];function Se(e,t,n){return(n===t.totalCents?xe:be).some(n=>e[n]!==t[n])||e.payment.connectedAccountId!==t.payment.connectedAccountId||e.payment.currency!==t.payment.currency||JSON.stringify(e.appliedDiscount)!==JSON.stringify(t.appliedDiscount)||JSON.stringify(e.lineItems)!==JSON.stringify(t.lineItems)}function Ce(e){return e.checkoutStatus===`success`?{kind:`success`,payment:e}:e.checkoutStatus===`failed`?{kind:`failed`,payment:e}:{kind:`unresolved`,paymentReference:e.paymentReference,reason:e.checkoutStatus===`action_required`?`action_required`:`pending`}}async function we(e,t,n){if(t.checkoutStatus!==`action_required`)return Ce(t);if(!n)return{kind:`unresolved`,paymentReference:t.paymentReference,reason:`action_required`};if(t.clientSecret)try{await n.handleNextAction({clientSecret:t.clientSecret})}catch{}try{return Ce(await e.getPaymentStatus(t.paymentReference))}catch{return{kind:`unresolved`,paymentReference:t.paymentReference,reason:`action_required`}}}async function Te(e,t,n){let r;try{r=await e.submitPayment(t)}catch(n){if(!(n instanceof u&&n.recoveryRecommended))throw n;try{r=await e.getPaymentStatus(t.checkout.paymentReference)}catch{return{kind:`unresolved`,paymentReference:t.checkout.paymentReference,reason:`recovery_failed`}}}return we(e,r,n)}async function Ee(e,t,n){try{return we(e,await e.getPaymentStatus(t),n)}catch{return{kind:`unresolved`,paymentReference:t,reason:`recovery_failed`}}}function De(e){throw Error(`Unexpected payment workflow value: ${String(e)}`)}function Oe(e,t){return t===void 0?{phase:e}:{error:t,phase:e}}function ke(e){return e?{phase:`recovering`}:{phase:`editing`}}function Ae(e){return e.phase===`editing`||e.phase===`invalid`?e.error:e.phase===`refreshing_quote`?e.previousError:void 0}function je(e){return e.phase===`succeeded`?`success`:e.phase===`unresolved`?`unresolved`:e.phase===`submitting`||e.phase===`recovering`?`submitting`:e.phase===`invalid`?`invalid`:Ae(e)?`error`:`idle`}function Me(e){return e.phase===`submitting`}function Ne(e,t){if(e.phase===`succeeded`||e.phase===`unresolved`)return e;switch(t.type){case`field_changed`:return e.phase===`invalid`?Oe(`editing`,e.error):e;case`validation_failed`:return e.phase===`submitting`||e.phase===`recovering`?e:Oe(`invalid`,Ae(e));case`quote_refresh_started`:{if(e.phase===`submitting`||e.phase===`recovering`)return e;let n=Ae(e);return{...n===void 0?{}:{previousError:n},phase:`refreshing_quote`,validatePromo:t.validatePromo}}case`quote_refresh_succeeded`:return e.phase===`refreshing_quote`?{phase:`editing`}:e;case`quote_refresh_failed`:return e.phase===`refreshing_quote`?Oe(`editing`,t.error??e.previousError):e;case`submission_started`:return e.phase===`recovering`?e:{phase:`submitting`};case`quote_changed`:return e.phase===`submitting`?{phase:`editing`}:e;case`retryable_failure`:return Oe(`editing`,t.error);case`recovery_failed`:return e.phase===`recovering`?Oe(`editing`,t.error):e;case`succeeded`:return e.phase===`submitting`||e.phase===`recovering`?{message:t.message,phase:`succeeded`}:e;case`unresolved`:return e.phase===`submitting`||e.phase===`recovering`?{message:t.message,paymentReference:t.paymentReference,phase:`unresolved`,reason:t.reason}:e;default:return De(t)}}function Pe(e,t){return t.tipPercent===`custom`?t.customTip.trim()?me(t.customTip):{cents:0,success:!0}:{cents:Math.round(e*Number(t.tipPercent)/100),success:!0}}function Fe(e,t,n,r){return{...n?{email:n}:{},...e.widget.fields.serviceFee?{includeServiceFee:t.includeServiceFee}:{},...e.widget.fields.promoCode&&t.promoCode.trim()?{promoCode:t.promoCode.trim()}:{},...e.widget.fields.tipping?{tipCents:r}:{}}}function Ie(e,t){if(!e?.complete)throw Error(`${t} address is required.`);return e.value}function Le(e,t,n,r){if(e.widget.fields.shipping)return t.shippingMatchesBilling?n:Ie(r.shipping,`Shipping`)}function Re({billingAddress:e,catalog:t,email:n,phone:r,shippingAddress:i}){return{payment_method_data:{billing_details:{address:e.address,email:n,name:e.name,...t.widget.fields.phone?{phone:r}:{}}},...i?{shipping:{address:i.address,name:i.name,phone:t.widget.fields.phone?r:i.phone??null}}:{}}}function ze({catalog:e,confirmationToken:n,email:r,fieldValues:i,metadata:a,phone:o,shippingAddress:s}){return{...n?{confirmationToken:n}:{},customFieldAnswers:t(e.widget.customFields,i.customFields),email:r,...a?{metadata:a}:{},...e.widget.fields.memberId&&i.memberId.trim()?{memberId:i.memberId.trim()}:{},...e.widget.fields.merchSize?{merchSize:i.merchSize}:{},...e.widget.fields.phone?{phone:o}:{},...s?{shipping:{address:{city:s.address.city??``,country:s.address.country,line1:s.address.line1??``,...s.address.line2?{line2:s.address.line2}:{},postal_code:s.address.postal_code??``,state:s.address.state??``},name:s.name}}:{}}}function Z(e,t){try{e?.(t)}catch{}}function Q(e){if(!e())throw Error(`Payment component is no longer active.`)}async function Be({addresses:e,catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:o,isAttemptActive:s,locallyPreviewedTotalCents:c,metadata:l,onPaymentRecoveryChange:u,phone:d,quote:f,stripe:p}){let m=a.trim().toLowerCase(),h=ce(d),g=Pe(f.subtotalCents,o);if(!g.success)throw Error(g.message);let _=Fe(t,o,m,g.cents),v=await r.calculateTotal({..._,items:n});if(Q(s),v.totalCents>0&&Se(f,v,c))return{kind:`quote_changed`,quote:v};if(v.totalCents===0){let n;t.widget.fields.shipping&&(n=Le(t,o,Ie(e.billing,`Billing`),e)),Q(s),Z(u,{connectedAccountId:v.payment.connectedAccountId,paymentReference:v.paymentReference});let i=await Te(r,{checkout:v,submission:ze({catalog:t,email:m,fieldValues:o,metadata:l,phone:h,...n?{shippingAddress:n}:{}})},p);return Q(s),i.kind===`failed`?{kind:`payment_failed`,message:`Order could not be completed. Review the details and try again.`}:i.kind===`unresolved`?{kind:`payment_unresolved`,paymentReference:i.paymentReference,reason:i.reason}:{kind:`payment`,payment:i.payment,quote:v}}if(!(i&&p))throw Error(`Payment form is still loading.`);await i.update({amount:v.totalCents}),Q(s);let y=await i.submit();if(Q(s),y.error)throw Error(y.error.message);let b=Ie(e.billing,`Billing`),x=Le(t,o,b,e),S=await p.createConfirmationToken({elements:i,params:Re({billingAddress:b,catalog:t,email:m,phone:h,shippingAddress:x})});if(Q(s),S.error)throw Error(S.error.message);Z(u,{connectedAccountId:v.payment.connectedAccountId,paymentReference:v.paymentReference});let C=await Te(r,{checkout:v,submission:ze({catalog:t,confirmationToken:S.confirmationToken.id,email:m,fieldValues:o,metadata:l,phone:h,...x?{shippingAddress:x}:{}})},p);return Q(s),C.kind===`failed`?{kind:`payment_failed`,message:`Payment was declined. Check your payment details and try again.`}:C.kind===`unresolved`?{kind:`payment_unresolved`,paymentReference:C.paymentReference,reason:C.reason}:{kind:`payment`,payment:C.payment,quote:v}}function Ve(e){return new Intl.NumberFormat(`en-US`,{currency:`USD`,style:`currency`}).format(e/100)}function He(e,t){if(!t)return e instanceof Error?e.message:`The order total could not be updated.`}function Ue({nextQuote:e,onQuoteChange:t,setDisplayedTotalCents:n,setPromoError:r,updateWorkflow:i,validatePromo:a}){i({type:`quote_refresh_succeeded`}),n(e.totalCents),t(e),a&&r(e.appliedDiscount?.source===`promo_code`?void 0:`This promo code is invalid or cannot be applied.`)}function We({error:e,setPromoError:t,updateWorkflow:n,validatePromo:r}){r&&t(`This promo code is invalid or cannot be applied.`);let i=He(e,r);n(i===void 0?{type:`quote_refresh_failed`}:{error:i,type:`quote_refresh_failed`})}function Ge({onPaymentComplete:e,onPaymentRecoveryChange:t,onPaymentUncertain:n,onQuoteChange:r,result:i,setDisplayedTotalCents:a,transitionWorkflow:o}){if(i.kind===`quote_changed`){let e=`The total changed to ${Ve(i.quote.totalCents)}. Review it and pay again.`;r(i.quote,e),a(i.quote.totalCents),o({type:`quote_changed`});return}if(i.kind===`payment_failed`){Z(t,null),o({error:i.message,type:`retryable_failure`});return}if(i.kind===`payment_unresolved`){o({message:`Payment is still processing. Do not submit it again.`,paymentReference:i.paymentReference,reason:i.reason,type:`unresolved`});try{n?.({paymentReference:i.paymentReference,reason:i.reason})}catch{}return}r(i.quote),Z(t,null),o({message:i.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`});try{e?.(i.payment)}catch{}}function Ke(e){let{catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:o,metadata:s,onPaymentComplete:c,onPaymentRecoveryChange:l,onPaymentUncertain:u,onQuoteChange:d,onStateChange:f,quote:m,resumePayment:g,stripe:_}=e,[v,S]=y(Ne,g,ke),[C,w]=x(m.totalCents),[T,E]=x(),D=b(!1),O=b(0),k=b(0),A=b(v);A.current=v;let j=p((e,t=!1)=>{let n=A.current,r=Ne(n,e);r!==n&&(A.current=r,S(e),t&&f(je(r)))},[f]),M=p(e=>j(e,!0),[j]),N=p(()=>{let e=k.current+1;return k.current=e,()=>k.current===e},[]);h(()=>()=>{k.current+=1},[]);let P=t.widget.fields.tipping?Pe(m.subtotalCents,o):{cents:0,success:!0},F=P.success?P.cents:null;h(()=>{if(F===null)return;let e=t.widget.fields.serviceFee&&o.includeServiceFee?m.serviceFeeCents||Math.round(m.subtotalCents*t.pricingPolicy.serviceFeeRateBasisPoints/1e4):0,n=m.totalCents-m.serviceFeeCents-m.tipCents+e+F;w(n),n>0&&i?.update({amount:n})},[t.pricingPolicy.serviceFeeRateBasisPoints,t.widget.fields.serviceFee,i,o.includeServiceFee,F,m.serviceFeeCents,m.tipCents,m.totalCents,m.subtotalCents]),h(()=>{if(!(g&&_)||D.current)return;D.current=!0;let e=N();return f(je(A.current)),Ee(r,g.paymentReference,_).then(t=>{if(e()){if(t.kind===`failed`){Z(l,null),M({error:`The previous payment failed. Check your details and try again.`,type:`recovery_failed`});return}if(t.kind===`unresolved`){M({message:`Payment is still processing. Do not submit it again.`,paymentReference:t.paymentReference,reason:t.reason,type:`unresolved`});try{u?.({paymentReference:t.paymentReference,reason:t.reason})}catch{}return}Z(l,null),M({message:t.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`});try{c?.(t.payment)}catch{}}}),()=>{e()&&(k.current+=1),D.current=!1}},[r,c,l,u,f,g,_,N,M]);let ee=p((e=!1)=>{e&&E(void 0),j({type:`field_changed`})},[j]);async function I(e=!1,i=!1){let s=le({email:a.trim().toLowerCase(),phone:``},!1);if(!(P.success&&(s.value||e)))return;O.current+=1;let c=O.current;j({type:`quote_refresh_started`,validatePromo:i});try{let e=await r.calculateTotal({...Fe(t,o,s.value?.email??``,P.cents),items:n});if(c!==O.current)return;Ue({nextQuote:e,onQuoteChange:d,setDisplayedTotalCents:w,setPromoError:E,updateWorkflow:j,validatePromo:i})}catch(e){if(c!==O.current)return;We({error:e,setPromoError:E,updateWorkflow:j,validatePromo:i})}}async function L(){E(void 0),await I(!0,!0)}async function R({addresses:e,phone:f}){M({type:`submission_started`});let p=N();try{let h=await Be({addresses:e,catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:o,isAttemptActive:p,locallyPreviewedTotalCents:C,metadata:s,onPaymentRecoveryChange:l,phone:f,quote:m,stripe:_});if(!p())return;Ge({onPaymentComplete:c,onPaymentRecoveryChange:l,onPaymentUncertain:u,onQuoteChange:d,result:h,setDisplayedTotalCents:w,transitionWorkflow:M})}catch(e){if(!p())return;Z(l,null),M({error:e instanceof Error?e.message:`Payment could not be completed.`,type:`retryable_failure`})}}let z=v.phase===`succeeded`||v.phase===`unresolved`?v.message:void 0;return{commands:{applyPromo:L,fieldChanged:ee,refreshAuthoritativeTotal:I,reportStripeLoadError:e=>M({error:e,type:`retryable_failure`}),reportValidationFailure:()=>M({type:`validation_failed`}),submit:R},state:{displayedTotalCents:C,isRecovering:v.phase===`recovering`,isRefreshingQuote:v.phase===`refreshing_quote`,isSubmitting:Me(v),parsedTip:P,paymentError:Ae(v),promoError:T,terminalMessage:z}}}function $(e){return new Intl.NumberFormat(`en-US`,{currency:`USD`,style:`currency`}).format(e/100)}function qe(e){return e===`monthly`?{interval:`month`,label:`Monthly`}:e===`annually`?{interval:`year`,label:`Annual`}:null}const Je=[{callingCode:`+1`,label:`🇺🇸 +1`,value:`US`},{callingCode:`+52`,label:`🇲🇽 +52`,value:`MX`},{callingCode:`+380`,label:`🇺🇦 +380`,value:`UA`},{callingCode:`+48`,label:`🇵🇱 +48`,value:`PL`},{callingCode:`+1`,label:`🇨🇦 +1`,value:`CA`},{callingCode:`+49`,label:`🇩🇪 +49`,value:`DE`},{callingCode:`+44`,label:`🇬🇧 +44`,value:`GB`},{callingCode:`+46`,label:`🇸🇪 +46`,value:`SE`},{callingCode:`+358`,label:`🇫🇮 +358`,value:`FI`},{callingCode:`+1`,label:`🇵🇷 +1`,value:`PR`}];function Ye(e,t){return e.trim().startsWith(`+`)?e:`${Je.find(e=>e.value===t)?.callingCode??`+1`}${e}`}function Xe({accentColor:e,catalog:t,checkoutItems:n,client:r,fontFamily:i,metadata:a,onPaymentComplete:o,onPaymentRecoveryChange:s,onPaymentUncertain:c,onQuoteChange:l,quote:u,resumePayment:d,onStateChange:f,stripeLoader:p,theme:m,visualStyle:h}){let g=d?d.connectedAccountId:u.payment.connectedAccountId,_=v(()=>p(t.payment.publishableKey,g?{stripeAccount:g}:void 0).catch(()=>null),[t.payment.publishableKey,g,p]);return V(C,{options:{amount:Math.max(u.totalCents,100),appearance:{rules:{".Input:focus":{borderColor:e,boxShadow:`0 0 0 1px ${e}`,outline:`none`}},theme:m===`light`?`stripe`:`night`,variables:{borderRadius:h?.[`--lockerverse-radius`]??`10px`,colorBackground:h?.[`--lockerverse-control`]??(m===`light`?`#f5f6f7`:`#121212`),colorDanger:h?.[`--lockerverse-danger`]??(m===`light`?`#c52b3e`:`#f08a98`),colorPrimary:e,colorText:h?.[`--lockerverse-text`]??(m===`light`?`#121416`:`#ffffff`),colorTextPlaceholder:h?.[`--lockerverse-placeholder`]??(m===`light`?`#72767d`:`#6b6b6b`),colorTextSecondary:h?.[`--lockerverse-muted`]??(m===`light`?`#62666d`:`#a1a1aa`),focusBoxShadow:`none`,focusOutline:`none`,fontFamily:i,fontSizeBase:`16px`}},currency:u.payment.currency,excludedPaymentMethodTypes:[`us_bank_account`],mode:u.paymentOption===`one-time`?`payment`:`subscription`,syncAddressCheckbox:`none`},stripe:_,children:V(st,{catalog:t,checkoutItems:n,client:r,metadata:a,onPaymentComplete:o,onPaymentRecoveryChange:s,onPaymentUncertain:c,onQuoteChange:l,onStateChange:f,quote:u,resumePayment:d})},`${t.payment.publishableKey}:${g??`platform`}:${u.paymentOption}`)}function Ze({label:e}){return H(`div`,{className:`lockerverse-payment__stripe-loader`,role:`status`,children:[V(`p`,{children:e}),H(`div`,{"aria-hidden":`true`,children:[V(`span`,{}),V(`span`,{}),V(`span`,{})]})]})}function Qe({onError:e,onReady:t,ready:n}){return H(`div`,{className:`lockerverse-payment__stripe-element`,"data-ready":n,children:[n?null:V(Ze,{label:`Loading payment form...`}),V(`div`,{className:`lockerverse-payment__stripe-mount`,children:V(w,{onLoadError:({error:t})=>e(t.message??`Payment form failed to load.`),onReady:t,options:{business:{name:`Lockerverse`},fields:{billingDetails:{address:`never`,email:`never`,name:`never`,phone:`never`}},layout:`tabs`,terms:{applePay:`auto`,auBecsDebit:`never`,bancontact:`never`,card:`always`,cashapp:`never`,googlePay:`never`,ideal:`never`,paypal:`auto`,sepaDebit:`never`,sofort:`never`,usBankAccount:`never`},wallets:{applePay:`auto`,googlePay:`never`}}})})]})}function $e({label:e,mode:t,onChange:n,onError:r,onReady:i,ready:a}){return H(`div`,{className:`lockerverse-payment__address`,children:[V(`h2`,{children:e}),H(`div`,{className:`lockerverse-payment__stripe-element lockerverse-payment__stripe-element--address`,"data-ready":a,children:[a?null:V(Ze,{label:`Loading ${e.toLowerCase()}...`}),V(`div`,{className:`lockerverse-payment__stripe-mount`,children:V(S,{onChange:n,onLoadError:({error:t})=>r(t.message??`${e} failed to load.`),onReady:i,options:{autocomplete:{mode:`automatic`},mode:t}})})]})]})}function et({message:e}){return e?V(`p`,{className:`lockerverse-payment__field-message`,role:`alert`,children:e}):null}function tt({catalog:e,displayedTotalCents:t,fieldValues:n,isBillingAddressReady:r,isPaymentReady:i,isShippingAddressReady:a,onAddressChange:o,onFieldValuesChange:s,onStripeLoadError:c,setIsBillingAddressReady:l,setIsPaymentReady:u,setIsShippingAddressReady:d}){let f=t>0;return H(B,{children:[f?V(Qe,{onError:c,onReady:()=>u(!0),ready:i}):null,f||e.widget.fields.shipping?V($e,{label:f?`Billing address`:`Shipping address`,mode:`billing`,onChange:e=>o(`billing`,e),onError:c,onReady:()=>l(!0),ready:r}):null,e.widget.fields.shipping?H(`div`,{className:`lockerverse-payment__shipping`,children:[V(ae,{checked:n.shippingMatchesBilling,name:`shippingMatchesBilling`,onChange:e=>{s({...n,shippingMatchesBilling:e}),e?o(`shipping`,null):d(!1)},children:`Shipping is same as billing information`}),n.shippingMatchesBilling?null:V($e,{label:`Shipping address`,mode:`shipping`,onChange:e=>o(`shipping`,e),onError:c,onReady:()=>d(!0),ready:a})]}):null]})}function nt({displayedBaseCents:e,displayedTipCents:t,displayedTotalCents:n,quote:r}){let i=qe(r.paymentOption),a=Math.max(0,e-r.subtotalCents+r.discountCents);return H(`section`,{"aria-label":`Payment summary`,className:`lockerverse-payment__payment-summary`,children:[V(`h2`,{children:`Order summary`}),V(`div`,{className:`lockerverse-payment__payment-summary-items`,children:r.lineItems.map(e=>H(`div`,{className:`lockerverse-payment__payment-summary-row`,children:[H(`span`,{children:[e.productName,e.quantity>1?H(B,{children:[` `,H(`small`,{children:[`× `,e.quantity]})]}):null,e.paymentOption===`monthly`?V(`small`,{children:` · Monthly`}):null,e.paymentOption===`annually`?V(`small`,{children:` · Annual`}):null]}),V(`strong`,{children:$(e.subtotalCents)})]},e.listingId))}),H(`div`,{className:`lockerverse-payment__payment-summary-totals`,children:[a>0?H(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-detail`,children:[V(`span`,{children:`Service fee`}),V(`strong`,{children:$(a)})]}):null,r.discountCents>0&&r.appliedDiscount?H(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-discount`,children:[H(`span`,{children:[r.appliedDiscount.source===`email_list`?`Email discount`:`Promo code discount`,` `,`(`,r.appliedDiscount.percentageOff,`% off)`]}),H(`strong`,{children:[`-`,$(r.discountCents)]})]}):null,t>0?H(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-detail lockerverse-payment__payment-summary-tip`,children:[V(`span`,{children:`Tip`}),V(`strong`,{children:$(t)})]}):null,H(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-total`,children:[V(`span`,{children:i?`${i.label} total`:`Total`}),V(`strong`,{children:$(n)})]})]})]})}function rt({catalog:e,displayedTotalCents:t,fieldValues:n,isBillingAddressReady:r,isPaymentReady:i,isRequiredShippingReady:a,isSubmitting:o,onFieldValuesChange:s,quote:c}){let l=t===0,u=l?!e.widget.fields.shipping||r&&a:i&&r&&a,d=qe(c.paymentOption),f=l?`Complete order`:`Pay ${$(t)}`;!l&&d&&(f=`Subscribe for ${$(t)}/${d.interval}`),o&&(f=l?`Completing…`:`Processing…`);let p=`Process payment for ${$(t)} total`;return l?p=`Complete order`:d&&(p=`Start ${d.label.toLowerCase()} subscription for ${$(t)}`),H(`div`,{className:`lockerverse-payment__actions`,children:[V(X,{amountCents:c.serviceFeeCents||Math.round(c.subtotalCents*e.pricingPolicy.serviceFeeRateBasisPoints/1e4),enabled:e.widget.fields.serviceFee,onChange:s,values:n}),V(`button`,{"aria-busy":o,"aria-label":p,disabled:o||!u,type:`submit`,children:f})]})}function it(e,t){let n=e.elements.namedItem(t);if(n instanceof HTMLElement){n.focus();return}n instanceof RadioNodeList&&Array.from(n).find(e=>e instanceof HTMLElement)?.focus()}function at({customFieldErrors:e,emailRef:t,form:n,parsedTipSuccess:r,phoneRef:i,validationErrors:a}){if(a.email){t.current?.focus();return}if(a.phone){i.current?.focus();return}if(!r){n.querySelector(`[name="tip"]`)?.focus();return}let[o]=Object.keys(e);o&&it(n,`custom:${o}`)}function ot({email:e,emailDiscountPercentOff:t,emailErrorId:n,emailId:r,emailRef:i,errors:a,onEmailBlur:o,onEmailChange:s,onPhoneChange:c,onPhoneCountryChange:l,phone:u,phoneCountry:d,phoneEnabled:f,phoneErrorId:p,phoneId:m,phoneRef:h}){return H(`div`,{className:`lockerverse-payment__contact`,children:[V(`label`,{htmlFor:r,children:`Email`}),V(`input`,{"aria-describedby":a.email?n:void 0,"aria-invalid":a.email?`true`:void 0,autoComplete:`email`,id:r,name:`email`,onBlur:o,onChange:e=>s(e.currentTarget.value),placeholder:`name@example.com`,ref:i,type:`email`,value:e}),a.email?V(`p`,{className:`lockerverse-payment__field-message`,id:n,children:a.email}):null,t===void 0?null:H(`p`,{className:`lockerverse-payment__discount-message`,role:`status`,children:[`Your email qualifies for `,t,`% off.`]}),f?H(B,{children:[V(`label`,{htmlFor:m,children:`Phone`}),H(`div`,{className:`lockerverse-payment__phone-control`,children:[V(q,{ariaLabel:`Phone number country`,className:`lockerverse-payment__select--phone-country`,name:`phoneCountry`,onValueChange:l,options:Je,value:d}),V(`input`,{"aria-describedby":a.phone?p:void 0,"aria-invalid":a.phone?`true`:void 0,autoComplete:`tel`,id:m,inputMode:`tel`,name:`phone`,onChange:e=>c(e.currentTarget.value),placeholder:`(201) 555-0123`,ref:h,type:`tel`,value:u})]}),a.phone?V(`p`,{className:`lockerverse-payment__field-message`,id:p,children:a.phone}):null]}):null]})}function st({catalog:e,checkoutItems:t,client:n,metadata:r,onPaymentComplete:i,onPaymentRecoveryChange:o,onPaymentUncertain:s,onQuoteChange:c,onStateChange:u,quote:d,resumePayment:f}){let[p,m]=x(``),[_,v]=x(``),[y,S]=x(`US`),[C,w]=x({}),[D,O]=x({}),[k,A]=x(),[j,M]=x(!1),[N,P]=x(!1),[F,ee]=x(!1),[I,L]=x({customFields:a(e.widget.customFields),customTip:``,includeServiceFee:e.widget.fields.serviceFee,memberId:``,merchSize:`M`,promoCode:``,shippingMatchesBilling:!0,tipPercent:`10`}),R=b({billing:null,shipping:null}),z=b(null),te=b(null),B=b(null),U=b(d.totalCents>0),W=Ke({catalog:e,checkoutItems:t,client:n,elements:T(),email:p,fieldValues:I,metadata:r,onPaymentComplete:i,onPaymentRecoveryChange:o,onPaymentUncertain:s,onQuoteChange:c,onStateChange:u,quote:d,resumePayment:f,stripe:E()}),{displayedTotalCents:G,isRecovering:ne,isRefreshingQuote:K,isSubmitting:q,parsedTip:J,paymentError:re,promoError:Y,terminalMessage:ae}=W.state,X=`lockerverse-${g()}`,se=`${X}-email`,ce=`${se}-error`,ue=`${X}-phone`,de=`${ue}-error`,fe=`${X}-tip-error`,pe=(J.success?J.cents:null)??0,me=G-pe,he=!e.widget.fields.shipping||I.shippingMatchesBilling||F;h(()=>{q&&B.current?.focus()},[q]),h(()=>{let e=G>0;e&&!U.current&&(M(!1),P(!1)),U.current=e},[G]);function ge(e){W.commands.fieldChanged(),w(t=>{let n={...t};return delete n[e],n})}function _e(e){W.commands.fieldChanged(e.promoCode!==I.promoCode),L(e),O({}),A(void 0)}async function ve(t){t.preventDefault();let n=le({email:p,phone:Ye(_,y)},e.widget.fields.phone),r=l(e.widget.customFields,I.customFields);if(!(n.value&&J.success)||Object.keys(r).length>0){w(n.errors),O(r),A(J.success?void 0:J.message),W.commands.reportValidationFailure();let e=t.currentTarget;queueMicrotask(()=>{at({customFieldErrors:r,emailRef:z,form:e,parsedTipSuccess:J.success,phoneRef:te,validationErrors:n.errors})});return}w({}),O({}),await W.commands.submit({addresses:R.current,phone:Ye(_,y)})}return ae?V(`p`,{className:`lockerverse-payment__payment-status`,ref:B,role:`status`,tabIndex:-1,children:ae}):ne?V(`p`,{className:`lockerverse-payment__payment-status`,role:`status`,children:`Recovering payment…`}):H(`form`,{"aria-busy":q,className:`lockerverse-payment__form`,noValidate:!0,onSubmit:ve,children:[V(`div`,{"data-lockerverse-input-region":``,inert:q?!0:void 0,children:H(`fieldset`,{className:`lockerverse-payment__input-fieldset`,disabled:q,children:[V(nt,{displayedBaseCents:me,displayedTipCents:pe,displayedTotalCents:G,quote:d}),V(ie,{enabled:e.widget.fields.tipping,error:k,errorId:fe,onChange:_e,values:I}),V(ot,{email:p,emailDiscountPercentOff:d.appliedDiscount?.source===`email_list`?d.appliedDiscount.percentageOff:void 0,emailErrorId:ce,emailId:se,emailRef:z,errors:C,onEmailBlur:()=>W.commands.refreshAuthoritativeTotal(),onEmailChange:e=>{m(e),ge(`email`)},onPhoneChange:e=>{v(e),ge(`phone`)},onPhoneCountryChange:e=>{S(e),W.commands.fieldChanged()},phone:_,phoneCountry:y,phoneEnabled:e.widget.fields.phone,phoneErrorId:de,phoneId:ue,phoneRef:te}),V(tt,{catalog:e,displayedTotalCents:G,fieldValues:I,isBillingAddressReady:N,isPaymentReady:j,isShippingAddressReady:F,onAddressChange:(e,t)=>{R.current[e]=t},onFieldValuesChange:_e,onStripeLoadError:W.commands.reportStripeLoadError,setIsBillingAddressReady:P,setIsPaymentReady:M,setIsShippingAddressReady:ee}),V(oe,{customFields:e.widget.customFields,errors:D,fields:e.widget.fields,idPrefix:X,isPromoApplying:K,onApplyPromo:W.commands.applyPromo,onChange:_e,promoError:Y,values:I}),V(rt,{catalog:e,displayedTotalCents:G,fieldValues:I,isBillingAddressReady:N,isPaymentReady:j,isRequiredShippingReady:he,isSubmitting:q,onFieldValuesChange:_e,quote:d})]})}),q?V(`p`,{className:`lockerverse-payment__sr-only`,ref:B,role:`status`,tabIndex:-1,children:G===0?`Completing order…`:`Processing payment…`}):null,V(et,{message:re})]})}function ct(){return V(o,{fieldCount:2,label:`Loading payment…`,sectionCount:2,showCheckbox:!0})}function lt({apiBaseUrl:e,branding:t,catalog:i,className:a,communitySlug:o,environment:s,fetch:c,metadata:l,onError:u,onPaymentComplete:d,onPaymentRecoveryChange:f,onPaymentUncertain:m,requestTimeoutMs:g,resumePayment:v,selection:y,sentryDsn:S,style:C,stripeLoader:w=D,theme:T=`dark`,widgetSlug:E,...O}){let k=b(v).current,A=b(null),[j,M]=x(),[N,P]=x(`idle`),F=b(void 0),{retryCheckout:ee,selectionError:I,session:L,updateCheckout:R}=ye({apiBaseUrl:e,catalog:i??void 0,communitySlug:o,environment:s,fetch:c,onError:u,paymentState:N,requestTimeoutMs:g,selection:y,sentryDsn:S,widgetSlug:E}),z=L.phase===`ready`?L.revision:void 0,te=p(e=>{z!==void 0&&(F.current=z),P(e)},[z]);h(()=>{L.phase===`loading`&&M(void 0)},[L.phase]),_(()=>{L.phase===`ready`&&F.current!==L.revision&&P(e=>e===`success`||e===`unresolved`?e:`idle`)},[L.phase,L.revision]);let B=[`lockerverse-payment`,a].filter(Boolean).join(` `),U=t??(L.phase===`ready`?L.catalog.community:null),W=r(C?.[`--lockerverse-accent`]??U?.accentColor??`#38d77a`),ne=n(W),K={...C,...C?.[`--lockerverse-accent`]!==void 0||U?.accentColor?{"--lockerverse-accent":W}:{},...ne&&C?.[`--lockerverse-accent-contrast`]===void 0?{"--lockerverse-accent-contrast":ne}:{}};if(I)return V(`section`,{...O,className:B,"data-lockerverse-theme":T,role:`alert`,style:K,children:I});if(L.phase===`error`)return H(`section`,{...O,className:B,"data-lockerverse-theme":T,style:K,children:[V(`p`,{role:`alert`,children:L.failure}),V(`button`,{onClick:ee,type:`button`,children:`Retry`})]});if(L.phase!==`ready`)return V(`section`,{...O,"aria-busy":`true`,"aria-label":`Payment`,className:B,"data-lockerverse-theme":T,style:K,children:V(ct,{})});let{catalog:q,checkoutItems:J,client:re,preparedCheckout:Y}=L;return H(`section`,{...O,"aria-label":`Payment`,className:B,"data-lockerverse-theme":T,"data-payment-state":N,ref:A,style:K,children:[H(`header`,{children:[q.widget.showCommunityBranding&&U?H(`div`,{className:`lockerverse-payment__branding`,children:[U.imageUrl?V(`img`,{alt:U.name,height:`48`,src:U.imageUrl,width:`48`}):null,V(`strong`,{children:U.name})]}):null,V(`h1`,{children:q.widget.title??q.widget.name}),q.widget.description?V(`p`,{children:q.widget.description}):null]}),j?V(`p`,{className:`lockerverse-payment__payment-status`,role:`status`,children:j}):null,V(G,{container:A,children:V(Xe,{accentColor:W,catalog:q,checkoutItems:J,client:re,fontFamily:C?.[`--lockerverse-font-family`]??`ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,metadata:l,onPaymentComplete:d,onPaymentRecoveryChange:f,onPaymentUncertain:m,onQuoteChange:(e,t)=>{M(t),R(e)},onStateChange:te,quote:Y,resumePayment:k,stripeLoader:w,theme:T,visualStyle:K})})]})}export{lt as t};
|
|
1
|
+
import{a as e,c as t,d as n,f as r,i,l as a,o,s,t as c,u as l}from"./contact-validation.js";import{createContext as u,useCallback as d,useContext as f,useEffect as p,useId as m,useLayoutEffect as h,useMemo as g,useReducer as _,useRef as v,useState as y}from"react";import{loadStripe as b}from"@stripe/stripe-js";import{AddressElement as x,Elements as S,PaymentElement as C,useElements as w,useStripe as T}from"@stripe/react-stripe-js";import{array as E,minLength as D,minValue as O,nonEmpty as k,number as A,object as j,pipe as M,regex as N,safeInteger as P,safeParse as F,strictObject as I,string as L,trim as R,union as z}from"valibot";import{Fragment as B,jsx as V,jsxs as H}from"react/jsx-runtime";import{Select as U}from"@base-ui/react/select";import{LockerverseSdkError as W,estimateLockerverseCheckout as ee}from"@lockerverse/sdk/checkout";const te=u(void 0);function ne({children:e,container:t}){return V(te.Provider,{value:t,children:e})}function re(){return V(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 16 16`,children:V(`path`,{d:`m4 6 4 4 4-4`})})}function ie(){return V(`svg`,{"aria-hidden":`true`,fill:`none`,viewBox:`0 0 16 16`,children:V(`path`,{d:`m3 8 3 3 7-7`})})}function ae({ariaDescribedBy:e,ariaLabel:t,ariaLabelledBy:n,className:r,id:i,invalid:a=!1,name:o,onValueChange:s,options:c,value:l}){let u=f(te),d=[`lockerverse-payment__select`,r].filter(Boolean).join(` `);return V(`div`,{className:d,children:H(U.Root,{id:i,items:c,name:o,onValueChange:e=>{e!==null&&s(e)},value:l,children:[H(U.Trigger,{"aria-describedby":e,"aria-invalid":a||void 0,"aria-label":t,"aria-labelledby":n,className:`lockerverse-payment__select-trigger`,children:[V(U.Value,{}),V(U.Icon,{"aria-hidden":`true`,className:`lockerverse-payment__select-icon`,children:V(re,{})})]}),V(U.Portal,{container:u,children:V(U.Positioner,{alignItemWithTrigger:!1,className:`lockerverse-payment__select-positioner`,sideOffset:6,children:V(U.Popup,{className:`lockerverse-payment__select-popup`,children:V(U.List,{className:`lockerverse-payment__select-list`,children:c.map(e=>H(U.Item,{className:`lockerverse-payment__select-item`,value:e.value,children:[V(U.ItemText,{children:e.label}),V(U.ItemIndicator,{"aria-hidden":`true`,className:`lockerverse-payment__select-item-indicator`,children:V(ie,{})})]},e.value))})})})})]})})}const G=[`XS`,`S`,`M`,`L`,`XL`,`XXL`,`XXXL`],K=[`15`,`12`,`10`,`5`],q=[...K,`custom`];function oe({enabled:e,error:t,errorId:n,onChange:r,values:i}){if(!e)return null;let a=e=>r({...i,...e}),o=(e,t)=>{let n=q.indexOf(t),r;switch(e.key){case`ArrowDown`:case`ArrowRight`:r=(n+1)%q.length;break;case`ArrowLeft`:case`ArrowUp`:r=(n-1+q.length)%q.length;break;case`Home`:r=0;break;case`End`:r=q.length-1;break;default:return}e.preventDefault();let i=q[r];i&&((e.currentTarget.closest(`[role="radiogroup"]`)?.querySelectorAll(`input[type="radio"]`))?.[r]?.focus(),a({tipPercent:i}))};return H(`div`,{className:`lockerverse-payment__tip-box`,children:[V(`p`,{children:`Add a tip to support the Lockerverse platform`}),H(`div`,{"aria-label":`Tip amount`,role:`radiogroup`,children:[K.map(e=>H(`label`,{className:`lockerverse-payment__tip-choice`,children:[V(`input`,{checked:i.tipPercent===e,name:`tipPercent`,onChange:()=>a({tipPercent:e}),onKeyDown:t=>o(t,e),tabIndex:i.tipPercent===e?0:-1,type:`radio`,value:e}),H(`span`,{children:[e,`%`]})]},e)),H(`label`,{className:`lockerverse-payment__tip-choice`,children:[V(`input`,{checked:i.tipPercent===`custom`,name:`tipPercent`,onChange:()=>a({tipPercent:`custom`}),onKeyDown:e=>o(e,`custom`),tabIndex:i.tipPercent===`custom`?0:-1,type:`radio`,value:`custom`}),V(`span`,{children:`Other`})]})]}),i.tipPercent===`custom`?H(`label`,{children:[V(`span`,{children:`Custom tip`}),H(`span`,{className:`lockerverse-payment__money-input`,children:[V(`span`,{"aria-hidden":`true`,children:`$`}),V(`input`,{"aria-describedby":t?n:void 0,"aria-invalid":t?`true`:void 0,inputMode:`decimal`,name:`tip`,onChange:e=>a({customTip:e.currentTarget.value}),placeholder:`0.00`,value:i.customTip})]}),t?V(`span`,{className:`lockerverse-payment__field-message`,id:n,children:t}):null]}):V(`input`,{name:`tip`,type:`hidden`,value:i.tipPercent})]})}function se({checked:e,children:t,name:n,onChange:r}){return H(`label`,{className:`lockerverse-payment__check-row`,children:[V(`input`,{checked:e,name:n,onChange:e=>r(e.currentTarget.checked),type:`checkbox`}),V(`span`,{children:t})]})}function ce({customFields:e,errors:t,fields:n,idPrefix:r,isPromoApplying:i,onChange:a,onApplyPromo:o,promoError:c,values:l}){let u=e=>a({...l,...e});return H(`div`,{className:`lockerverse-payment__additional-fields`,children:[n.memberId?H(`label`,{children:[V(`span`,{children:`Member ID`}),V(`input`,{name:`memberId`,onChange:e=>u({memberId:e.currentTarget.value}),placeholder:`Optional`,value:l.memberId})]}):null,n.merchSize?H(`div`,{className:`lockerverse-payment__field`,children:[V(`span`,{id:`${r}-merch-size-label`,children:`Size`}),V(ae,{ariaLabelledBy:`${r}-merch-size-label`,name:`merchSize`,onValueChange:e=>u({merchSize:e}),options:G.map(e=>({label:e,value:e})),value:l.merchSize})]}):null,n.promoCode?H(`div`,{className:`lockerverse-payment__field`,children:[V(`span`,{id:`${r}-promo-code-label`,children:`Promo code`}),H(`div`,{className:`lockerverse-payment__promo-control`,children:[V(`input`,{"aria-describedby":c?`${r}-promo-code-error`:void 0,"aria-invalid":c?`true`:void 0,"aria-labelledby":`${r}-promo-code-label`,name:`promoCode`,onChange:e=>u({promoCode:e.currentTarget.value}),placeholder:`Optional`,value:l.promoCode}),V(`button`,{disabled:!l.promoCode.trim()||i,onClick:o,type:`button`,children:i?`Applying…`:`Apply`})]}),c?V(`p`,{className:`lockerverse-payment__field-message`,id:`${r}-promo-code-error`,role:`alert`,children:c}):null]}):null,V(s,{choiceClassName:`lockerverse-payment__check-row`,errorClassName:`lockerverse-payment__field-message`,errors:t,fields:e,idPrefix:r,onChange:e=>u({customFields:e}),values:l.customFields})]})}function J({amountCents:e,enabled:t,onChange:n,values:r}){return t?H(se,{checked:r.includeServiceFee,name:`includeServiceFee`,onChange:e=>n({...r,includeServiceFee:e}),children:[`Add `,Y(e),` to help cover processing fees`]}):null}function Y(e){return new Intl.NumberFormat(`en-US`,{currency:`USD`,style:`currency`}).format(e/100)}function le(e){return c(e)}function ue(t,n){let r=n?{...t,phone:le(t.phone)}:t,a=j(n?{email:i,phone:e}:{email:i}),o=F(a,r);if(o.success)return{errors:{},value:o.output};let s={};for(let e of o.issues){let t=e.path?.[0]?.key;(t===`email`||t===`phone`)&&!s[t]&&(s[t]=e.message)}return{errors:s,value:null}}function de(e){return{error:void 0,message:void 0,status:e?`recovering`:`editing`}}function X(e,t,n){return t.includes(e.status)?{...e,...n}:e}function fe(e,t){if(e.status===`succeeded`||e.status===`unresolved`)return e;switch(t.type){case`field_changed`:return X(e,[`invalid`],{status:`editing`});case`validation_failed`:return X(e,[`editing`],{status:`invalid`});case`quote_refresh_started`:return X(e,[`editing`,`invalid`],{status:`refreshing_quote`});case`quote_refresh_succeeded`:return X(e,[`refreshing_quote`],{error:void 0,status:`editing`});case`quote_refresh_failed`:return X(e,[`refreshing_quote`],{error:t.error??e.error,status:`editing`});case`submission_started`:return X(e,[`editing`,`invalid`,`refreshing_quote`],{error:void 0,status:`submitting`});case`quote_changed`:return X(e,[`submitting`],{status:`editing`});case`retryable_failure`:return X(e,[`editing`,`invalid`,`submitting`],{error:t.error,status:`editing`});case`recovery_failed`:return X(e,[`recovering`],{error:t.error,status:`editing`});case`succeeded`:return X(e,[`recovering`,`submitting`],{message:t.message,status:`succeeded`});case`unresolved`:return X(e,[`recovering`,`submitting`],{message:t.message,status:`unresolved`});default:return e}}function pe(e){return e.status===`editing`||e.status===`invalid`||e.status===`refreshing_quote`?e.error:void 0}function me(e){return e.status===`succeeded`?`success`:e.status===`unresolved`?`unresolved`:e.status===`submitting`||e.status===`recovering`?`submitting`:e.status===`invalid`?`invalid`:pe(e)?`error`:`idle`}function he(e){return e.status===`submitting`}const ge=[`amountCents`,`discountableSubtotalCents`,`discountCents`,`serviceFeeCents`,`subtotalCents`,`tipCents`,`totalCents`],_e=[`discountableSubtotalCents`,`discountCents`,`subtotalCents`];function ve(e,t,n,r){return(n===t.totalCents?_e:ge).some(n=>e[n]!==t[n])||r!==t.payment.connectedAccountId||e.authoritative&&(e.payment.connectedAccountId!==r||e.payment.currency!==t.payment.currency)||JSON.stringify(e.appliedDiscount)!==JSON.stringify(t.appliedDiscount)||JSON.stringify(e.lineItems)!==JSON.stringify(t.lineItems)}function ye(e){return e.checkoutStatus===`success`?{kind:`success`,payment:e}:e.checkoutStatus===`failed`?{kind:`failed`,payment:e}:{kind:`unresolved`,paymentReference:e.paymentReference,reason:e.checkoutStatus===`action_required`?`action_required`:`pending`}}async function be(e,t,n){if(t.checkoutStatus!==`action_required`)return ye(t);if(!n)return{kind:`unresolved`,paymentReference:t.paymentReference,reason:`action_required`};if(t.clientSecret)try{await n.handleNextAction({clientSecret:t.clientSecret})}catch{}try{return ye(await e.getPaymentStatus(t.paymentReference))}catch{return{kind:`unresolved`,paymentReference:t.paymentReference,reason:`action_required`}}}async function xe(e,t,n){let r;try{r=await e.submitPayment(t)}catch(n){if(!(n instanceof W&&n.recoveryRecommended))throw n;try{r=await e.getPaymentStatus(t.checkout.paymentReference)}catch{return{kind:`unresolved`,paymentReference:t.checkout.paymentReference,reason:`recovery_failed`}}}return be(e,r,n)}async function Se(e,t,n){try{return be(e,await e.getPaymentStatus(t),n)}catch{return{kind:`unresolved`,paymentReference:t,reason:`recovery_failed`}}}const Ce=M(L(),R(),k()),we=M(A(),P(),O(1)),Te=M(E(z([I({amountCents:we,productSlug:Ce}),I({productSlug:Ce,quantity:we}),I({productSlug:Ce})])),D(1)),Ee=M(L(),R(),N(/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/,`Enter a valid tip amount.`));function De(e){let t=F(Ee,e);if(!t.success)return{message:t.issues[0]?.message??`Enter a valid tip amount.`,success:!1};let[n=`0`,r=``]=t.output.split(`.`),i=BigInt(n)*100n+BigInt(r.padEnd(2,`0`));return i>BigInt(2**53-1)?{message:`Enter a valid tip amount.`,success:!1}:{cents:Number(i),success:!0}}function Oe(e){let t=F(Te,e);return t.success?{success:!0,value:t.output}:{message:`Lockerverse payment configuration is invalid.`,success:!1}}function ke(e,t){return t.tipPercent===`custom`?t.customTip.trim()?De(t.customTip):{cents:0,success:!0}:{cents:Math.round(e*Number(t.tipPercent)/100),success:!0}}function Ae(e,t,n,r){return{...n?{email:n}:{},...e.widget.fields.serviceFee?{includeServiceFee:t.includeServiceFee}:{},...e.widget.fields.promoCode&&t.promoCode.trim()?{promoCode:t.promoCode.trim()}:{},...e.widget.fields.tipping?{tipCents:r}:{}}}function je(e,t){if(!e?.complete)throw Error(`${t} address is required.`);return e.value}function Me(e,t,n,r){if(e.widget.fields.shipping)return t.shippingMatchesBilling?n:je(r.shipping,`Shipping`)}function Ne({billingAddress:e,catalog:t,email:n,phone:r,shippingAddress:i}){return{payment_method_data:{billing_details:{address:e.address,email:n,name:e.name,...t.widget.fields.phone?{phone:r}:{}}},...i?{shipping:{address:i.address,name:i.name,phone:t.widget.fields.phone?r:i.phone??null}}:{}}}function Pe({catalog:e,confirmationToken:n,email:r,fieldValues:i,metadata:a,phone:o,shippingAddress:s}){return{...n?{confirmationToken:n}:{},customFieldAnswers:t(e.widget.customFields,i.customFields),email:r,...a?{metadata:a}:{},...e.widget.fields.memberId&&i.memberId.trim()?{memberId:i.memberId.trim()}:{},...e.widget.fields.merchSize?{merchSize:i.merchSize}:{},...e.widget.fields.phone?{phone:o}:{},...s?{shipping:{address:{city:s.address.city??``,country:s.address.country,line1:s.address.line1??``,...s.address.line2?{line2:s.address.line2}:{},postal_code:s.address.postal_code??``,state:s.address.state??``},name:s.name}}:{}}}function Z(e,t){try{e?.(t)}catch{}}function Fe(e,t){try{e?.(t)}catch{}}function Q(e){if(!e())throw Error(`Payment component is no longer active.`)}function Ie(e,t,n){return e.kind===`unresolved`&&e.reason===`action_required`&&!t&&!n}async function Le({addresses:e,catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:o,isAttemptActive:s,locallyPreviewedTotalCents:c,metadata:l,onPaymentRecoveryChange:u,phone:d,quote:f,stripe:p,stripeConnectedAccountId:m}){let h=a.trim().toLowerCase(),g=le(d),_=ke(f.subtotalCents,o);if(!_.success)throw Error(_.message);let v=Ae(t,o,h,_.cents),y=await r.calculateTotal({...v,catalog:t,items:n});if(Q(s),y.totalCents>0&&ve(f,y,c,m))return{kind:`quote_changed`,quote:y};if(y.totalCents===0){let n;t.widget.fields.shipping&&(n=Me(t,o,je(e.billing,`Billing`),e)),Q(s),Z(u,{connectedAccountId:y.payment.connectedAccountId,paymentReference:y.paymentReference});let i=await xe(r,{checkout:y,submission:Pe({catalog:t,email:h,fieldValues:o,metadata:l,phone:g,...n?{shippingAddress:n}:{}})},p);return Q(s),i.kind===`failed`?{kind:`payment_failed`,message:`Order could not be completed. Review the details and try again.`}:i.kind===`unresolved`?{kind:`payment_unresolved`,paymentReference:i.paymentReference,reason:i.reason}:{kind:`payment`,payment:i.payment,quote:y}}if(!(i&&p))throw Error(`Payment form is still loading.`);await i.update({amount:y.totalCents}),Q(s);let b=await i.submit();if(Q(s),b.error)throw Error(b.error.message);let x=je(e.billing,`Billing`),S=Me(t,o,x,e),C=await p.createConfirmationToken({elements:i,params:Ne({billingAddress:x,catalog:t,email:h,phone:g,shippingAddress:S})});if(Q(s),C.error)throw Error(C.error.message);Z(u,{connectedAccountId:y.payment.connectedAccountId,paymentReference:y.paymentReference});let w=await xe(r,{checkout:y,submission:Pe({catalog:t,confirmationToken:C.confirmationToken.id,email:h,fieldValues:o,metadata:l,phone:g,...S?{shippingAddress:S}:{}})},p);return Q(s),w.kind===`failed`?{kind:`payment_failed`,message:`Payment was declined. Check your payment details and try again.`}:w.kind===`unresolved`?{kind:`payment_unresolved`,paymentReference:w.paymentReference,reason:w.reason}:{kind:`payment`,payment:w.payment,quote:y}}function Re(e){return new Intl.NumberFormat(`en-US`,{currency:`USD`,style:`currency`}).format(e/100)}function ze(e,t){if(!t)return e instanceof Error?e.message:`The order total could not be updated.`}function Be({nextQuote:e,onQuoteChange:t,setDisplayedTotalCents:n,setPromoError:r,updateWorkflow:i,validatePromo:a}){i({type:`quote_refresh_succeeded`}),n(e.totalCents),t(e),a&&r(e.appliedDiscount?.source===`promo_code`?void 0:`This promo code is invalid or cannot be applied.`)}function Ve({error:e,setPromoError:t,updateWorkflow:n,validatePromo:r}){r&&t(`This promo code is invalid or cannot be applied.`);let i=ze(e,r);n(i===void 0?{type:`quote_refresh_failed`}:{error:i,type:`quote_refresh_failed`})}function He({onPaymentComplete:e,onPaymentRecoveryChange:t,onPaymentUncertain:n,onQuoteChange:r,result:i,setDisplayedTotalCents:a,transitionWorkflow:o}){if(i.kind===`quote_changed`){let e=`The total changed to ${Re(i.quote.totalCents)}. Review it and pay again.`;r(i.quote,e),a(i.quote.totalCents),o({type:`quote_changed`});return}if(i.kind===`payment_failed`){Z(t,null),o({error:i.message,type:`retryable_failure`});return}if(i.kind===`payment_unresolved`){o({message:`Payment is still processing. Do not submit it again.`,type:`unresolved`}),Fe(n,{paymentReference:i.paymentReference,reason:i.reason});return}r(i.quote),Z(t,null),o({message:i.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`});try{e?.(i.payment)}catch{}}function Ue(e){let{catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:o,metadata:s,onPaymentComplete:c,onResumePaymentFailed:l,onPaymentRecoveryChange:u,onPaymentUncertain:f,onQuoteChange:m,onStateChange:h,quote:g,resumePayment:_,stripe:b,stripeConnectedAccountId:x,stripeLoadFailed:S,updateWorkflow:C,workflow:w}=e,[T,E]=y(g.totalCents),[D,O]=y(),k=v(!1),A=v(0),j=v(0),M=d(e=>C(e,!0),[C]),N=d(()=>{let e=j.current+1;return j.current=e,()=>j.current===e},[]);p(()=>()=>{j.current+=1,A.current+=1},[]);let P=t.widget.fields.tipping?ke(g.subtotalCents,o):{cents:0,success:!0},F=P.success?P.cents:null;p(()=>{if(F===null)return;let e=t.widget.fields.serviceFee&&o.includeServiceFee?g.serviceFeeCents||Math.round(g.subtotalCents*t.pricingPolicy.serviceFeeRateBasisPoints/1e4):0,n=g.totalCents-g.serviceFeeCents-g.tipCents+e+F;E(n),n>0&&i?.update({amount:n})},[t.pricingPolicy.serviceFeeRateBasisPoints,t.widget.fields.serviceFee,i,o.includeServiceFee,F,g.serviceFeeCents,g.tipCents,g.totalCents,g.subtotalCents]),p(()=>{if(!_||k.current||w.status!==`recovering`)return;k.current=!0;let e=N();return h(me(w)),Se(r,_.paymentReference,b).then(t=>{if(e()&&!Ie(t,b,S)){if(t.kind===`failed`){Z(u,null),l(),M({error:`The previous payment failed. Check your details and try again.`,type:`recovery_failed`});return}if(t.kind===`unresolved`){M({message:`Payment is still processing. Do not submit it again.`,type:`unresolved`}),Fe(f,{paymentReference:t.paymentReference,reason:t.reason});return}Z(u,null),M({message:t.payment.paymentRequired?`Payment completed successfully.`:`Order confirmed. No payment was required.`,type:`succeeded`});try{c?.(t.payment)}catch{}}}),()=>{e()&&(j.current+=1),k.current=!1}},[r,c,l,u,f,h,_,b,S,N,M,w]);let I=d((e=!1)=>{e&&O(void 0),C({type:`field_changed`})},[C]);async function L(e=!1,i=!1){let s=ue({email:a.trim().toLowerCase(),phone:``},!1);if(!(P.success&&(s.value||e)))return;A.current+=1;let c=A.current;C({type:`quote_refresh_started`});try{let e=await r.calculateTotal({...Ae(t,o,s.value?.email??``,P.cents),catalog:t,items:n});if(c!==A.current)return;Be({nextQuote:e,onQuoteChange:m,setDisplayedTotalCents:E,setPromoError:O,updateWorkflow:C,validatePromo:i})}catch(e){if(c!==A.current)return;Ve({error:e,setPromoError:O,updateWorkflow:C,validatePromo:i})}}async function R(){O(void 0),await L(!0,!0)}async function z({addresses:e,phone:l}){M({type:`submission_started`});let d=N();try{let p=await Le({addresses:e,catalog:t,checkoutItems:n,client:r,elements:i,email:a,fieldValues:o,isAttemptActive:d,locallyPreviewedTotalCents:T,metadata:s,onPaymentRecoveryChange:u,phone:l,quote:g,stripe:b,stripeConnectedAccountId:x});if(!d())return;He({onPaymentComplete:c,onPaymentRecoveryChange:u,onPaymentUncertain:f,onQuoteChange:m,result:p,setDisplayedTotalCents:E,transitionWorkflow:M})}catch(e){if(!d())return;Z(u,null),M({error:e instanceof Error?e.message:`Payment could not be completed.`,type:`retryable_failure`})}}let B=w.status===`succeeded`||w.status===`unresolved`?w.message:void 0;return{commands:{applyPromo:R,fieldChanged:I,refreshAuthoritativeTotal:L,reportStripeLoadError:e=>M({error:e,type:`retryable_failure`}),reportValidationFailure:()=>M({type:`validation_failed`}),submit:z},state:{displayedTotalCents:T,isRecovering:w.status===`recovering`,isRefreshingQuote:w.status===`refreshing_quote`,isSubmitting:he(w),parsedTip:P,paymentError:pe(w),promoError:D,terminalMessage:B}}}function $(e){return new Intl.NumberFormat(`en-US`,{currency:`USD`,style:`currency`}).format(e/100)}function We(e){return e===`monthly`?{interval:`month`,label:`Monthly`}:e===`annually`?{interval:`year`,label:`Annual`}:null}const Ge=[{callingCode:`+1`,label:`🇺🇸 +1`,value:`US`},{callingCode:`+52`,label:`🇲🇽 +52`,value:`MX`},{callingCode:`+380`,label:`🇺🇦 +380`,value:`UA`},{callingCode:`+48`,label:`🇵🇱 +48`,value:`PL`},{callingCode:`+1`,label:`🇨🇦 +1`,value:`CA`},{callingCode:`+49`,label:`🇩🇪 +49`,value:`DE`},{callingCode:`+44`,label:`🇬🇧 +44`,value:`GB`},{callingCode:`+46`,label:`🇸🇪 +46`,value:`SE`},{callingCode:`+358`,label:`🇫🇮 +358`,value:`FI`},{callingCode:`+1`,label:`🇵🇷 +1`,value:`PR`}];function Ke(e,t){return e.trim().startsWith(`+`)?e:`${Ge.find(e=>e.value===t)?.callingCode??`+1`}${e}`}function qe(e,t,n){if(n){let{connectedAccountId:e}=n;return e}if(`payment`in t){let{connectedAccountId:e}=t.payment;return e}let{connectedAccountId:r}=e.payment;return r}function Je({accentColor:e,catalog:t,checkoutItems:n,client:r,fontFamily:i,metadata:a,onPaymentComplete:o,onResumePaymentFailed:s,onPaymentRecoveryChange:c,onPaymentUncertain:l,onQuoteChange:u,quote:f,resumePayment:m,onStateChange:h,stripeLoader:_,theme:b,visualStyle:x}){let[C,w]=y(()=>de(!!m)),T=v(C);T.current=C;let E=d((e,t=!1)=>{let n=fe(T.current,e);n!==T.current&&(T.current=n,w(n),t&&h(me(n)))},[h]),D=qe(t,f,m),O=v({connectedAccountId:D,paymentOption:f.paymentOption});C.status!==`submitting`&&C.status!==`recovering`&&(O.current={connectedAccountId:D,paymentOption:f.paymentOption});let{connectedAccountId:k,paymentOption:A}=O.current,j=g(()=>_(t.payment.publishableKey,k?{stripeAccount:k}:void 0).catch(()=>null),[t.payment.publishableKey,k,_]),[M,N]=y(!1);return p(()=>{let e=!0;return N(!1),j.then(t=>{e&&t===null&&N(!0)}),()=>{e=!1}},[j]),V(S,{options:{amount:Math.max(f.totalCents,100),appearance:{rules:{".Input:focus":{borderColor:e,boxShadow:`0 0 0 1px ${e}`,outline:`none`}},theme:b===`light`?`stripe`:`night`,variables:{borderRadius:x?.[`--lockerverse-radius`]??`10px`,colorBackground:x?.[`--lockerverse-control`]??(b===`light`?`#f5f6f7`:`#121212`),colorDanger:x?.[`--lockerverse-danger`]??(b===`light`?`#c52b3e`:`#f08a98`),colorPrimary:e,colorText:x?.[`--lockerverse-text`]??(b===`light`?`#121416`:`#ffffff`),colorTextPlaceholder:x?.[`--lockerverse-placeholder`]??(b===`light`?`#72767d`:`#6b6b6b`),colorTextSecondary:x?.[`--lockerverse-muted`]??(b===`light`?`#62666d`:`#a1a1aa`),focusBoxShadow:`none`,focusOutline:`none`,fontFamily:i,fontSizeBase:`16px`}},currency:t.payment.currency,excludedPaymentMethodTypes:[`us_bank_account`],mode:A===`one-time`?`payment`:`subscription`,syncAddressCheckbox:`none`},stripe:j,children:V(at,{catalog:t,checkoutItems:n,client:r,metadata:a,onPaymentComplete:o,onPaymentRecoveryChange:c,onPaymentUncertain:l,onQuoteChange:u,onResumePaymentFailed:s,onStateChange:h,quote:f,resumePayment:m,stripeConnectedAccountId:k,stripeLoadFailed:M,updateWorkflow:E,workflowState:C})},`${t.payment.publishableKey}:${k??`platform`}:${A}`)}function Ye({label:e}){return H(`div`,{className:`lockerverse-payment__stripe-loader`,role:`status`,children:[V(`p`,{children:e}),H(`div`,{"aria-hidden":`true`,children:[V(`span`,{}),V(`span`,{}),V(`span`,{})]})]})}function Xe({onError:e,onReady:t,ready:n}){return H(`div`,{className:`lockerverse-payment__stripe-element`,"data-ready":n,children:[n?null:V(Ye,{label:`Loading payment form...`}),V(`div`,{className:`lockerverse-payment__stripe-mount`,children:V(C,{onLoadError:({error:t})=>e(t.message??`Payment form failed to load.`),onReady:t,options:{business:{name:`Lockerverse`},fields:{billingDetails:{address:`never`,email:`never`,name:`never`,phone:`never`}},layout:`tabs`,terms:{applePay:`auto`,auBecsDebit:`never`,bancontact:`never`,card:`always`,cashapp:`never`,googlePay:`never`,ideal:`never`,paypal:`auto`,sepaDebit:`never`,sofort:`never`,usBankAccount:`never`},wallets:{applePay:`auto`,googlePay:`never`}}})})]})}function Ze({label:e,mode:t,onChange:n,onError:r,onReady:i,ready:a}){return H(`div`,{className:`lockerverse-payment__address`,children:[V(`h2`,{children:e}),H(`div`,{className:`lockerverse-payment__stripe-element lockerverse-payment__stripe-element--address`,"data-ready":a,children:[a?null:V(Ye,{label:`Loading ${e.toLowerCase()}...`}),V(`div`,{className:`lockerverse-payment__stripe-mount`,children:V(x,{onChange:n,onLoadError:({error:t})=>r(t.message??`${e} failed to load.`),onReady:i,options:{autocomplete:{mode:`automatic`},mode:t}})})]})]})}function Qe({message:e}){return e?V(`p`,{className:`lockerverse-payment__field-message`,role:`alert`,children:e}):null}function $e({catalog:e,displayedTotalCents:t,fieldValues:n,isBillingAddressReady:r,isPaymentReady:i,isShippingAddressReady:a,onAddressChange:o,onFieldValuesChange:s,onStripeLoadError:c,setIsBillingAddressReady:l,setIsPaymentReady:u,setIsShippingAddressReady:d}){let f=t>0;return H(B,{children:[f?V(Xe,{onError:c,onReady:()=>u(!0),ready:i}):null,f||e.widget.fields.shipping?V(Ze,{label:f?`Billing address`:`Shipping address`,mode:`billing`,onChange:e=>o(`billing`,e),onError:c,onReady:()=>l(!0),ready:r}):null,e.widget.fields.shipping?H(`div`,{className:`lockerverse-payment__shipping`,children:[V(se,{checked:n.shippingMatchesBilling,name:`shippingMatchesBilling`,onChange:e=>{s({...n,shippingMatchesBilling:e}),e?o(`shipping`,null):d(!1)},children:`Shipping is same as billing information`}),n.shippingMatchesBilling?null:V(Ze,{label:`Shipping address`,mode:`shipping`,onChange:e=>o(`shipping`,e),onError:c,onReady:()=>d(!0),ready:a})]}):null]})}function et({displayedBaseCents:e,displayedTipCents:t,displayedTotalCents:n,quote:r}){let i=We(r.paymentOption),a=Math.max(0,e-r.subtotalCents+r.discountCents);return H(`section`,{"aria-label":`Payment summary`,className:`lockerverse-payment__payment-summary`,children:[V(`h2`,{children:`Order summary`}),V(`div`,{className:`lockerverse-payment__payment-summary-items`,children:r.lineItems.map(e=>H(`div`,{className:`lockerverse-payment__payment-summary-row`,children:[H(`span`,{children:[e.productName,e.quantity>1?H(B,{children:[` `,H(`small`,{children:[`× `,e.quantity]})]}):null,e.paymentOption===`monthly`?V(`small`,{children:` · Monthly`}):null,e.paymentOption===`annually`?V(`small`,{children:` · Annual`}):null]}),V(`strong`,{children:$(e.subtotalCents)})]},e.listingId))}),H(`div`,{className:`lockerverse-payment__payment-summary-totals`,children:[a>0?H(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-detail`,children:[V(`span`,{children:`Service fee`}),V(`strong`,{children:$(a)})]}):null,r.discountCents>0&&r.appliedDiscount?H(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-discount`,children:[H(`span`,{children:[r.appliedDiscount.source===`email_list`?`Email discount`:`Promo code discount`,` `,`(`,r.appliedDiscount.percentageOff,`% off)`]}),H(`strong`,{children:[`-`,$(r.discountCents)]})]}):null,t>0?H(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-detail lockerverse-payment__payment-summary-tip`,children:[V(`span`,{children:`Tip`}),V(`strong`,{children:$(t)})]}):null,H(`div`,{className:`lockerverse-payment__payment-summary-row lockerverse-payment__payment-summary-total`,children:[V(`span`,{children:i?`${i.label} total`:`Total`}),V(`strong`,{children:$(n)})]})]})]})}function tt({catalog:e,displayedTotalCents:t,fieldValues:n,isBillingAddressReady:r,isPaymentReady:i,isRequiredShippingReady:a,isSubmitting:o,onFieldValuesChange:s,quote:c}){let l=t===0,u=l?!e.widget.fields.shipping||r&&a:i&&r&&a,d=We(c.paymentOption),f=l?`Complete order`:`Pay ${$(t)}`;!l&&d&&(f=`Subscribe for ${$(t)}/${d.interval}`),o&&(f=l?`Completing…`:`Processing…`);let p=`Process payment for ${$(t)} total`;return l?p=`Complete order`:d&&(p=`Start ${d.label.toLowerCase()} subscription for ${$(t)}`),H(`div`,{className:`lockerverse-payment__actions`,children:[V(J,{amountCents:c.serviceFeeCents||Math.round(c.subtotalCents*e.pricingPolicy.serviceFeeRateBasisPoints/1e4),enabled:e.widget.fields.serviceFee,onChange:s,values:n}),V(`button`,{"aria-busy":o,"aria-label":p,disabled:o||!u,type:`submit`,children:f})]})}function nt(e,t){let n=e.elements.namedItem(t);if(n instanceof HTMLElement){n.focus();return}n instanceof RadioNodeList&&Array.from(n).find(e=>e instanceof HTMLElement)?.focus()}function rt({customFieldErrors:e,emailRef:t,form:n,parsedTipSuccess:r,phoneRef:i,validationErrors:a}){if(a.email){t.current?.focus();return}if(a.phone){i.current?.focus();return}if(!r){n.querySelector(`[name="tip"]`)?.focus();return}let[o]=Object.keys(e);o&&nt(n,`custom:${o}`)}function it({email:e,emailDiscountPercentOff:t,emailErrorId:n,emailId:r,emailRef:i,errors:a,onEmailBlur:o,onEmailChange:s,onPhoneChange:c,onPhoneCountryChange:l,phone:u,phoneCountry:d,phoneEnabled:f,phoneErrorId:p,phoneId:m,phoneRef:h}){return H(`div`,{className:`lockerverse-payment__contact`,children:[V(`label`,{htmlFor:r,children:`Email`}),V(`input`,{"aria-describedby":a.email?n:void 0,"aria-invalid":a.email?`true`:void 0,autoComplete:`email`,id:r,name:`email`,onBlur:o,onChange:e=>s(e.currentTarget.value),placeholder:`name@example.com`,ref:i,type:`email`,value:e}),a.email?V(`p`,{className:`lockerverse-payment__field-message`,id:n,children:a.email}):null,t===void 0?null:H(`p`,{className:`lockerverse-payment__discount-message`,role:`status`,children:[`Your email qualifies for `,t,`% off.`]}),f?H(B,{children:[V(`label`,{htmlFor:m,children:`Phone`}),H(`div`,{className:`lockerverse-payment__phone-control`,children:[V(ae,{ariaLabel:`Phone number country`,className:`lockerverse-payment__select--phone-country`,name:`phoneCountry`,onValueChange:l,options:Ge,value:d}),V(`input`,{"aria-describedby":a.phone?p:void 0,"aria-invalid":a.phone?`true`:void 0,autoComplete:`tel`,id:m,inputMode:`tel`,name:`phone`,onChange:e=>c(e.currentTarget.value),placeholder:`(201) 555-0123`,ref:h,type:`tel`,value:u})]}),a.phone?V(`p`,{className:`lockerverse-payment__field-message`,id:p,children:a.phone}):null]}):null]})}function at({catalog:e,checkoutItems:t,client:n,metadata:r,onPaymentComplete:i,onResumePaymentFailed:o,onPaymentRecoveryChange:s,onPaymentUncertain:c,onQuoteChange:u,onStateChange:d,quote:f,resumePayment:h,stripeConnectedAccountId:g,stripeLoadFailed:_,updateWorkflow:b,workflowState:x}){let[S,C]=y(``),[E,D]=y(``),[O,k]=y(`US`),[A,j]=y({}),[M,N]=y({}),[P,F]=y(),[I,L]=y(!1),[R,z]=y(!1),[B,U]=y(!1),[W,ee]=y({customFields:a(e.widget.customFields),customTip:``,includeServiceFee:e.widget.fields.serviceFee,memberId:``,merchSize:`M`,promoCode:``,shippingMatchesBilling:!0,tipPercent:`10`}),te=v({billing:null,shipping:null}),ne=v(null),re=v(null),ie=v(null),ae=v(f.totalCents>0),G=Ue({catalog:e,checkoutItems:t,client:n,elements:w(),email:S,fieldValues:W,metadata:r,onPaymentComplete:i,onPaymentRecoveryChange:s,onPaymentUncertain:c,onQuoteChange:u,onResumePaymentFailed:o,onStateChange:d,quote:f,resumePayment:h,stripe:T(),stripeConnectedAccountId:g,stripeLoadFailed:_,updateWorkflow:b,workflow:x}),{displayedTotalCents:K,isRecovering:q,isRefreshingQuote:se,isSubmitting:J,parsedTip:Y,paymentError:le,promoError:de,terminalMessage:X}=G.state,fe=`lockerverse-${m()}`,pe=`${fe}-email`,me=`${pe}-error`,he=`${fe}-phone`,ge=`${he}-error`,_e=`${fe}-tip-error`,ve=(Y.success?Y.cents:null)??0,ye=K-ve,be=!e.widget.fields.shipping||W.shippingMatchesBilling||B;p(()=>{J&&ie.current?.focus()},[J]),p(()=>{let e=K>0;e&&!ae.current&&(L(!1),z(!1)),ae.current=e},[K]);function xe(e){G.commands.fieldChanged(),j(t=>{let n={...t};return delete n[e],n})}function Se(e){G.commands.fieldChanged(e.promoCode!==W.promoCode),ee(e),N({}),F(void 0)}async function Ce(t){t.preventDefault();let n=ue({email:S,phone:Ke(E,O)},e.widget.fields.phone),r=l(e.widget.customFields,W.customFields);if(!(n.value&&Y.success)||Object.keys(r).length>0){j(n.errors),N(r),F(Y.success?void 0:Y.message),G.commands.reportValidationFailure();let e=t.currentTarget;queueMicrotask(()=>{rt({customFieldErrors:r,emailRef:ne,form:e,parsedTipSuccess:Y.success,phoneRef:re,validationErrors:n.errors})});return}j({}),N({}),await G.commands.submit({addresses:te.current,phone:Ke(E,O)})}return X?V(`p`,{className:`lockerverse-payment__payment-status`,ref:ie,role:`status`,tabIndex:-1,children:X}):q?V(`p`,{className:`lockerverse-payment__payment-status`,role:`status`,children:`Recovering payment…`}):H(`form`,{"aria-busy":J,className:`lockerverse-payment__form`,noValidate:!0,onSubmit:Ce,children:[V(`div`,{"data-lockerverse-input-region":``,inert:J?!0:void 0,children:H(`fieldset`,{className:`lockerverse-payment__input-fieldset`,disabled:J,children:[V(et,{displayedBaseCents:ye,displayedTipCents:ve,displayedTotalCents:K,quote:f}),V(oe,{enabled:e.widget.fields.tipping,error:P,errorId:_e,onChange:Se,values:W}),V(it,{email:S,emailDiscountPercentOff:f.appliedDiscount?.source===`email_list`?f.appliedDiscount.percentageOff:void 0,emailErrorId:me,emailId:pe,emailRef:ne,errors:A,onEmailBlur:()=>G.commands.refreshAuthoritativeTotal(),onEmailChange:e=>{C(e),xe(`email`)},onPhoneChange:e=>{D(e),xe(`phone`)},onPhoneCountryChange:e=>{k(e),G.commands.fieldChanged()},phone:E,phoneCountry:O,phoneEnabled:e.widget.fields.phone,phoneErrorId:ge,phoneId:he,phoneRef:re}),V($e,{catalog:e,displayedTotalCents:K,fieldValues:W,isBillingAddressReady:R,isPaymentReady:I,isShippingAddressReady:B,onAddressChange:(e,t)=>{te.current[e]=t},onFieldValuesChange:Se,onStripeLoadError:G.commands.reportStripeLoadError,setIsBillingAddressReady:z,setIsPaymentReady:L,setIsShippingAddressReady:U}),V(ce,{customFields:e.widget.customFields,errors:M,fields:e.widget.fields,idPrefix:fe,isPromoApplying:se,onApplyPromo:G.commands.applyPromo,onChange:Se,promoError:de,values:W}),V(tt,{catalog:e,displayedTotalCents:K,fieldValues:W,isBillingAddressReady:R,isPaymentReady:I,isRequiredShippingReady:be,isSubmitting:J,onFieldValuesChange:Se,quote:f})]})}),J?V(`p`,{className:`lockerverse-payment__sr-only`,ref:ie,role:`status`,tabIndex:-1,children:K===0?`Completing order…`:`Processing payment…`}):null,V(Qe,{message:le})]})}function ot(){return V(o,{fieldCount:2,label:`Loading payment…`,sectionCount:2,showCheckbox:!0})}function st(e,t){switch(t.type){case`loading`:return{phase:`loading`,revision:e.revision};case`ready`:return dt(t.displayedQuote,e.revision+1);case`error`:return{failure:t.failure,phase:`error`,revision:e.revision};case`checkout`:return e.phase===`ready`?{...e,displayedQuote:t.checkout,quoteFailure:void 0}:e;case`quote-error`:return e.phase===`ready`?{...e,quoteFailure:t.failure}:e;default:return e}}function ct(e,t){return e===t}function lt({checkout:e}){return{displayedQuote:e,type:`ready`}}function ut(e){return e instanceof Error?e.message:`Lockerverse payment could not load.`}function dt(e,t){return{checkoutItems:[...e.items],displayedQuote:e,phase:`ready`,quoteFailure:void 0,revision:t}}function ft(e,t){let n=e.widget.fields.serviceFee;return ee(e,{includeServiceFee:n,selection:t})}function pt(e,t){try{return dt(ft(e,t),1)}catch(e){return{failure:ut(e),phase:`error`,revision:0}}}function mt({catalog:e,client:t,paymentState:n,selection:r}){let i=Oe(r),a=i.success?JSON.stringify(i.value):`invalid-selection`,o=g(()=>i.success?JSON.parse(a):[],[i.success,a]),[s,c]=_(st,void 0,()=>i.success?pt(e,o):{phase:`loading`,revision:0}),l=v(void 0),u=v(0),d=v(s.phase===`ready`?a:void 0),f=v(s.phase===`error`?a:void 0);p(()=>{if(!i.success||n===`submitting`||n===`success`||n===`unresolved`||ct(f.current,a)||ct(l.current,a))return;let r=!0;l.current=a;let s=d.current===a;s||c({type:`loading`});function p(e){r&&c(e)}function m(){r&&(l.current=void 0,f.current=a)}let h;function g(e){if(!r||(l.current=void 0,f.current=a,s&&h!==void 0&&u.current!==h))return;let t=ut(e);c(s?{failure:t,type:`quote-error`}:{failure:t,type:`error`})}async function _(){try{h=u.current;let n=e.widget.fields.serviceFee;if(!s){let t=ft(e,o);s=!0,d.current=a,p(lt({checkout:t}))}m();let r=await t.calculateTotal({catalog:e,includeServiceFee:n,selection:o});u.current===h&&p({checkout:r,type:`checkout`})}catch(e){g(e)}}return _(),()=>{r=!1,ct(l.current,a)&&(l.current=void 0)}},[e,t,i.success,n,a,o]);let m=n===`submitting`||n===`success`||n===`unresolved`,h=ct(d.current,a)||ct(f.current,a)||ct(l.current,a),y=m||h?s:{phase:`loading`,revision:s.revision};return{selectionError:i.success?void 0:i.message,session:y,updateCheckout:e=>{u.current+=1,c({checkout:e,type:`checkout`})}}}function ht({catalog:e,client:t,...i}){let{branding:a,className:o,metadata:s,onPaymentComplete:c,onPaymentRecoveryChange:l,onPaymentUncertain:u,resumePayment:f,selection:m,style:g,stripeLoader:_=b,theme:x=`dark`,...S}=i,[C,w]=y(f),T=v(null),[E,D]=y(),[O,k]=y(`idle`),A=v(void 0),{selectionError:j,session:M,updateCheckout:N}=mt({catalog:e,client:t,paymentState:O,selection:m}),P=M.phase===`ready`?M.revision:void 0,F=d(e=>{P!==void 0&&(A.current=P),k(e)},[P]),I=d(e=>{l?.(e)},[l]),L=d(()=>{w(void 0)},[]);p(()=>{M.phase===`loading`&&D(void 0)},[M.phase]),h(()=>{M.phase===`ready`&&A.current!==M.revision&&k(e=>e===`success`||e===`unresolved`?e:`idle`)},[M.phase,M.revision]);let R=[`lockerverse-payment`,o].filter(Boolean).join(` `),z=a??e.community,B=r(g?.[`--lockerverse-accent`]??z?.accentColor??`#38d77a`),U=n(B),W={...g,...g?.[`--lockerverse-accent`]!==void 0||z?.accentColor?{"--lockerverse-accent":B}:{},...U&&g?.[`--lockerverse-accent-contrast`]===void 0?{"--lockerverse-accent-contrast":U}:{}};return j?V(`section`,{...S,className:R,"data-lockerverse-theme":x,role:`alert`,style:W,children:j}):M.phase===`error`?V(`section`,{...S,className:R,"data-lockerverse-theme":x,style:W,children:V(`p`,{role:`alert`,children:M.failure})}):M.phase===`ready`?H(`section`,{...S,"aria-label":`Payment`,className:R,"data-lockerverse-theme":x,"data-payment-state":O,ref:T,style:W,children:[H(`header`,{children:[e.widget.showCommunityBranding&&z?H(`div`,{className:`lockerverse-payment__branding`,children:[z.imageUrl?V(`img`,{alt:z.name,height:`48`,src:z.imageUrl,width:`48`}):null,V(`strong`,{children:z.name})]}):null,V(`h1`,{children:e.widget.title??e.widget.name}),e.widget.description?V(`p`,{children:e.widget.description}):null]}),E?V(`p`,{className:`lockerverse-payment__payment-status`,role:`status`,children:E}):null,M.quoteFailure?H(`div`,{className:`lockerverse-payment__payment-status`,role:`alert`,children:[V(`span`,{children:M.quoteFailure}),V(`span`,{children:` The final total will be checked when you submit.`})]}):null,V(ne,{container:T,children:V(Je,{accentColor:B,catalog:e,checkoutItems:M.checkoutItems,client:t,fontFamily:g?.[`--lockerverse-font-family`]??`ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,metadata:s,onPaymentComplete:c,onPaymentRecoveryChange:I,onPaymentUncertain:u,onQuoteChange:(e,t)=>{D(t),N(e)},onResumePaymentFailed:L,onStateChange:F,quote:M.displayedQuote,resumePayment:C,stripeLoader:_,theme:x,visualStyle:W},M.revision)})]}):V(`section`,{...S,"aria-busy":`true`,"aria-label":`Payment`,className:R,"data-lockerverse-theme":x,style:W,children:V(ot,{})})}function gt({children:e,loading:t=!1,viewProps:i}){let{branding:a,className:o,metadata:s,onPaymentComplete:c,onPaymentRecoveryChange:l,onPaymentUncertain:u,resumePayment:d,selection:f,stripeLoader:p,style:m,theme:h=`dark`,...g}=i,_=r(m?.[`--lockerverse-accent`]??a?.accentColor??`#38d77a`),v=n(_),y={...m,...m?.[`--lockerverse-accent`]!==void 0||a?.accentColor?{"--lockerverse-accent":_}:{},...v&&m?.[`--lockerverse-accent-contrast`]===void 0?{"--lockerverse-accent-contrast":v}:{}};return V(`section`,{...g,...t?{"aria-busy":!0,"aria-label":`Payment`}:{},className:[`lockerverse-payment`,o].filter(Boolean).join(` `),"data-lockerverse-theme":h,style:y,children:e})}function _t({widget:e,...t}){return e.error?H(gt,{viewProps:t,children:[V(`p`,{role:`alert`,children:e.error.message}),V(`button`,{onClick:e.refresh,type:`button`,children:`Retry`})]}):e.loading||!e.catalog?V(gt,{loading:!0,viewProps:t,children:V(ot,{})}):V(ht,{catalog:e.catalog,client:e.client,...t})}export{_t as t};
|
|
2
2
|
//# sourceMappingURL=lockerverse-payment.js.map
|