@flopay/js 1.18.0 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{a as Y,b as G,c as J,d as ne,e as Q,f as Oe,g as Ue,h as X,i as ie,j as se,k as ae,l as le,m as ce,n as z,o as E,p as Le,q as Be,r as de,s as Z,t as ue}from"./chunk-WTVYMDK5.mjs";import{dropThirdPartyOnlyError as Kt}from"@flopay/shared";import{assertCaptureMethodEligible as Ne,buildProductPayload as qe,classifyTelemetryFailure as ze,FloPayError as O,foldIntoProducts as je,IDEMPOTENCY_IN_PROGRESS_CODE as Ve,IDEMPOTENCY_KEY_HEADER as $e,resolveIdempotencyKey as me,resolveSessionCurrency as Ke,SDK_VERSION as pe,telemetryStatusClass as ye,withTelemetryHttpDiagnostics as He}from"@flopay/shared";var te=5,fe=new WeakSet;function We(e){(typeof e=="object"&&e!==null||typeof e=="function")&&fe.add(e)}function Ye(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&fe.has(e)}function Ge(e,t){let r=t?.error,o=Y(t?.code)??Y(r?.code)??`http_${e}`,a=G(t?.message)??G(r?.message)??Je(o,e);return new O(a,"api_error",{code:o,statusCode:e})}function Je(e,t){switch(e){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${te}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${t}).`}}async function ge(e,t,r){let{billingApiUrl:o,checkoutBaseUrl:a,items:i=[],subscriptions:d=[],products:s,account:c,successUrl:n,cancelUrl:l,checkoutMode:m="confirm",captureMethod:h,couponCodes:w=[],checkoutMetadata:p,tagsData:g,redirectParams:I={},setCookie:f=!0,clientId:x,currency:k,utmMetadata:R,idempotencyKey:U}=e,F=me(U);if(w.length>te)throw new O(`Too many coupon codes \u2014 a checkout session accepts at most ${te}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let S=s??je(i,d);Ne({captureMethod:h,products:S});let _=Ke(k,i,d,S);if(!_)throw new O("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let C={clientId:x,checkoutVersion:pe,successUrl:n,cancelUrl:l,currency:_,checkoutMode:m,products:S.map(v=>qe(v,_)),accountData:{userId:c.userId,firstName:c.firstName??null,lastName:c.lastName??null,email:c.email,country:c.country??null,gender:c.gender??null,city:c.city??null,state:c.state??null,zip:c.zip??null,addressLine1:c.addressLine1??null,addressLine2:c.addressLine2??null},couponCodes:w};h==="manual"&&(C.captureMethod=h),p!==void 0&&(C.checkoutMetadata=p),g&&(C.tagsData=g),R&&R.length>0&&(C.utmMetadata=R);let q=`${o.replace(/\/+$/,"")}/v1/checkouts/sessions`,L={"Content-Type":"application/json"};F&&(L[$e]=F);let b,T,B={method:"POST",headers:L,body:JSON.stringify(C),signal:t},P;try{r?.startAttempt(),P=await fetch(q,B)}catch(v){throw We(v),v}try{r?.record(P.status)}catch{}b=P.status;try{T=await P.json()}catch{}if(b>=400)throw He(Ge(b,T),P);if(b===201){let v=T?.data?.uuid,D=T?.data?.nonce;if(!v)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!D)throw new O("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(S.length>0||_)&&Q(v,{currency:_,products:S.map(u=>({code:u.code??u.providerItemId??u.providerPlanId,type:u.type,name:u.name??u.itemName??u.providerItemName??u.subscriptionName??u.providerPlanName??null,totalAmount:u.totalAmount,overrideAmount:u.overrideAmount,currency:u.currency??_}))});let y=new URL(`${a.replace(/\/+$/,"")}/secure`);y.searchParams.set("id",v);for(let[u,A]of Object.entries(I))y.searchParams.set(u,A);if(f&&typeof window<"u"&&typeof document<"u"){let u=JSON.stringify({origin_url:l}),A=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(u)}; domain=.${A}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(D)}; domain=.${A}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=y.toString()),{status:201,redirectUrl:y.toString(),nonce:D}}return b===204?(typeof window<"u"&&(window.location.href=n),{status:204}):{status:b}}async function Qe(e){let t=Ce(e),r=he(t),o=J(e.timeoutMs);try{let a=await ge(e,o.signal,r);return r.commit(),ve(t,a),a}catch(a){throw r.commit(),j(t,a),a}finally{o.clear(),M(t.reporter)}}function he(e){let t=!1,r=e.startedAt,o;return{startAttempt(){r=e.reporter.now()},record(a){o={status:a,durationMs:Math.max(0,e.reporter.now()-r),attempt:e.attempt}},commit(){if(t||!o)return;t=!0;let a=ye(o.status);e.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:a,attempt:o.attempt}),e.reporter.performance({stage:"session_first_byte",durationMs:o.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:a,attempt:o.attempt})}}}function Ce(e){let t=new E({billingApiUrl:e.billingApiUrl,sdkVersion:pe,enabled:e.telemetry!==!1}),r=t.now();return t.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:t,startedAt:r,attempt:0}}function ve(e,t){let r=ye(t.status);e.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:r}),e.reporter.performance({stage:"session_create",durationMs:e.reporter.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:e.attempt})}function j(e,t){let{reporter:r}=e,o=ze(t,"CHECKOUT_SESSION_CREATE_FAILED");if(r.performance({stage:"session_create",durationMs:r.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:e.attempt}),t instanceof O&&t.type==="validation_error"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(o.statusClass==="4xx"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}r.error({...o,stage:"session_create",requestCategory:"session_create"})}function M(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}async function Xe(e){let{maxRetries:t=2,...r}=e,o=Ce(e),a=he(o);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0||t>=3)throw o.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),M(o.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let i={...r,idempotencyKey:me(r.idempotencyKey)},d=J(r.timeoutMs),s;for(let c=0;c<=t;c++){o.attempt=c;try{let n=await ge(i,d.signal,a);return a.commit(),ve(o,n),d.clear(),M(o.reporter),n}catch(n){s=n;let l=n instanceof Error&&n.name==="AbortError",m=Ye(n),h=n instanceof O&&n.code===Ve;if((l||m||h)&&!d.signal.aborted&&c<t){o.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:c+1});try{await ne(c,d.signal)}catch(w){throw a.commit(),j(o,w),d.clear(),M(o.reporter),w}continue}throw a.commit(),j(o,n),d.clear(),M(o.reporter),n}}throw a.commit(),j(o,s),d.clear(),M(o.reporter),s??new Error("Unknown error during checkout session creation")}import{classifyTelemetryFailure as Ze,FloPayError as V,resolveBillingApiUrl as Se,SDK_VERSION as et}from"@flopay/shared";var we=Symbol.for("@flopay/js.telemetry.bridge.v1");function _e(e,t,r){let o=()=>t?.now()??r();Object.defineProperty(e,we,{configurable:!1,enumerable:!1,writable:!1,value:{error:i=>t?.error(i),log:i=>t?.log(i),performance:i=>t?.performance(i),terminal:i=>t?.terminal(i),now:o,elapsed:i=>Math.max(0,o()-i),setCheckoutContext:i=>t?.setCheckoutContext(i),beginCheckout:(i={})=>t?.beginCheckout(i)??o(),disable:()=>t?.disable(),subscribe:i=>t?.subscribe(i)??(()=>{}),flush:()=>t?.flush()??Promise.resolve()}})}function be(e){return e[we]}var $=class{now(){return this.telemetryReporter?.now?.()??z()}constructor(t,r,o){this.provider=t,this.config=r,this.telemetryReporter=o??new E({billingApiUrl:Se(r.billingApiUrl),sdkVersion:et,enabled:r.telemetry!==!1}),_e(this,this.telemetryReporter,z)}cardCapture(t){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?ue({sessionId:t?.sessionId,captureMethod:t?.captureMethod,cardFieldsTimeoutMs:t?.cardFieldsTimeoutMs},this.telemetryReporter):new Z({sessionId:t?.sessionId,captureMethod:t?.captureMethod,cardFieldsTimeoutMs:t?.cardFieldsTimeoutMs,telemetry:!1})}async retrieveSession(t,r){if(!t)throw new V("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let o=await this.retrieveUnifiedSession(t,r);if(!o.data.session)throw new V("Session not found","api_error");return o.data.session}async retrieveUnifiedSession(t,r){if(!t)throw new V("sessionId is required.","validation_error",{param:"sessionId"});let o=Se(r??this.config.billingApiUrl),a=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let i,d,s=n=>{if(i===void 0)return;let l=i,m=d;i=void 0,d=void 0,this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:n,attempt:m}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:l,durationMode:"machine",requestCategory:"session_read",statusClass:n,attempt:m})},c=de(o,{now:()=>this.telemetryReporter?.now()??z(),onFirstByte:(n,l)=>{i=n,d=l},onRetry:(n,l)=>{this.telemetryReporter?.log({name:"operation.retry",stage:n==="session_read"?"session_read":"processing",requestCategory:n,attempt:l})}});try{let n=await c.getUnifiedCheckoutSession(t);return s("2xx"),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-a,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),n}catch(n){let l=Ze(n,n instanceof V&&n.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw s(l.statusClass),this.telemetryReporter?.error({...l,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-a,durationMode:"machine",requestCategory:"session_read",statusClass:l.statusClass}),n}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.provider.destroy()}};function Pe(e,t,r){let o=$;return new o(e,t,r)}import{FloPayError as nt,resolveBillingApiUrl as re,SDK_VERSION as Te}from"@flopay/shared";import{FloPayError as Ae}from"@flopay/shared";import{loadStripe as tt}from"@stripe/stripe-js";import{toStripeAppearance as rt,toStripeAppearanceTheme as ot}from"@flopay/shared";var ke=new WeakSet;function Re(e){return e instanceof Ae&&ke.has(e)}var N=class{constructor(){this.name="stripe";this.stripe=null}async initialize(t){if(typeof window>"u")return;let r=await tt(t.publishableKey,{locale:t.locale??"auto"});if(!r){let o=new Ae("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw ke.add(o),o}this.stripe=r}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var Ee=new Map;function oe(e){return Array.isArray(e)?e.map(oe):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,oe(r)])):e}function it(e,t){return JSON.stringify([e,re(t?.billingApiUrl),t?.telemetry!==!1,t?.locale??"auto",t?.apiVersion??null,oe(t?.appearance??null)])}var K=new Map;async function st(e,t){if(!e){let s=new E({billingApiUrl:re(t?.billingApiUrl),sdkVersion:Te,enabled:t?.telemetry!==!1});throw s.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),s.flush().catch(()=>{}).finally(()=>s.destroy()),new nt("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let r=it(e,t),o=Ee.get(r);if(o)return t?.telemetry!==!1&&be(o)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),o;let a=K.get(r);if(a)return a;let i={...t,publishableKey:e},d=(async()=>{let s=new E({billingApiUrl:re(i.billingApiUrl),sdkVersion:Te,enabled:i.telemetry!==!1}),c=s.now();s.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),s.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),s.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let n=new N,l=s.now();try{await n.initialize(i)}catch(w){throw s.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:Re(w)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),s.destroy(),w}let m=s.now();s.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),s.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),s.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),s.performance({stage:"sdk_initialize",durationMs:m-c,durationMode:"machine",provider:"stripe"}),s.performance({stage:"provider_ready",durationMs:m-l,durationMode:"machine",provider:"stripe"});let h=Pe(n,i,s);return Ee.set(r,h),h})();K.set(r,d);try{return await d}finally{K.get(r)===d&&K.delete(r)}}import{FloPayError as W,THREE_DS_CHALLENGE_WINDOW_MS as xe}from"@flopay/shared";var at=4,lt=1e3,ct=1e3,dt=15e3;function ut(e){let t=!!e?.gateways?.stripe,r=!!e?.gateways?.worldpayCorporateGateway;return t===r?"unknown":t?"stripe":"worldpay"}function mt(e,t,r){try{return typeof e?.beginThreeDsChallenge!="function"?void 0:e.beginThreeDsChallenge(t,{provider:ut(r)})}catch{return}}function H(e){return new W("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Fe(){return new W("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function De(e){return e.replace(/\/+$/,"")}function pt(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}function yt(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",r=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":case"authorized":case"pending":case"timeout":return{status:t,providerIntentId:r};case"declined":return{status:"declined",providerIntentId:r,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:r,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}async function Me(e){if(typeof document>"u"||typeof window>"u")throw new W("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});let t=X(e.telemetry);t.record("handoff_planned");let r=ie(e.nextActionRedirectUrl);r==="missing"?t.record("action_missing",{reason:"missing_url"}):r==="invalid"&&t.record("action_invalid",{reason:"invalid_url"});let o=p=>{let g=se(p);if(g==="buyer_cancel"){t.record("cancel_requested",{reason:g,evidenceBasis:"signal_reason"}),t.terminal("cancel",{reason:g,evidenceBasis:"signal_reason"});return}t.record("abort_observed",{reason:g,evidenceBasis:"signal_reason"}),t.terminal("abort",{reason:g,evidenceBasis:"signal_reason"})},a=p=>{(p.status==="succeeded"||p.status==="authorized"||p.status==="declined"||p.status==="timeout")&&t.reconcile(p.status)};if(e.signal?.aborted)throw o(e.signal.reason),H();let i=`${De(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,d=async()=>{let p=new AbortController,g=()=>p.abort();e.signal?.aborted?p.abort():e.signal?.addEventListener("abort",g);let I=window.setTimeout(()=>p.abort(),dt);try{let f=await fetch(i,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json",...t.attemptId?{"x-flopay-challenge-attempt":t.attemptId}:{}},body:"{}",signal:p.signal});if(!f.ok)return{status:"unknown"};let x=await f.json().catch(()=>null),k=yt(x);return a(k),k}catch{return{status:"unknown"}}finally{window.clearTimeout(I),e.signal?.removeEventListener("abort",g)}},s,c=()=>e.pollCompletionEndpoint!==!1?d():(s??(s=d()),s),n=document.activeElement instanceof HTMLElement?document.activeElement:null,l=document.createElement("div");l.setAttribute("data-flopay-auto-3ds-overlay","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let m=document.createElement("iframe");m.setAttribute("title","Card authentication"),m.setAttribute("allow","payment"),m.tabIndex=0,m.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let h=null;try{h=new URL(e.billingApiUrl,window.location.href).origin}catch{h=null}let w=ce(e.nextActionRedirectUrl);try{let p=await new Promise((g,I)=>{let f=!1,x=0,k=0,R=0,U=!1,F=!1,S=!1,_=0,C=()=>{window.clearTimeout(x),window.clearInterval(k),window.clearTimeout(R),window.removeEventListener("message",v),window.removeEventListener("pagehide",L),document.removeEventListener("securitypolicyviolation",b),m.removeEventListener("load",T),e.signal?.removeEventListener("abort",B)},q=async()=>{if(!(f||U)){U=!0;try{let y=await c();if(f||!pt(y))return;f=!0,C(),t.terminal("status_poll",{evidenceBasis:"server_status"}),g(y)}finally{U=!1}}},L=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},b=y=>{if(S)return;let u=le(y,w);u&&(S=!0,t.record("policy_violation",{reason:u,evidenceBasis:"parent_csp_event"}))},T=()=>{F||(F=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"})),e.pollCompletionEndpoint!==!1&&(window.clearTimeout(R),R=window.setTimeout(()=>{q()},250))},B=()=>{f||(f=!0,C(),o(e.signal?.reason),I(H()))},P=y=>{f||_>=at||(_+=1,t.record("return_rejected",{reason:y,evidenceBasis:"message_origin_check"}))},v=y=>{let u=y.data,A=!!u&&typeof u=="object"&&u.source==="flopay-vault-3ds-return";if(y.source!==m.contentWindow){A&&P("untrusted_source");return}if(h&&y.origin!==h){A&&P("untrusted_origin");return}A&&(f||(f=!0,C(),t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),g(null)))};x=window.setTimeout(()=>{f||(f=!0,C(),F||t.record("load_unconfirmed",{evidenceBasis:"no_load_signal"}),t.record("timer_expired",{reason:"window_elapsed",evidenceBasis:"timer"}),t.terminal("timer",{reason:"window_elapsed",evidenceBasis:"timer"}),I(Fe()))},xe),e.pollCompletionEndpoint!==!1&&(k=window.setInterval(()=>{q()},ct)),m.addEventListener("load",T),window.addEventListener("message",v),window.addEventListener("pagehide",L),document.addEventListener("securitypolicyviolation",b),e.signal?.addEventListener("abort",B),m.src=e.nextActionRedirectUrl,t.record("render_attempted");try{l.appendChild(m),document.body.appendChild(l)}catch(y){throw f=!0,C(),t.record("render_failed"),y}t.record("container_attached"),t.record("navigation_assigned");let D=ae(l);D&&t.record("container_visibility",{reason:D,evidenceBasis:"parent_computed_style"}),m.focus(),e.signal?.aborted&&B()});return p||await c()}finally{l.parentNode?.removeChild(l),t.record("teardown"),n?.isConnected&&n.focus()}}function Ie(e,t){try{let r=t.data.session?.status;r==="complete"?e.reconcile("succeeded"):r==="authorized"&&e.reconcile("authorized")}catch{}}function ft(e){return new W("Card was declined.","api_error",{code:e.declineReason??"authorization_declined",...e.gatewayDeclineReason?{declineCode:e.gatewayDeclineReason}:{}})}async function gt(e,t){let r=`${De(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/status`,o=new AbortController,a=new AbortController,i=()=>{o.abort(e.signal?.reason),a.abort(e.signal?.reason)};e.signal?.aborted?i():e.signal?.addEventListener("abort",i,{once:!0});let d=X(e.telemetry),s=Me({billingApiUrl:e.billingApiUrl,sessionId:e.sessionId,nonce:e.nonce,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o.signal,pollCompletionEndpoint:!1,...e.telemetry?{telemetry:e.telemetry}:{}}),c=t.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:lt,nonce:e.nonce,statusUrl:r,continueAfterActionRequired:!0,timeoutMs:xe+15e3,signal:a.signal,...d.attemptId?{challengeAttemptId:d.attemptId}:{}});c.catch(()=>{}),s.catch(()=>{});try{let n=await Promise.race([s,c]);if("data"in n)return d.terminal("status_poll",{evidenceBasis:"server_status"}),Ie(d,n),n;if(n.status==="declined")throw(e.createDeclineError??ft)(n);if(n.status==="timeout")throw Fe();let l=await c;return Ie(d,l),l}catch(n){throw e.signal?.aborted||n instanceof Error&&n.name==="AbortError"?H(n):n}finally{e.signal?.removeEventListener("abort",i),o.abort(),a.abort()}}export{$ as FloPay,Be as PaymentAPI,Z as PciVaultCardCapture,Le as SESSION_CREATE_TELEMETRY,N as StripeAdapter,mt as beginSavedCardChallengeTelemetry,Q as cacheSessionDisplayData,Ue as clearSessionDisplayData,gt as completeSavedCardNextAction,Qe as createCheckoutSession,Xe as createCheckoutSessionWithRetries,H as createSavedCardActionAbortedError,Kt as dropThirdPartyOnlyError,Oe as getSessionDisplayData,st as loadFloPay,Me as runSavedCardChallenge,rt as toStripeAppearance,ot as toStripeAppearanceTheme};
1
+ import{a as Y,b as G,c as J,d as ne,e as Q,f as Oe,g as Ue,h as X,i as ie,j as se,k as ae,l as le,m as ce,n as z,o as E,p as Le,q as Be,r as de,s as Z,t as ue}from"./chunk-SM2BLO3P.mjs";import{dropThirdPartyOnlyError as Kt}from"@flopay/shared";import{assertCaptureMethodEligible as Ne,buildProductPayload as qe,classifyTelemetryFailure as ze,FloPayError as O,foldIntoProducts as je,IDEMPOTENCY_IN_PROGRESS_CODE as Ve,IDEMPOTENCY_KEY_HEADER as $e,resolveIdempotencyKey as me,resolveSessionCurrency as Ke,SDK_VERSION as pe,telemetryStatusClass as ye,withTelemetryHttpDiagnostics as He}from"@flopay/shared";var te=5,fe=new WeakSet;function We(e){(typeof e=="object"&&e!==null||typeof e=="function")&&fe.add(e)}function Ye(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&fe.has(e)}function Ge(e,t){let r=t?.error,o=Y(t?.code)??Y(r?.code)??`http_${e}`,a=G(t?.message)??G(r?.message)??Je(o,e);return new O(a,"api_error",{code:o,statusCode:e})}function Je(e,t){switch(e){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${te}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${t}).`}}async function ge(e,t,r){let{billingApiUrl:o,checkoutBaseUrl:a,items:i=[],subscriptions:d=[],products:s,account:c,successUrl:n,cancelUrl:l,checkoutMode:m="confirm",captureMethod:h,couponCodes:w=[],checkoutMetadata:p,tagsData:g,redirectParams:I={},setCookie:f=!0,clientId:x,currency:k,utmMetadata:R,idempotencyKey:U}=e,F=me(U);if(w.length>te)throw new O(`Too many coupon codes \u2014 a checkout session accepts at most ${te}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let S=s??je(i,d);Ne({captureMethod:h,products:S});let _=Ke(k,i,d,S);if(!_)throw new O("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let C={clientId:x,checkoutVersion:pe,successUrl:n,cancelUrl:l,currency:_,checkoutMode:m,products:S.map(v=>qe(v,_)),accountData:{userId:c.userId,firstName:c.firstName??null,lastName:c.lastName??null,email:c.email,country:c.country??null,gender:c.gender??null,city:c.city??null,state:c.state??null,zip:c.zip??null,addressLine1:c.addressLine1??null,addressLine2:c.addressLine2??null},couponCodes:w};h==="manual"&&(C.captureMethod=h),p!==void 0&&(C.checkoutMetadata=p),g&&(C.tagsData=g),R&&R.length>0&&(C.utmMetadata=R);let q=`${o.replace(/\/+$/,"")}/v1/checkouts/sessions`,L={"Content-Type":"application/json"};F&&(L[$e]=F);let b,T,B={method:"POST",headers:L,body:JSON.stringify(C),signal:t},P;try{r?.startAttempt(),P=await fetch(q,B)}catch(v){throw We(v),v}try{r?.record(P.status)}catch{}b=P.status;try{T=await P.json()}catch{}if(b>=400)throw He(Ge(b,T),P);if(b===201){let v=T?.data?.uuid,D=T?.data?.nonce;if(!v)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!D)throw new O("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(S.length>0||_)&&Q(v,{currency:_,products:S.map(u=>({code:u.code??u.providerItemId??u.providerPlanId,type:u.type,name:u.name??u.itemName??u.providerItemName??u.subscriptionName??u.providerPlanName??null,totalAmount:u.totalAmount,overrideAmount:u.overrideAmount,currency:u.currency??_}))});let y=new URL(`${a.replace(/\/+$/,"")}/secure`);y.searchParams.set("id",v);for(let[u,A]of Object.entries(I))y.searchParams.set(u,A);if(f&&typeof window<"u"&&typeof document<"u"){let u=JSON.stringify({origin_url:l}),A=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(u)}; domain=.${A}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(D)}; domain=.${A}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=y.toString()),{status:201,redirectUrl:y.toString(),nonce:D}}return b===204?(typeof window<"u"&&(window.location.href=n),{status:204}):{status:b}}async function Qe(e){let t=Ce(e),r=he(t),o=J(e.timeoutMs);try{let a=await ge(e,o.signal,r);return r.commit(),ve(t,a),a}catch(a){throw r.commit(),j(t,a),a}finally{o.clear(),M(t.reporter)}}function he(e){let t=!1,r=e.startedAt,o;return{startAttempt(){r=e.reporter.now()},record(a){o={status:a,durationMs:Math.max(0,e.reporter.now()-r),attempt:e.attempt}},commit(){if(t||!o)return;t=!0;let a=ye(o.status);e.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:a,attempt:o.attempt}),e.reporter.performance({stage:"session_first_byte",durationMs:o.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:a,attempt:o.attempt})}}}function Ce(e){let t=new E({billingApiUrl:e.billingApiUrl,sdkVersion:pe,enabled:e.telemetry!==!1}),r=t.now();return t.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:t,startedAt:r,attempt:0}}function ve(e,t){let r=ye(t.status);e.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:r}),e.reporter.performance({stage:"session_create",durationMs:e.reporter.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:e.attempt})}function j(e,t){let{reporter:r}=e,o=ze(t,"CHECKOUT_SESSION_CREATE_FAILED");if(r.performance({stage:"session_create",durationMs:r.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:e.attempt}),t instanceof O&&t.type==="validation_error"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(o.statusClass==="4xx"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}r.error({...o,stage:"session_create",requestCategory:"session_create"})}function M(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}async function Xe(e){let{maxRetries:t=2,...r}=e,o=Ce(e),a=he(o);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0||t>=3)throw o.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),M(o.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let i={...r,idempotencyKey:me(r.idempotencyKey)},d=J(r.timeoutMs),s;for(let c=0;c<=t;c++){o.attempt=c;try{let n=await ge(i,d.signal,a);return a.commit(),ve(o,n),d.clear(),M(o.reporter),n}catch(n){s=n;let l=n instanceof Error&&n.name==="AbortError",m=Ye(n),h=n instanceof O&&n.code===Ve;if((l||m||h)&&!d.signal.aborted&&c<t){o.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:c+1});try{await ne(c,d.signal)}catch(w){throw a.commit(),j(o,w),d.clear(),M(o.reporter),w}continue}throw a.commit(),j(o,n),d.clear(),M(o.reporter),n}}throw a.commit(),j(o,s),d.clear(),M(o.reporter),s??new Error("Unknown error during checkout session creation")}import{classifyTelemetryFailure as Ze,FloPayError as V,resolveBillingApiUrl as Se,SDK_VERSION as et}from"@flopay/shared";var we=Symbol.for("@flopay/js.telemetry.bridge.v1");function _e(e,t,r){let o=()=>t?.now()??r();Object.defineProperty(e,we,{configurable:!1,enumerable:!1,writable:!1,value:{error:i=>t?.error(i),log:i=>t?.log(i),performance:i=>t?.performance(i),terminal:i=>t?.terminal(i),now:o,elapsed:i=>Math.max(0,o()-i),setCheckoutContext:i=>t?.setCheckoutContext(i),beginCheckout:(i={})=>t?.beginCheckout(i)??o(),disable:()=>t?.disable(),subscribe:i=>t?.subscribe(i)??(()=>{}),flush:()=>t?.flush()??Promise.resolve()}})}function be(e){return e[we]}var $=class{now(){return this.telemetryReporter?.now?.()??z()}constructor(t,r,o){this.provider=t,this.config=r,this.telemetryReporter=o??new E({billingApiUrl:Se(r.billingApiUrl),sdkVersion:et,enabled:r.telemetry!==!1}),_e(this,this.telemetryReporter,z)}cardCapture(t){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?ue({sessionId:t?.sessionId,captureMethod:t?.captureMethod,cardFieldsTimeoutMs:t?.cardFieldsTimeoutMs},this.telemetryReporter):new Z({sessionId:t?.sessionId,captureMethod:t?.captureMethod,cardFieldsTimeoutMs:t?.cardFieldsTimeoutMs,telemetry:!1})}async retrieveSession(t,r){if(!t)throw new V("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let o=await this.retrieveUnifiedSession(t,r);if(!o.data.session)throw new V("Session not found","api_error");return o.data.session}async retrieveUnifiedSession(t,r){if(!t)throw new V("sessionId is required.","validation_error",{param:"sessionId"});let o=Se(r??this.config.billingApiUrl),a=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let i,d,s=n=>{if(i===void 0)return;let l=i,m=d;i=void 0,d=void 0,this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:n,attempt:m}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:l,durationMode:"machine",requestCategory:"session_read",statusClass:n,attempt:m})},c=de(o,{now:()=>this.telemetryReporter?.now()??z(),onFirstByte:(n,l)=>{i=n,d=l},onRetry:(n,l)=>{this.telemetryReporter?.log({name:"operation.retry",stage:n==="session_read"?"session_read":"processing",requestCategory:n,attempt:l})}});try{let n=await c.getUnifiedCheckoutSession(t);return s("2xx"),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-a,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),n}catch(n){let l=Ze(n,n instanceof V&&n.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw s(l.statusClass),this.telemetryReporter?.error({...l,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-a,durationMode:"machine",requestCategory:"session_read",statusClass:l.statusClass}),n}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.provider.destroy()}};function Pe(e,t,r){let o=$;return new o(e,t,r)}import{FloPayError as nt,resolveBillingApiUrl as re,SDK_VERSION as Te}from"@flopay/shared";import{FloPayError as Ae}from"@flopay/shared";import{loadStripe as tt}from"@stripe/stripe-js";import{toStripeAppearance as rt,toStripeAppearanceTheme as ot}from"@flopay/shared";var ke=new WeakSet;function Re(e){return e instanceof Ae&&ke.has(e)}var N=class{constructor(){this.name="stripe";this.stripe=null}async initialize(t){if(typeof window>"u")return;let r=await tt(t.publishableKey,{locale:t.locale??"auto"});if(!r){let o=new Ae("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw ke.add(o),o}this.stripe=r}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var Ee=new Map;function oe(e){return Array.isArray(e)?e.map(oe):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,oe(r)])):e}function it(e,t){return JSON.stringify([e,re(t?.billingApiUrl),t?.telemetry!==!1,t?.locale??"auto",t?.apiVersion??null,oe(t?.appearance??null)])}var K=new Map;async function st(e,t){if(!e){let s=new E({billingApiUrl:re(t?.billingApiUrl),sdkVersion:Te,enabled:t?.telemetry!==!1});throw s.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),s.flush().catch(()=>{}).finally(()=>s.destroy()),new nt("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let r=it(e,t),o=Ee.get(r);if(o)return t?.telemetry!==!1&&be(o)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),o;let a=K.get(r);if(a)return a;let i={...t,publishableKey:e},d=(async()=>{let s=new E({billingApiUrl:re(i.billingApiUrl),sdkVersion:Te,enabled:i.telemetry!==!1}),c=s.now();s.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),s.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),s.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let n=new N,l=s.now();try{await n.initialize(i)}catch(w){throw s.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:Re(w)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),s.destroy(),w}let m=s.now();s.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),s.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),s.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),s.performance({stage:"sdk_initialize",durationMs:m-c,durationMode:"machine",provider:"stripe"}),s.performance({stage:"provider_ready",durationMs:m-l,durationMode:"machine",provider:"stripe"});let h=Pe(n,i,s);return Ee.set(r,h),h})();K.set(r,d);try{return await d}finally{K.get(r)===d&&K.delete(r)}}import{FloPayError as W,THREE_DS_CHALLENGE_WINDOW_MS as xe}from"@flopay/shared";var at=4,lt=1e3,ct=1e3,dt=15e3;function ut(e){let t=!!e?.gateways?.stripe,r=!!e?.gateways?.worldpayCorporateGateway;return t===r?"unknown":t?"stripe":"worldpay"}function mt(e,t,r){try{return typeof e?.beginThreeDsChallenge!="function"?void 0:e.beginThreeDsChallenge(t,{provider:ut(r)})}catch{return}}function H(e){return new W("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Fe(){return new W("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function De(e){return e.replace(/\/+$/,"")}function pt(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}function yt(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",r=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":case"authorized":case"pending":case"timeout":return{status:t,providerIntentId:r};case"declined":return{status:"declined",providerIntentId:r,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:r,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}async function Me(e){if(typeof document>"u"||typeof window>"u")throw new W("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});let t=X(e.telemetry);t.record("handoff_planned");let r=ie(e.nextActionRedirectUrl);r==="missing"?t.record("action_missing",{reason:"missing_url"}):r==="invalid"&&t.record("action_invalid",{reason:"invalid_url"});let o=p=>{let g=se(p);if(g==="buyer_cancel"){t.record("cancel_requested",{reason:g,evidenceBasis:"signal_reason"}),t.terminal("cancel",{reason:g,evidenceBasis:"signal_reason"});return}t.record("abort_observed",{reason:g,evidenceBasis:"signal_reason"}),t.terminal("abort",{reason:g,evidenceBasis:"signal_reason"})},a=p=>{(p.status==="succeeded"||p.status==="authorized"||p.status==="declined"||p.status==="timeout")&&t.reconcile(p.status)};if(e.signal?.aborted)throw o(e.signal.reason),H();let i=`${De(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,d=async()=>{let p=new AbortController,g=()=>p.abort();e.signal?.aborted?p.abort():e.signal?.addEventListener("abort",g);let I=window.setTimeout(()=>p.abort(),dt);try{let f=await fetch(i,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json",...t.attemptId?{"x-flopay-challenge-attempt":t.attemptId}:{}},body:"{}",signal:p.signal});if(!f.ok)return{status:"unknown"};let x=await f.json().catch(()=>null),k=yt(x);return a(k),k}catch{return{status:"unknown"}}finally{window.clearTimeout(I),e.signal?.removeEventListener("abort",g)}},s,c=()=>e.pollCompletionEndpoint!==!1?d():(s??(s=d()),s),n=document.activeElement instanceof HTMLElement?document.activeElement:null,l=document.createElement("div");l.setAttribute("data-flopay-auto-3ds-overlay","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let m=document.createElement("iframe");m.setAttribute("title","Card authentication"),m.setAttribute("allow","payment"),m.tabIndex=0,m.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let h=null;try{h=new URL(e.billingApiUrl,window.location.href).origin}catch{h=null}let w=ce(e.nextActionRedirectUrl);try{let p=await new Promise((g,I)=>{let f=!1,x=0,k=0,R=0,U=!1,F=!1,S=!1,_=0,C=()=>{window.clearTimeout(x),window.clearInterval(k),window.clearTimeout(R),window.removeEventListener("message",v),window.removeEventListener("pagehide",L),document.removeEventListener("securitypolicyviolation",b),m.removeEventListener("load",T),e.signal?.removeEventListener("abort",B)},q=async()=>{if(!(f||U)){U=!0;try{let y=await c();if(f||!pt(y))return;f=!0,C(),t.terminal("status_poll",{evidenceBasis:"server_status"}),g(y)}finally{U=!1}}},L=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},b=y=>{if(S)return;let u=le(y,w);u&&(S=!0,t.record("policy_violation",{reason:u,evidenceBasis:"parent_csp_event"}))},T=()=>{F||(F=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"})),e.pollCompletionEndpoint!==!1&&(window.clearTimeout(R),R=window.setTimeout(()=>{q()},250))},B=()=>{f||(f=!0,C(),o(e.signal?.reason),I(H()))},P=y=>{f||_>=at||(_+=1,t.record("return_rejected",{reason:y,evidenceBasis:"message_origin_check"}))},v=y=>{let u=y.data,A=!!u&&typeof u=="object"&&u.source==="flopay-vault-3ds-return";if(y.source!==m.contentWindow){A&&P("untrusted_source");return}if(h&&y.origin!==h){A&&P("untrusted_origin");return}A&&(f||(f=!0,C(),t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),g(null)))};x=window.setTimeout(()=>{f||(f=!0,C(),F||t.record("load_unconfirmed",{evidenceBasis:"no_load_signal"}),t.record("timer_expired",{reason:"window_elapsed",evidenceBasis:"timer"}),t.terminal("timer",{reason:"window_elapsed",evidenceBasis:"timer"}),I(Fe()))},xe),e.pollCompletionEndpoint!==!1&&(k=window.setInterval(()=>{q()},ct)),m.addEventListener("load",T),window.addEventListener("message",v),window.addEventListener("pagehide",L),document.addEventListener("securitypolicyviolation",b),e.signal?.addEventListener("abort",B),m.src=e.nextActionRedirectUrl,t.record("render_attempted");try{l.appendChild(m),document.body.appendChild(l)}catch(y){throw f=!0,C(),t.record("render_failed"),y}t.record("container_attached"),t.record("navigation_assigned");let D=ae(l);D&&t.record("container_visibility",{reason:D,evidenceBasis:"parent_computed_style"}),m.focus(),e.signal?.aborted&&B()});return p||await c()}finally{l.parentNode?.removeChild(l),t.record("teardown"),n?.isConnected&&n.focus()}}function Ie(e,t){try{let r=t.data.session?.status;r==="complete"?e.reconcile("succeeded"):r==="authorized"&&e.reconcile("authorized")}catch{}}function ft(e){return new W("Card was declined.","api_error",{code:e.declineReason??"authorization_declined",...e.gatewayDeclineReason?{declineCode:e.gatewayDeclineReason}:{}})}async function gt(e,t){let r=`${De(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/status`,o=new AbortController,a=new AbortController,i=()=>{o.abort(e.signal?.reason),a.abort(e.signal?.reason)};e.signal?.aborted?i():e.signal?.addEventListener("abort",i,{once:!0});let d=X(e.telemetry),s=Me({billingApiUrl:e.billingApiUrl,sessionId:e.sessionId,nonce:e.nonce,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o.signal,pollCompletionEndpoint:!1,...e.telemetry?{telemetry:e.telemetry}:{}}),c=t.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:lt,nonce:e.nonce,statusUrl:r,continueAfterActionRequired:!0,timeoutMs:xe+15e3,signal:a.signal,...d.attemptId?{challengeAttemptId:d.attemptId}:{}});c.catch(()=>{}),s.catch(()=>{});try{let n=await Promise.race([s,c]);if("data"in n)return d.terminal("status_poll",{evidenceBasis:"server_status"}),Ie(d,n),n;if(n.status==="declined")throw(e.createDeclineError??ft)(n);if(n.status==="timeout")throw Fe();let l=await c;return Ie(d,l),l}catch(n){throw e.signal?.aborted||n instanceof Error&&n.name==="AbortError"?H(n):n}finally{e.signal?.removeEventListener("abort",i),o.abort(),a.abort()}}export{$ as FloPay,Be as PaymentAPI,Z as PciVaultCardCapture,Le as SESSION_CREATE_TELEMETRY,N as StripeAdapter,mt as beginSavedCardChallengeTelemetry,Q as cacheSessionDisplayData,Ue as clearSessionDisplayData,gt as completeSavedCardNextAction,Qe as createCheckoutSession,Xe as createCheckoutSessionWithRetries,H as createSavedCardActionAbortedError,Kt as dropThirdPartyOnlyError,Oe as getSessionDisplayData,st as loadFloPay,Me as runSavedCardChallenge,rt as toStripeAppearance,ot as toStripeAppearanceTheme};
@@ -1,4 +1,4 @@
1
- import type { CaptureMethod, CardCaptureAdapter, CardCaptureEventType, CardCaptureMountOptions, CardCaptureOutcomeEvent, CardCaptureProviderId, CardFieldPlaceholders, CardFieldsEvent, VaultCardFieldKey, VaultCardThemeColors } from '@flopay/shared';
1
+ import type { CaptureMethod, CardCaptureAdapter, CardCaptureEventType, CardCaptureMountOptions, CardCaptureOutcomeEvent, CardCaptureProviderId, CardFieldLabels, CardFieldPlaceholders, CardFieldsEvent, VaultCardFieldKey, VaultCardThemeColors } from '@flopay/shared';
2
2
  import { TelemetryReporter } from './telemetry-reporter.js';
3
3
  /** Browser operation hosted by the PCIVault card-capture adapter. */
4
4
  export type CardCaptureOperation = 'checkout' | 'card_setup';
@@ -98,6 +98,13 @@ export declare class PciVaultCardCapture implements CardCaptureAdapter {
98
98
  * Discover icons. Off by default; only `true` turns them on.
99
99
  */
100
100
  private cardBrandIcons;
101
+ /**
102
+ * Latest card field label settings: whether the labels show, and their text
103
+ * (only the fields that were set). Each stays `undefined` until the host sets
104
+ * it, so a host that never does posts no label message at all.
105
+ */
106
+ private showCardFieldLabels;
107
+ private cardFieldLabels;
101
108
  /**
102
109
  * Latest merchant submit wording: a label, `null` for the explicit reset to
103
110
  * the hosted session default, or `undefined` when the host has never set
@@ -189,6 +196,28 @@ export declare class PciVaultCardCapture implements CardCaptureAdapter {
189
196
  * `ready` re-pushes it; an older hosted form ignores the directive.
190
197
  */
191
198
  setCardBrandIcons(show: boolean): void;
199
+ /**
200
+ * Show or hide the visible labels above the hosted card fields (live, no
201
+ * remount). Only `true` shows them. Stored so `ready` re-pushes it; an older
202
+ * hosted form ignores the directive.
203
+ */
204
+ setShowCardFieldLabels(show: boolean): void;
205
+ /**
206
+ * Replace the text of the hosted card field labels (live, no remount). Only
207
+ * the string text of `number`, `expiry`, `cvv` and `name` is sent, verbatim:
208
+ * the hosted form shows it literally. `null` clears the text, so the hosted
209
+ * form falls back to its defaults. Stored so `ready` re-pushes it.
210
+ */
211
+ setCardFieldLabels(labels: CardFieldLabels | null): void;
212
+ /**
213
+ * postMessage the retained card field label settings to the widget's
214
+ * document: `show` once the host set it, `labels` once the host set them.
215
+ * Nothing is posted while the host has set neither. Like the submit label,
216
+ * the label text is merchant text drawn inside the card form, so it is sent
217
+ * only with the session + message-token binding the hosted form checks, and
218
+ * only to the vault block's exact origin — never to `'*'`.
219
+ */
220
+ private postCardFieldLabels;
192
221
  /**
193
222
  * Set the placeholder text of the hosted card number, expiry, CVV and name
194
223
  * fields (live, no remount). Only the fields given are sent; the hosted form
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flopay/js",
3
- "version": "1.18.0",
3
+ "version": "1.19.0",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "publishConfig": {
@@ -31,7 +31,7 @@
31
31
  "dist"
32
32
  ],
33
33
  "dependencies": {
34
- "@flopay/shared": "1.18.0",
34
+ "@flopay/shared": "1.19.0",
35
35
  "@stripe/stripe-js": "^10.3.0"
36
36
  },
37
37
  "devDependencies": {
@@ -1 +0,0 @@
1
- var nt="flopay_session_display:";var V=new Map;function B(r){return`${nt}${r}`}function J(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function Q(r,e,t){if(!r)return;let n=t?.ttlMs??36e5,s={data:e,expiresAt:Date.now()+n},i=J();if(i)try{i.setItem(B(r),JSON.stringify(s));return}catch{}V.set(r,s)}function ce(r){if(!r)return null;let e=J();if(e)try{let n=e.getItem(B(r));if(n){let s=JSON.parse(n);if(s&&typeof s.expiresAt=="number"&&s.expiresAt>Date.now())return s.data;e.removeItem(B(r))}}catch{}let t=V.get(r);if(t){if(t.expiresAt>Date.now())return t.data;V.delete(r)}return null}function de(r){if(!r)return;V.delete(r);let e=J();if(e)try{e.removeItem(B(r))}catch{}}import{ASYNC_AUTO_CHECKOUT_CAPABILITY as _t,assertCaptureMethodEligible as Ee,buildProductPayload as ie,CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as St,CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED as Rt,classifyPaymentRejection as At,classifyTelemetryFailure as x,FLO_SDK_CAPABILITIES_HEADER as Et,FLO_SDK_VERSION_HEADER as U,FloPayError as v,foldIntoProducts as Z,IDEMPOTENCY_IN_PROGRESS_CODE as kt,IDEMPOTENCY_KEY_HEADER as ke,isCardHolderNamePlaceholder as Ve,isDetachedSessionEligible as wt,isUuidV4 as we,isValidEmail as Me,markSessionResponseReceived as q,normalizeCheckoutFailureOutcome as Ie,normalizePaymentMethodLayout as Mt,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as ee,randomUuidV4 as It,readTelemetryHttpDiagnostics as Pt,resolveIdempotencyKey as Dt,resolveSessionCurrency as te,SDK_VERSION as E,STORED_PAYMENT_METHOD_UNSUPPORTED_CODE as Pe,STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE as De,telemetryStatusClass as w,withTelemetryHttpDiagnostics as Be}from"@flopay/shared";function ue(r){return typeof r=="string"&&r.trim()?r:void 0}function he(r){if(typeof r=="string")return r.trim()?r:void 0;if(Array.isArray(r))return r.filter(t=>typeof t=="string"&&t.trim().length>0).join("; ")||void 0}function P(r=12e3){let e=Number.isFinite(r)&&r>=0?r:12e3,t=new AbortController,n=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(n)}}function st(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function z(r,e){let t=150*2**r,n=Math.round(t*(.75+Math.random()*.5));return new Promise((s,i)=>{let o,a=()=>e.removeEventListener("abort",l),l=()=>{o!==void 0&&clearTimeout(o),a(),i(st())};if(e.aborted){l();return}o=setTimeout(()=>{a(),s()},n),e.addEventListener("abort",l,{once:!0})})}import{buildTelemetryErrorEvent as Te,buildTelemetryLogEvent as be,buildTelemetryPerformanceEvent as dt,buildTelemetryTerminalEvent as ut,serializeTelemetryBatch as ht,TELEMETRY_MAX_BATCH_BYTES as mt}from"@flopay/shared";import{isThreeDsChallengeAttemptId as pe}from"@flopay/shared";var it=32,me=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function ot(){let r=globalThis,e=r[me];if(e instanceof Map)return e;let t=new Map;try{Object.defineProperty(r,me,{configurable:!0,enumerable:!1,writable:!1,value:t})}catch{}return t}function at(r,e){let t=ot(),n=t.get(r);if(n)return n;for(;t.size>=it;){let i=t.keys().next();if(i.done)break;t.delete(i.value)}let s={nextSequence:0,startedAt:e,terminated:!1,reconciled:new Set,provider:"unknown"};return t.set(r,s),s}var lt=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),ct=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function ye(r,e={}){let t=pe(e.attemptId)?e.attemptId.toLowerCase():r.newAttemptId(),n=()=>{try{let a=r.now();return Number.isFinite(a)?a:0}catch{return 0}},s=at(t,n());(e.provider==="stripe"||e.provider==="worldpay")&&(s.provider=e.provider);let i=s.provider,o=(a,l)=>{if(s.terminated&&!ct.has(a))return;let c={attemptId:t,phase:a,attemptSequence:s.nextSequence,elapsedMs:Math.max(0,n()-s.startedAt),provider:i};s.nextSequence+=1,l.reason!==void 0&&(c.reason=l.reason),l.evidenceBasis!==void 0&&(c.evidenceBasis=l.evidenceBasis),l.terminalSource!==void 0&&(c.terminalSource=l.terminalSource),l.providerOutcome!==void 0&&(c.providerOutcome=l.providerOutcome);try{r.emit(c,lt.has(a))}catch{}};return{attemptId:t,record(a,l={}){a==="browser_terminal"||a==="provider_reconciled"||o(a,{reason:l.reason,evidenceBasis:l.evidenceBasis})},terminal(a,l={}){s.terminated||(o("browser_terminal",{terminalSource:a,reason:l.reason,evidenceBasis:l.evidenceBasis}),s.terminated=!0)},reconcile(a){s.reconciled.has(a)||(s.reconciled.add(a),o("provider_reconciled",{providerOutcome:a,evidenceBasis:"provider_fact"}))}}}function ge(r){let e=null;try{e=pe(r?.attemptId)?r?.attemptId??null:null}catch{e=null}return{attemptId:e,record(t,n){try{r?.record(t,n)}catch{}},terminal(t,n){try{r?.terminal(t,n)}catch{}},reconcile(t){try{r?.reconcile(t)}catch{}}}}function X(r){if(typeof r!="string"||r.trim()==="")return"missing";try{let e=new URL(r);return e.protocol==="https:"||e.protocol==="http:"?"valid":"invalid"}catch{return"invalid"}}function Fr(r){return r==="buyer_cancel"||r==="component_unmount"||r==="navigation"?r:"unspecified"}function fe(r){try{if(typeof window>"u"||typeof window.getComputedStyle!="function")return null;for(let e=r;e;e=e.parentElement){let t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||t.visibility==="collapse"||t.opacity==="0")return"hidden"}return"visible"}catch{return null}}function ve(r,e){if(!e)return null;try{let t=r,n=String(t.effectiveDirective||t.violatedDirective||"").trim().split(/\s+/)[0],s=null;return n==="frame-src"&&(s="frame_src"),n==="child-src"&&(s="child_src"),!s||typeof t.blockedURI!="string"?null:new URL(t.blockedURI).origin===e?s:null}catch{return null}}function Ce(r){try{return X(r)==="valid"?new URL(r).origin:null}catch{return null}}var pt="/v1/sdk-telemetry/events",H=16,_e=64,yt=1500,Se=1e3,gt=64,ft="00000000-0000-4000-8000-000000000000",vt={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},Ct=48;function R(){try{return globalThis.crypto.randomUUID()}catch{let r=new Uint8Array(16);try{globalThis.crypto.getRandomValues(r)}catch{for(let t=0;t<r.length;t+=1)r[t]=Math.floor(Math.random()*256)}r[6]=(r[6]??0)&15|64,r[8]=(r[8]??0)&63|128;let e=[...r].map(t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}}function Tt(r){try{return new TextEncoder().encode(r).byteLength}catch{return r.length}}function bt(r){return JSON.stringify([r.code,r.failureCategory,r.reason,r.stage,r.provider,r.attempt,r.statusClass,r.requestCategory,r.paymentMethodCategory,r.walletType,r.operationOutcome,r.checkoutMode,r.layout,r.inAppBrowser,r.appFamily,r.popupCapability,r.presentationMode,r.terminalReason])}function _(){return globalThis.performance?.now()??0}var A=class{constructor(e){this.ingestionDisabled=!1;this.queue=[];this.sequence=0;this.threeDsChallengeCount=0;this.flushTimer=null;this.flushInFlight=null;this.reportedFailures=new Map;this.checkoutContext={};this.checkoutStartedAt=null;this.destroyed=!1;this.observers=new Set;this.pageExitHandler=()=>{this.drainQueue()};this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.flush()};this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0};this.endpoint=`${e.billingApiUrl.replace(/\/+$/,"")}${pt}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=R(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??_,this.browserTransportAvailable=typeof window<"u"&&typeof document<"u",this.browserTransportAvailable&&(window.addEventListener("pagehide",this.pageExitHandler),document.addEventListener("visibilitychange",this.visibilityHandler))}log(e){this.notify({...e,class:"lifecycle"}),this.canCollect()&&this.enqueue(be({...this.checkoutContext,...e,eventId:R(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=Te({...this.checkoutContext,...e,eventId:ft,sequence:0}),n=bt(t),s=this.now();this.pruneReportedFailures(s);let i=this.reportedFailures.get(n);if(i!==void 0&&s>=i&&s-i<Se){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt,inAppBrowser:e.inAppBrowser,appFamily:e.appFamily,popupCapability:e.popupCapability,presentationMode:e.presentationMode,terminalReason:e.terminalReason});return}this.rememberReportedFailure(n,s),this.enqueue(Te({...this.checkoutContext,...e,eventId:R(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue(dt({...this.checkoutContext,...e,eventId:R(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue(ut({...this.checkoutContext,...e,eventId:R(),sequence:this.sequence++})),e.outcome!=="action_required"&&this.checkoutStartedAt!==null)){let t=this.checkoutStartedAt;this.checkoutStartedAt=null,this.performance({...e,stage:"total_journey",durationMs:Math.max(0,this.now()-t),durationMode:"total"})}}beginThreeDsChallenge(e={}){return ye({now:()=>this.now(),newAttemptId:R,emit:(t,n)=>this.recordThreeDsChallenge(t,n)},e)}recordThreeDsChallenge(e,t){if(!this.canCollect()||this.threeDsChallengeCount>=Ct)return;let n=be({...this.checkoutContext,...e,name:"three_ds.challenge",stage:"three_ds_handoff",eventId:R(),sequence:this.sequence++});if(!(this.queue.length>=_e)){if(this.threeDsChallengeCount+=1,this.queue.push(n),t){this.drainQueue();return}if(this.queue.length>=H){this.flush();return}this.scheduleFlush()}}now(){try{return this.clock()}catch{return _()}}subscribe(e){return this.destroyed?()=>{}:(this.observers.add(e),()=>this.observers.delete(e))}notify(e){if(!this.destroyed)for(let t of this.observers)try{t(e)}catch{}}pruneReportedFailures(e){for(let[t,n]of this.reportedFailures)(e<n||e-n>=Se)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=gt;){let n=this.reportedFailures.keys().next();if(n.done)break;this.reportedFailures.delete(n.value)}this.reportedFailures.set(e,t)}setCheckoutContext(e){this.checkoutContext={checkoutMode:e.checkoutMode,layout:e.layout}}beginCheckout(e={}){return this.canCollect()?(this.drainQueue(),this.setCheckoutContext(e),this.sequence=0,this.threeDsChallengeCount=0,this.reportedFailures.clear(),this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0},this.checkoutStartedAt=this.now(),this.checkoutStartedAt):0}enqueue(e){if(this.canCollect()&&!(this.queue.length>=_e||this.eventCounts[e.class]>=vt[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=H){this.flush();return}this.scheduleFlush()}}canCollect(){return this.browserTransportAvailable&&this.merchantEnabled&&!this.ingestionDisabled&&!this.destroyed}async flush(){if(this.flushInFlight!==null)return this.flushInFlight;if(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0)return;this.clearFlushTimer();let e=this.queue.splice(0,H);return this.flushInFlight=this.sendBatch(e).finally(()=>{this.flushInFlight=null,this.queue.length>0&&this.scheduleFlush()}),this.flushInFlight}destroy(){this.destroyed||(this.drainQueue(),this.destroyed=!0,this.clearFlushTimer(),this.browserTransportAvailable&&(window.removeEventListener("pagehide",this.pageExitHandler),document.removeEventListener("visibilitychange",this.visibilityHandler)),this.queue.splice(0),this.reportedFailures.clear(),this.observers.clear())}disable(){this.merchantEnabled=!1,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}drainQueue(){if(!(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0))for(this.clearFlushTimer();this.queue.length>0;){let e=this.queue.splice(0,H);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=ht(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:R()});if(Tt(t)>mt)return;let n=typeof AbortController>"u"?null:new AbortController,s=null;try{let i=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:n?.signal}).then(async l=>{if(l.status!==202)return null;let c=null;try{c=await l.json()}catch{}return c?.status==="disabled"?"disabled":null}).catch(()=>null),o=new Promise(l=>{s=setTimeout(()=>{n?.abort(),l(null)},yt)});await Promise.race([i,o])==="disabled"&&this.disableFromIngestion()}catch{}finally{s&&clearTimeout(s)}}disableFromIngestion(){this.ingestionDisabled=!0,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}scheduleFlush(){this.flushTimer||this.destroyed||this.ingestionDisabled||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush()},0))}clearFlushTimer(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}},Re=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),Ae=globalThis;Ae[Re]===void 0&&Object.defineProperty(Ae,Re,{configurable:!0,enumerable:!1,writable:!1,value:r=>new A(r)});function Ft(r){return r==="on_session"||r==="off_session"}function Ot(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function xt(r){let e=r.vaultOutcome;if(!(!e||e.code!==Rt))return typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0}var Ut="x-flopay-process-result-source",qt="status",ze=new WeakSet;function Lt(r,e){let t=new v(r,"api_error",{code:e,statusCode:500});return ze.add(t),t}function Nt(r){return typeof r=="object"&&r!==null&&ze.has(r)}function Fe(r){return r?.result==="DECLINE"||r?.result==="ERROR"}var Vt=50,M=new Map;function Bt(r,e){return M.get(r)?.has(e)===!0}function zt(r,e){let t=M.get(r)??new Set;if(t.add(e),M.delete(r),M.set(r,t),M.size>Vt){let n=M.keys().next().value;n!==void 0&&M.delete(n)}}function Ht(r){let e=r?.threeDSecureActionResultTokenId;if(typeof e=="string"&&e.length>0)return e;if(r?.gateway==="paypal"&&r.type!=="paypal_setup_token"&&typeof r.id=="string"&&r.id.length>0)return r.id}var Oe=0,xe=500,j=15e3,Ue=15e3,jt=3e3,Kt=1e4,Gt=1e4;function L(r){return typeof r=="object"&&r!==null}function k(r,e){return ue(r?.[e])}function qe(r,e){return he(r?.[e])}function $t(r,e){let t=r?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function ne(r,e){return e?new Promise((t,n)=>{let s=()=>{clearTimeout(i),n(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},i=setTimeout(()=>{e.removeEventListener("abort",s),t()},r);e.aborted?s():e.addEventListener("abort",s,{once:!0})}):new Promise(t=>setTimeout(t,r))}function re(r){return r instanceof Error&&r.name==="AbortError"}function b(){return new v(St,"api_error",{code:"checkout_processing_timeout"})}async function S(r,e){let t=await r.json().catch(()=>null),n=L(t?.error)?t.error:null,s=qe(t,"message")??qe(n,"message")??e,i=k(t,"code")??k(t,"gatewayErrorCode")??k(n,"code")??`http_${r.status}`;return Be(new v(s,"api_error",{code:i,statusCode:r.status}),r)}async function Yt(r){if(r.status!==403)return!1;let e=await r.clone().json().catch(()=>null),t=L(e?.error)?e.error:null;return(k(e,"code")??k(t,"code"))==="verification_required"}function Wt(r){if(!(!L(r)||typeof r.required!="boolean"))return{required:r.required,provider:"turnstile"}}async function Jt(r){let e=r.status===400?await r.clone().json().catch(()=>null):null;return At(r.status,e)}function Le(r){return r===400||r===422}var G=2;async function K(r,e,t=G,n,s){let i;for(let o=0;;o++)try{return s?.(o),await fetch(r,e)}catch(a){if(e?.signal?.aborted||a instanceof Error&&a.name==="AbortError")throw a;if(i=a,o>=t)throw i;try{n?.(o+1)}catch{}await ne(150*2**o,e?.signal??void 0)}}var Qt=Symbol.for("@flopay/js.session-create.telemetry.v1");function Xt(r){return r[Qt]}function Zt(r){return"now"in r||"onFirstByte"in r||"onSessionCreateFailure"in r||"onRetry"in r}function He(r){let e=Ve(r.firstName,r.lastName);return{userId:r.userId,firstName:e?null:r.firstName??null,lastName:e?null:r.lastName??null,email:r.email,country:r.country??null,gender:r.gender??null,city:r.city??null,state:r.state??null,zip:r.zip??null,addressLine1:r.addressLine1??null,addressLine2:r.addressLine2??null}}function je(r,e){e.checkoutMetadata!==void 0&&(r.checkoutMetadata=e.checkoutMetadata),e.tagsData&&(r.tagsData=e.tagsData),e.utmMetadata&&e.utmMetadata.length>0&&(r.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(r.avsCheck=e.avsCheck),e.checkoutType&&(r.checkoutType=e.checkoutType),e.checkoutLayout&&(r.checkoutLayout=e.checkoutLayout),e.avsConfig&&(r.avsConfig=e.avsConfig)}function er(r,e){let t={clientId:r.clientId,checkoutVersion:E,successUrl:r.successUrl,cancelUrl:r.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};return r.captureMethod==="manual"&&(t.captureMethod=r.captureMethod),r.account.country&&(t.accountData={country:r.account.country}),je(t,r),t}function Ne(r,e,t){return{currency:e,products:t.map(n=>ie(n,e)),couponCodes:r.couponCodes??[],accountData:He(r.account)}}function tr(r,e,t){return{currency:e,products:t.map(n=>ie(n,e)),couponCodes:r.couponCodes??[]}}function rr(r){let e={},t=Ve(r.firstName,r.lastName);for(let[n,s]of Object.entries(r)){if(t&&n.endsWith("Name")||typeof s!="string")continue;let i=s.trim();i&&(e[n]=i)}return{accountData:e}}var I=class I{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let n=Zt(t);this.telemetryHooks=n?t:void 0,this.directTelemetry=n||t.telemetry===!1?void 0:new A({billingApiUrl:this.baseUrl,sdkVersion:E})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,n,s,i="unknown"){let o=x(e,t);this.directTelemetry?.error({...o,...Nt(e)?{reason:"capture_failed"}:{},stage:n,requestCategory:s,paymentMethodCategory:i})}reportAccountSnapshotFailure(e,t){let n=x(e,"NETWORK_REQUEST_FAILED");if(t==="best_effort"&&n.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...n,stage:"processing",requestCategory:"account_snapshot",paymentMethodCategory:"unknown"})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??_()}catch{return _()}}beginDirectTelemetryCheckout(e){!this.directTelemetry||this.directTelemetryCheckoutId===e||(this.directTelemetryCheckoutId=e,this.directTelemetry.beginCheckout())}beginDirectTelemetryOperation(){this.directTelemetry&&(this.directTelemetryCheckoutId=void 0,this.directTelemetry.beginCheckout())}adoptDirectTelemetryCheckout(e){e&&(this.directTelemetryCheckoutId=e)}async getCheckoutSession(e,t){return this.fetchCheckoutSession(e,t)}async fetchCheckoutSession(e,t,n=!0,s){this.beginDirectTelemetryCheckout(e);let i=this.telemetryTimestamp(),o=i,a=0;this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let l={[U]:E};t&&(l["x-checkout-session-token"]=t);let c=!1;try{let d=await K(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:l,signal:s},G,h=>{this.telemetryHooks?.onRetry?.("session_read",h),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:h})},h=>{a=h,o=this.telemetryTimestamp()});c=!0;let m=Math.max(0,this.telemetryTimestamp()-o);try{this.telemetryHooks?.onFirstByte?.(m,a)}catch{}let u=`${Math.floor(d.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:u,attempt:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:m,durationMode:"machine",requestCategory:"session_read",statusClass:u,attempt:a}),!d.ok)throw await S(d,"Failed to get checkout session");let g=await d.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:u}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"session_read",statusClass:u}),{...g,data:this.mergeCachedDisplayData(g.data)}}catch(d){throw c&&q(d),n&&this.directTelemetry?.error({...x(d,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),d}}cacheSessionDisplayData(e,t,n){Q(e,t,n)}clearSessionDisplayData(e){de(e)}async getVaultCapture(e,t){let n=`${this.baseUrl}\0${e}\0${t??""}`,s=I.activeVaultCaptureRequests.get(n);if(s!==void 0)return s;let i=this.requestVaultCapture(e,t);I.activeVaultCaptureRequests.set(n,i);try{return await i}finally{I.activeVaultCaptureRequests.get(n)===i&&I.activeVaultCaptureRequests.delete(n)}}async requestVaultCapture(e,t){let n=new AbortController,s=setTimeout(()=>n.abort(),Gt);this.beginDirectTelemetryCheckout(e);let i=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let o={"Content-Type":"application/json"};t&&(o["x-checkout-session-token"]=t);try{let a=await K(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:o,signal:n.signal},G,c=>{this.telemetryHooks?.onRetry?.("vault_capture",c),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:c})});if(await Yt(a))return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"4xx"}),{verification:{required:!0,provider:"turnstile"}};if(!a.ok)throw await S(a,"Failed to load the secure card form");let l=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(l)}catch(a){let l=n.signal.aborted?new v("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(l,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),l}finally{clearTimeout(s)}}async getUnifiedCheckoutSession(e,t){let n=await this.getCheckoutSession(e,t);return this.normalizeCheckoutSessionResponse(n)}async getUnifiedCheckoutSessionForRecovery(e,t,n){let s=await this.fetchCheckoutSession(e,t,!1,n);return this.normalizeCheckoutSessionResponse(s)}normalizeCheckoutSessionResponse(e){try{let t=this.normalizeRawSession(e.data),n=e.vault;return n&&t.data.session&&(t.data.session.vault=this.toVaultBlock(n)),t}catch(t){throw q(t)}}async processPayment(e,t,n){this.beginDirectTelemetryCheckout(t.sessionId);let s=t.paymentMethodCategory??"unknown";if(!t.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:s}),new v("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let i=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:s});let{nonce:o,paymentMethodCategory:a,...l}=t,c=Ht(t.tokenizedData),d,m;try{d=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":o},body:JSON.stringify(l)}),m=d}catch(u){if(re(u))throw this.reportDirectFailure(u,"PAYMENT_PROCESSING_FAILED","processing","process_payment",s),u;d=await this.reconcileProcessPayment(t.sessionId,{...n,nonce:o,paymentMethodCategory:s,submittedIntentId:c})}if(!d.ok&&d.status!==202){let u=await Jt(d);return u?this.directTelemetry?.terminal({outcome:u,stage:"processing",requestCategory:"process_payment",statusClass:"4xx",paymentMethodCategory:s}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:w(d.status),failureCategory:d.status>=500?"server_error":void 0,paymentMethodCategory:s,...Pt(m)}),d}try{let u=await this.resolveProcessResponse(d,t.sessionId,{...n,nonce:o,paymentMethodCategory:s,submittedIntentId:c});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:w(u.status),paymentMethodCategory:s}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"process_payment",statusClass:w(u.status),paymentMethodCategory:s}),u}catch(u){throw u instanceof v&&u.code==="checkout_processing_timeout"||this.reportDirectFailure(u,"PAYMENT_PROCESSING_FAILED","processing","process_payment",s),u}}async patchAccountSnapshot(e,t,n,s){this.beginDirectTelemetryCheckout(e);let i=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let o=s?.timeoutMs??Kt,a=new AbortController,l=()=>a.abort();s?.signal&&(s.signal.aborted?a.abort():s.signal.addEventListener("abort",l,{once:!0}));let c=setTimeout(()=>a.abort(),o);try{let d;try{d=await K(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(n),signal:a.signal},G,m=>{this.telemetryHooks?.onRetry?.("account_snapshot",m),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:m})})}finally{clearTimeout(c),s?.signal?.removeEventListener("abort",l)}if(!d.ok)throw await S(d,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(d){throw this.reportAccountSnapshotFailure(d,s?.telemetryMode??"blocking"),d}}async createSessionIntent(e,t,n,s){if(!t)throw new v("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let i=n,o=i.paymentMethodType,a=typeof o=="string"&&o.trim().toLowerCase()==="card",l=typeof o=="string"&&o.length>0&&!a&&(typeof i.paymentMethodId=="string"||i.paymentMethodId===null),c=i.provider==="stripe"&&(i.paymentMethodCategory==="wallet"||i.paymentMethodCategory==="apm")&&(i.intentKind==="payment"||i.intentKind==="setup"),d=i.provider==="paypal"&&i.paymentMethodCategory==="wallet"&&i.paymentMethodId===null&&(i.paymentMethodType==="paypal"&&i.intentKind==="payment"||i.paymentMethodType===ee&&(i.intentKind==="payment"||i.intentKind==="setup"));if(!l||!c&&!d)throw new v("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let m=i.authorizationAttemptId;if(m!==void 0&&!we(m))throw new v("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let u=we(m)?m:It();this.beginDirectTelemetryCheckout(e);let g=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let h={"Content-Type":"application/json","x-checkout-session-token":t,[ke]:s?.idempotencyKey||u},y=!1;try{let f=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:h,body:JSON.stringify({...n,authorizationAttemptId:u}),signal:s?.signal});if(!f.ok){y=!0;let W=await S(f,"Failed to create checkout intent"),rt=x(W,"PAYMENT_PROCESSING_FAILED");throw Le(W.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...rt,stage:"processing",requestCategory:"intent_create"}),W}let C=await f.json();if(f.status===202&&L(C)&&C.type==="checkout_processing")return y=!0,await this.settleProcessingSessionIntent(C,f,e,t,n);let T=C.data;if(!T||typeof T!="object")throw new v("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let p=T,le=p.paymentMethodType,Xe=(p.paymentMethodCategory==="wallet"||p.paymentMethodCategory==="apm")&&typeof le=="string"&&le.trim().toLowerCase()!=="card"&&(typeof p.paymentMethodId=="string"||p.paymentMethodId===null)&&typeof p.providerObjectId=="string",Ze=p.provider==="stripe"&&(p.intentKind==="payment"||p.intentKind==="setup")&&typeof p.clientSecret=="string",et=p.provider==="paypal"&&p.paymentMethodCategory==="wallet"&&p.paymentMethodId===null&&(p.paymentMethodType==="paypal"&&p.intentKind==="payment"&&(p.providerObjectType==="order"||p.providerObjectType==="subscription")||p.paymentMethodType===ee&&p.intentKind==="payment"&&p.providerObjectType==="order"||p.paymentMethodType===ee&&p.intentKind==="setup"&&p.providerObjectType==="setup_token")&&p.clientSecret===null,tt=p.provider===n.provider&&p.paymentMethodCategory===n.paymentMethodCategory&&p.paymentMethodType===n.paymentMethodType&&p.paymentMethodId===n.paymentMethodId&&p.intentKind===n.intentKind;if(!Xe||!Ze&&!et||!tt)throw new v("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:w(f.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-g),durationMode:"machine",requestCategory:"intent_create",statusClass:w(f.status)}),p}catch(f){throw y||this.reportDirectFailure(f,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),f}}async settleProcessingSessionIntent(e,t,n,s,i){let o=this.toCheckoutProcessingPending(e,t,n);try{return{settled:!0,response:await this.resolveCheckoutProcessing(o,n,{nonce:s,paymentMethodCategory:i.provider==="paypal"?"paypal":i.paymentMethodCategory})}}catch(a){throw a instanceof v&&a.code==="checkout_processing_timeout"?new v(a.message,a.type,{code:a.code,statusCode:202,sessionId:o.sessionId,cause:a}):a}}async reportSessionIntentDecline(e,t,n,s){if(!t)throw new v("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let i=n,o=i.providerDeclineReason,a=i.paymentMethodType,l=i.providerIntentId,c=typeof o=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(o)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(o),d=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&c,m=i.provider==="stripe"&&(i.paymentMethodCategory==="wallet"||i.paymentMethodCategory==="apm")&&(l===void 0||typeof l=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(l)),u=i.provider==="paypal"&&i.paymentMethodCategory==="wallet"&&i.paymentMethodType==="paypal"&&l===void 0;if(!d||!m&&!u)throw new v("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let g=u?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:o}:{provider:"stripe",paymentMethodCategory:i.paymentMethodCategory,paymentMethodType:i.paymentMethodType,providerDeclineReason:o,...typeof l=="string"?{providerIntentId:l}:{}},h=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents/decline`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(g),signal:s?.signal});if(!h.ok)throw await S(h,"Failed to report checkout decline")}async resolvePaymentMethodLayout(e,t,n,s){if(!t)throw new v("resolvePaymentMethodLayout requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let i=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/payment-method-layout`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[U]:E},body:JSON.stringify(n),signal:s?.signal});if(i.status===404||i.status===405)return null;if(!i.ok)throw await S(i,"Failed to resolve the payment method layout");let o=await i.json();return Mt(o?.data)}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let n=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let s=t?.page??1,i=t?.limit??1,o=new URLSearchParams({email:e,page:String(s),limit:String(i),sortField:"createdAt",sortDirection:"DESC"});try{let a=await fetch(`${this.baseUrl}/v1/payments?${o.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!a.ok)throw Be(new v("Failed to fetch payments","api_error",{statusCode:a.status}),a);let l=await a.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-n),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),l}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if(wt(e)){let i=e.account.email?.trim();if(i&&!Me(i))throw new v("Buyer email must be valid when supplied.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"});return(await this.createDetachedSession(e)).claimed}this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),n=P(e.timeoutMs??12e3),s={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let i=await this.createAndFetchSessionRequest(e,n.signal,s);return this.adoptDirectTelemetryCheckout(i.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:s.statusClass}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:s.statusClass,attempt:s.attempt}),i}catch(i){throw this.reportSessionCreateFailure(i,t,s),i}finally{n.clear()}}async createAndFetchSessionRequest(e,t,n){let s=e.products??Z(e.items,e.subscriptions);Ee({captureMethod:e.captureMethod,products:s});let i=te(e.currency,e.items,e.subscriptions,s);if(!i)throw new v("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let o={clientId:e.clientId,checkoutVersion:E,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:i,checkoutMode:e.checkoutMode??"full",products:s.map(c=>ie(c,i)),accountData:He(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(o.captureMethod=e.captureMethod),e.tokenizedData&&(o.tokenizedData=e.tokenizedData),je(o,e);let a=await this.postCheckoutSessionCreate(o,e,t,n),l=!1;try{let c=await a.json();if(c.data&&"gateways"in c.data){this.autoCacheDisplayData(c.data.uuid,e);let u=this.mergeCachedDisplayData(c.data),g=this.normalizeRawSession(u);return c.vault&&g.data.session&&(g.data.session.vault=this.toVaultBlock(c.vault)),{...g,autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}let d=c.data?.uuid;if(!d)throw new v("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(d,e),this.adoptDirectTelemetryCheckout(d),l=!0,{...await this.getUnifiedCheckoutSession(d),autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}catch(c){throw l?c:q(c)}}async postCheckoutSessionCreate(e,t,n,s){let i={"Content-Type":"application/json",[U]:E},o=Dt(t.idempotencyKey);o&&(i[ke]=o),t.checkoutMode==="auto"&&(i[Et]=_t);let a,l=!1,c=Xt(t),d=(u,g,h)=>{l||(l=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:h,attempt:u}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-g),durationMode:"machine",requestCategory:"session_create",statusClass:h,attempt:u}))},m=u=>{try{this.telemetryHooks?.onRetry?.("session_create",u),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:u})}catch{}};for(let u=0;u<3;u++){s.attempt=u;let g=this.telemetryTimestamp();try{c?.onAttempt?.(u)}catch{}try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:i,body:JSON.stringify(e),signal:n})}catch(f){if(s.statusClass=n.aborted||f instanceof Error&&f.name==="AbortError"?"timeout":"network_error",n.aborted||f instanceof Error&&f.name==="AbortError"||u>=2)throw f;let C=u+1;m(C),await z(u,n);continue}let h=w(a.status);if(s.statusClass=h,a.status===204)throw d(u,g,h),new v("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(a.ok){d(u,g,h);break}let y=await S(a,"Failed to create checkout session");if(y.code===kt&&u<2){m(u+1),await z(u,n);continue}throw d(u,g,h),y}if(!a)throw new TypeError("Checkout-session creation exhausted its retry budget.");return a}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),n=P(e.timeoutMs??12e3),s={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let i=e.products??Z(e.items,e.subscriptions);try{Ee({captureMethod:e.captureMethod,products:i})}catch(C){throw n.clear(),this.reportSessionCreateFailure(C,t,s),C}let o=te(e.currency,e.items,e.subscriptions,i);if(!o)throw n.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new v("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});try{Ne(e,o,i)}catch(C){throw n.clear(),this.reportSessionCreateFailure(C,t,s),C}let a,l,c=!1;try{let C=await this.postCheckoutSessionCreate(er(e,o),e,n.signal,s);if(c=!0,l=await C.json(),!l.data||!("gateways"in l.data))throw new v("The billing API returned no session shell for a detached create. It must support `deferDataAttachment` (TeamFloPay/backend#1099).","api_error",{code:"InvalidCheckoutSessionResponse"});a=this.normalizeRawSession(this.mergeCachedDisplayData(l.data)),l.vault&&a.data.session&&(a.data.session.vault=this.toVaultBlock(l.vault))}catch(C){throw n.clear(),c&&q(C),this.reportSessionCreateFailure(C,t,s),C}let d=a.data.session?.id??l.data.uuid??"",m=a.data.session?.clientSecret??l.data.nonce??"";if(!d||!m){n.clear();let C=new v("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(C,t,s),C}n.clear(),this.adoptDirectTelemetryCheckout(d),this.directTelemetry?.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",statusClass:s.statusClass,paymentMethodCategory:"card"}),this.directTelemetry?.performance({stage:"session_shell",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:s.statusClass,attempt:s.attempt,paymentMethodCategory:"card"});let u=!e.account.email?.trim(),g=P(e.timeoutMs??12e3),h=this.claimCheckoutSession(d,m,u?tr(e,o,i):Ne(e,o,i),{params:e,startedAt:t,deadline:g,createAttempt:s.attempt}),y=u?void 0:h,f=(C={})=>{if(y!==void 0)return y;let T={...e,account:{...e.account,...C,email:C.email?.trim()||e.account.email?.trim()}};return Me(T.account.email)?(y=h.then(()=>{let p=this.telemetryTimestamp();return this.claimCheckoutSession(d,m,rr(T.account),{params:T,startedAt:p,deadline:P(e.timeoutMs??12e3),createAttempt:0})}),y.catch(()=>{}),y):Promise.reject(new v("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return h.catch(()=>{}),{shell:a,sessionId:d,nonce:m,claimed:h,claim:f}}async claimCheckoutSession(e,t,n,s){let i=s?.startedAt??this.telemetryTimestamp(),o=this.telemetryTimestamp(),a=s?.deadline??P(12e3),l=JSON.stringify(n),c="unknown",d=0,m=!1;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let u;for(d=0;d<3;d++){try{u=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[U]:E},body:l,signal:a.signal})}catch(y){let f=a.signal.aborted||y instanceof Error&&y.name==="AbortError";if(c=f?"timeout":"network_error",f||d>=2)throw y;try{this.telemetryHooks?.onRetry?.("session_claim",d+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:d+1})}catch{}await z(d,a.signal);continue}if(c=w(u.status),u.ok)break;throw await S(u,"Failed to attach checkout session data")}if(!u)throw new TypeError("Checkout-session claim exhausted its retry budget.");m=!0;let g=await u.json();if(!g.data?.gateways)throw new v("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});s?.params&&this.autoCacheDisplayData(g.data.uuid??e,s.params);let h=this.normalizeRawSession(this.mergeCachedDisplayData(g.data));return g.vault&&h.data.session&&(h.data.session.vault=this.toVaultBlock(g.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:c}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_claim",statusClass:c,attempt:d}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:c}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"session_create",statusClass:c,attempt:s?.createAttempt??d}),h}catch(u){throw m&&q(u),this.reportSessionCreateFailure(u,o,{attempt:d,statusClass:c},"session_claim"),u}finally{a.clear()}}reportSessionCreateFailure(e,t,n,s="session_create"){if(!(e instanceof v&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let i=x(e,"CHECKOUT_SESSION_CREATE_FAILED");if(this.directTelemetry?.performance({stage:s,durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:s==="session_claim"?"session_claim":"session_create",statusClass:i.statusClass,attempt:n.attempt}),e instanceof v&&e.type==="validation_error"||e instanceof v&&Le(e.statusCode)){this.directTelemetry?.terminal({outcome:"validation_rejected",stage:s,requestCategory:s==="session_claim"?"session_claim":"session_create",...e.type==="validation_error"?{}:{statusClass:"4xx"}});return}e instanceof v&&e.code==="session_auto_completed"||this.directTelemetry?.error({...i,stage:s,requestCategory:s==="session_claim"?"session_claim":"session_create"})}reportThreeDsAbandoned(e){this.beginDirectTelemetryCheckout(e),this.directTelemetry?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",paymentMethodCategory:"saved"})}beginThreeDsChallenge(e,t={}){try{return this.directTelemetry?(this.beginDirectTelemetryCheckout(e),this.directTelemetry.beginThreeDsChallenge(t)):void 0}catch{return}}async waitForCheckoutSessionCompletion(e,t){this.beginDirectTelemetryCheckout(e);let n=this.telemetryTimestamp(),s=t?.paymentMethodCategory??"saved";this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:s});let i=t?.timeoutMs??j,o=Date.now()+i,a=new AbortController,l=!1,c,d=setTimeout(()=>{c=setTimeout(()=>{l=!0,a.abort()},Ue)},i),m=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?m():t?.signal?.addEventListener("abort",m,{once:!0});let u=this.clampRetryAfterMs(t?.initialDelayMs??Oe),g=0;try{if(t?.statusUrl){let h=await this.waitForCheckoutStatus(e,{initialDelayMs:u,timeoutMs:i,nonce:t.nonce,statusUrl:t.statusUrl,pollAfterAction:t.continueAfterActionRequired,signal:a.signal});if(h){let y=await this.resolveCheckoutSessionStatus(e,h,t.nonce,a.signal,()=>l);return this.reportRecoveryCompleted(n,s,t.challengeAttemptId),y}}for(;;){let h=o-Date.now();if(h<=0)throw b();if(u>0){try{g+=1,this.telemetryHooks?.onRetry?.("session_read",g),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:s,attempt:g})}catch{}if(await ne(Math.min(u,h),a.signal),Date.now()>=o)throw b()}let y=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,a.signal),f=y.data.session?.status;if(f==="authorized"||f==="complete"||f==="expired")return this.reportRecoveryCompleted(n,s,t?.challengeAttemptId),y;if(Date.now()>=o)throw b();u=this.clampRetryAfterMs(Math.max(u*2,xe))}}catch(h){let y=l&&re(h)?b():h;throw this.reportDirectFailure(y,"RECOVERY_FAILED","recovery","session_read",s),y}finally{clearTimeout(d),clearTimeout(c),t?.signal?.removeEventListener("abort",m)}}reportRecoveryCompleted(e,t,n){let s={stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t};if(this.directTelemetry?.log({name:"operation.recovery.completed",...s}),n)try{this.directTelemetry?.beginThreeDsChallenge({attemptId:n}).record("recovery_read_completed",{evidenceBasis:"server_status"})}catch{}this.directTelemetry?.performance({...s,durationMs:Math.max(0,this.telemetryTimestamp()-e),durationMode:"machine"})}async resolveCheckoutSessionStatus(e,t,n,s,i){let o=t.latestTransactionAttempt;if(this.rememberReportedFailure(e,t),o?.result==="DECLINE"){let c=o.code===Pe;throw new v(c?De:"Payment was declined. Please choose another payment method.","api_error",{code:o.code??o.declineReason??"authorization_declined",statusCode:400})}if(o?.result==="ERROR"||t.status==="voided")throw Lt("Payment could not be completed. Please try again.",o?.code??"payment_processing_error");let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,n,s)}catch(c){if(!i?.()||!re(c))throw c;a={providers:[],mode:"tokenize",data:{},raw:t}}let l=a.data.session;return l&&o?.result==="SUCCESS"?{...a,data:{...a.data,session:{...l,status:"complete"}}}:l&&o?.result==="AUTHORIZED"?{...a,data:{...a.data,session:{...l,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:l&&t.status==="completed"?{...a,data:{...a.data,session:{...l,status:"complete"}}}:l&&t.status==="authorized"?{...a,data:{...a.data,session:{...l,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:l&&t.status==="expired"?{...a,data:{...a.data,session:{...l,status:"expired"}}}:o?.result!=="ACTION_REQUIRED"?a:o.gateway==="paypal"&&o.providerIntentId?{...a,autoProcessingError:{type:"paypal_direct_required",message:"PayPal authorization required",orderId:o.providerIntentId,checkoutMethod:"paypal"}}:o.nextActionRedirectUrl?{...a,autoProcessingError:{type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:o.nextActionRedirectUrl}}:a}async waitForCheckoutStatus(e,t){let n=t.timeoutMs??j,s=Date.now()+n,i=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let o=s-Date.now();if(o<=0||i>0&&(await ne(Math.min(i,o),t.signal),Date.now()>=s))throw b();let a=s-Date.now();if(a<=0)throw b();let l=new AbortController,c,d=t.signal?new Promise((T,p)=>{c=p}):null,m=()=>{l.abort(t.signal?.reason),c?.(t.signal?.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))};t.signal?.aborted?m():t.signal?.addEventListener("abort",m,{once:!0});let u,g=t.signal?null:new Promise((T,p)=>{u=setTimeout(()=>{p(b()),l.abort()},a+Ue)}),h;try{let T=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,l.signal);h=await Promise.race([T,g,d].filter(p=>p!==null))}finally{u!==void 0&&clearTimeout(u),t.signal?.removeEventListener("abort",m)}if(!h)return null;let y=Fe(h.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,h,t.submittedIntentId);if(h.status==="completed"||h.status==="authorized"||h.status==="expired"||h.status==="voided")return y?{...h,latestTransactionAttempt:null}:h;let f=h.latestTransactionAttempt?.result,C=t.pollAfterAction===!0&&f==="ACTION_REQUIRED";if(!y&&f!==void 0&&f!=="PENDING"&&!C)return h;i=this.clampRetryAfterMs(Math.max(i*2,xe))}}isOwnFailedAttempt(e,t,n){let s=t.latestTransactionAttempt?.providerIntentId??null;return n!==void 0?s===n:s===null?!0:!Bt(t.uuid||e,s)}rememberReportedFailure(e,t){let n=t.latestTransactionAttempt;!Fe(n)||!n.providerIntentId||zt(t.uuid||e,n.providerIntentId)}async fetchCheckoutStatus(e,t,n,s){let i=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,o=i;if(n)try{let d=new URL(n,`${this.baseUrl}/`),m=new URL(i);d.origin===m.origin&&(o=d.toString())}catch{}let a={[U]:E};t&&(a["x-checkout-session-token"]=t);let l=await K(o,{headers:a,signal:s});if(l.status===404||l.status===405)return null;if(!l.ok)throw await S(l,"Failed to get checkout session status");let c=await l.json();return L(c.data)&&"latestTransactionAttempt"in c.data?c.data:null}normalizeRawSession(e){let t=e.gateways??{},n=[],s={session:this.toCheckoutSession(e)},i=t.stripe;if(i?.publishableKey){n.push("stripe");let l=[e.stripeClientSecret,i.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);s.stripe={clientSecret:l??"",publishableKey:i.publishableKey??void 0,paypalPublishableKey:i.paypalPublishableKey??void 0,environment:i.environment,enabledPaymentMethods:Array.isArray(i.enabledPaymentMethods)?i.enabledPaymentMethods.filter(c=>typeof c=="string"):void 0}}let o=t.paypal;return o?.publishableKey&&(n.push("paypal"),s.paypal={publishableKey:o.publishableKey,environment:o.environment,providerObjectType:o.providerObjectType,approvalPresentation:o.approvalPresentation}),{providers:n,mode:"tokenize",...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},data:s,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],n=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),s=t.reduce((c,d)=>c+(d.overrideAmount??d.totalAmount??0),0),i=n?e.totalAmount:s,o=Math.round(i*100),a=e.currency??t[0]?.currency??"USD",l="payment";return e.checkoutMode==="setup"?l="setup":t.some(c=>c.type==="subscription")&&(l="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:l,status:this.toCheckoutSessionStatus(e.status),amount:o,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:Ie(e.outcome)??Ie(e.failureReason)??(e.status==="expired"&&e.captureMethod==="manual"?"authorization_expired":void 0),customer:{id:e.accountData.userId??void 0,email:e.accountData.email??void 0,firstName:e.accountData.firstName??void 0,lastName:e.accountData.lastName??void 0,country:e.accountData.country??void 0,city:e.accountData.city??void 0,state:e.accountData.state??void 0,zip:e.accountData.zip??void 0,gender:e.accountData.gender??void 0,line1:e.accountData.addressLine1??void 0,line2:e.accountData.addressLine2??void 0},...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},metadata:{},checkoutMode:e.checkoutMode,...Array.isArray(e.advertisedPaymentMethods)?{advertisedPaymentMethods:e.advertisedPaymentMethods}:{},...Ft(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(Ot)}:{},buyerIdentified:e.buyerIdentified,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(c=>({...c,totalAmount:typeof c.totalAmount=="number"?c.totalAmount:void 0,overrideAmount:typeof c.overrideAmount=="number"?c.overrideAmount:null,currency:typeof c.currency=="string"?c.currency:void 0,metadata:c.metadata??null})),successUrl:e.successUrl,cancelUrl:e.cancelUrl,coupons:e.coupons,subtotalAmount:e.subtotalAmount,discountAmount:e.discountAmount,totalAmount:e.totalAmount,createdAt:e.createdAt,gateways:e.gateways,accountData:e.accountData,tagsData:e.tagsData}}toVaultBlock(e){let t=Wt(e.verification);return{html:typeof e.html=="string"?e.html:void 0,url:typeof e.url=="string"?e.url:void 0,messageToken:typeof e.messageToken=="string"?e.messageToken:void 0,expectedOrigin:typeof e.expectedOrigin=="string"?e.expectedOrigin:void 0,...t?{verification:t}:{}}}toCheckoutSessionStatus(e){return e==="completed"?"complete":e==="authorized"?"authorized":e==="expired"?"expired":"open"}async resolveProcessResponse(e,t,n){if(e.status!==202)return e;let s=await e.json().catch(()=>null),i=this.toCheckoutProcessingPending(s,e,t);return this.resolveCheckoutProcessing(i,t,n)}async resolveCheckoutProcessing(e,t,n){let s=n?.pollTimeoutMs??j,i=Date.now()+s;if(e.statusUrl){let a=await this.waitForCheckoutStatus(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:s,nonce:n?.nonce,statusUrl:e.statusUrl,submittedIntentId:n?.submittedIntentId});if(a)return this.toProcessResponseFromStatus(a,t,n?.nonce)}let o=await this.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:i-Date.now(),nonce:n?.nonce,paymentMethodCategory:n?.paymentMethodCategory});return this.toProcessResponseFromSession(o,t)}async toProcessResponseFromStatus(e,t,n){let s=e.latestTransactionAttempt?.result,i={[Ut]:qt},o={"Content-Type":"application/json",...i};if(e.status==="completed"||s==="SUCCESS")return new Response(null,{status:204,statusText:"No Content",headers:i});if(e.status==="authorized"||s==="AUTHORIZED")return new Response(JSON.stringify({status:"authorized",paymentId:e.paymentId??void 0,sessionId:e.uuid||t,authorizationExpiresAt:e.authorizationExpiresAt??void 0}),{status:200,headers:o});if(e.status==="expired"){let a=await this.resolveCheckoutSessionStatus(t,e,n);return this.toProcessResponseFromSession(a,t)}if(this.rememberReportedFailure(t,e),s==="DECLINE"){let a=e.latestTransactionAttempt,l=a?.code===Pe,c=a?.declineReason??void 0;return new Response(JSON.stringify({type:c??"authorization_declined",message:l?De:"Payment was declined. Please choose another payment method.",code:a?.code??c??"authorization_declined",...c?{declineCode:c}:{}}),{status:400,headers:o})}if(s==="ACTION_REQUIRED"&&e.latestTransactionAttempt?.gateway==="paypal"&&e.latestTransactionAttempt.providerIntentId)return new Response(JSON.stringify({type:"paypal_direct_required",message:"PayPal authorization required",orderId:e.latestTransactionAttempt.providerIntentId}),{status:400,headers:o});if(s==="ACTION_REQUIRED"&&e.latestTransactionAttempt?.nextActionRedirectUrl)return new Response(JSON.stringify({type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:e.latestTransactionAttempt.nextActionRedirectUrl}),{status:400,headers:o});if(s==="ERROR"||e.status==="voided")return new Response(JSON.stringify({type:"unknown",code:e.latestTransactionAttempt?.code??"payment_processing_error",message:xt(e)??"Payment could not be completed. Please try again."}),{status:500,headers:o});throw b()}async reconcileProcessPayment(e,t){let n=t?.pollTimeoutMs??j,s=Date.now()+n,i=null;try{i=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:n,nonce:t?.nonce,submittedIntentId:t?.submittedIntentId})}catch(l){if(this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),l instanceof v&&l.code==="checkout_processing_timeout")throw l}if(i)return this.toProcessResponseFromStatus(i,e,t?.nonce);let o=s-Date.now();if(o<=0)throw b();let a=await this.waitForCheckoutSessionCompletion(e,{initialDelayMs:0,timeoutMs:o,nonce:t?.nonce,paymentMethodCategory:t?.paymentMethodCategory});return this.toProcessResponseFromSession(a,e)}toProcessResponseFromSession(e,t){if(e.data.session?.status==="complete")return new Response(null,{status:204,statusText:"No Content"});if(e.data.session?.status==="authorized"){let n=e.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:n.paymentId,sessionId:n.id||t,authorizationExpiresAt:n.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(e.data.session?.status==="expired"){let n=e.data.session.failureOutcome==="authorization_expired"||e.data.session.captureMethod==="manual";throw new v(n?"Authorization has expired.":"Checkout session has expired.","api_error",{code:n?"authorization_expired":"checkout_session_expired"})}throw b()}toCheckoutProcessingPending(e,t,n){let s=t.headers.get("Retry-After"),i=s===null||s.trim()===""?void 0:Number(s),o=i!==void 0&&Number.isFinite(i)?i*1e3:void 0;return{type:"checkout_processing",sessionId:k(e,"sessionId")??n,retryAfterMs:this.clampRetryAfterMs($t(e,"retryAfterMs")??o??Oe),statusUrl:k(e,"statusUrl"),sessionUrl:k(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,jt))}autoCacheDisplayData(e,t){if(!e)return;let n=t.products??Z(t.items,t.subscriptions);if(n.length===0&&!t.currency)return;let s=t.products!==void 0,i=te(t.currency,s?void 0:t.items,s?void 0:t.subscriptions,n);Q(e,{currency:i??void 0,products:n.map(o=>({code:o.code??o.providerItemId??o.providerPlanId,type:o.type,name:o.name??o.itemName??o.providerItemName??o.subscriptionName??o.providerPlanName??null,totalAmount:o.totalAmount,overrideAmount:o.overrideAmount,currency:o.currency??i??void 0}))})}mergeCachedDisplayData(e){let t=ce(e.uuid),n=new Map,s=o=>o?`code:${o}`:void 0;for(let o of t?.products??[]){let a=s(o.code);a&&n.set(a,o)}let i=(e.products??[]).map(o=>{let a=s(o.code),l=a?n.get(a):void 0;return{...o,name:o.name??l?.name??null,totalAmount:o.totalAmount??l?.totalAmount,overrideAmount:o.overrideAmount??l?.overrideAmount,currency:o.currency??l?.currency}});return{...e,currency:e.currency??t?.currency,products:i}}};I.activeVaultCaptureRequests=new Map;var se=I;function Hr(r,e){let t=se;return new t(r,e)}import{buildTelemetryErrorEvent as ir,buildTelemetryLogEvent as or,buildTelemetryTerminalEvent as We,FloPayError as Ge,resolveBillingApiUrl as $e,SDK_VERSION as Ye,THREE_DS_CHALLENGE_WINDOW_MS as ar}from"@flopay/shared";import{invokeMerchantCallback as nr,resolveCardFieldsTimeoutMs as sr}from"@flopay/shared";function Ke(r){if(!r)return null;try{let e=new URL(r,window.location.href);return e.origin==="null"?null:e.origin}catch{return null}}var $=class{constructor(e){this.options=e;this.handlers=new Set;this.active=!1;this.readyReported=!1;this.failureReported=!1;this.startedAt=0;this.timer=null;this.detach=null}subscribe(e){return this.handlers.add(e),()=>{this.handlers.delete(e)}}begin(){this.end(),this.active=!0,this.readyReported=!1,this.failureReported=!1,this.startedAt=this.options.now();let e=sr(this.options.timeoutMs);this.timer=setTimeout(()=>{this.timer=null,this.reportFailure("timeout",e)},e)}watch(e){if(!this.active)return;this.detachWatchers();let t=new Set,n=[];for(let i of Array.from(e.querySelectorAll("script[src], iframe[src]"))){let o=Ke(i.getAttribute("src"));if(o&&t.add(o),i.tagName==="SCRIPT"){let a=()=>this.fail("load_error");i.addEventListener("error",a),n.push(()=>i.removeEventListener("error",a))}}let s=i=>{let o=Ke(i.blockedURI);o&&t.has(o)&&this.fail("blocked")};document.addEventListener("securitypolicyviolation",s),n.push(()=>document.removeEventListener("securitypolicyviolation",s)),this.detach=()=>{for(let i of n)i()}}ready(){!this.active||this.readyReported||(this.readyReported=!0,this.clearTimer(),this.detachWatchers(),this.dispatch({type:"card_fields_ready",elapsedMs:this.elapsed()}))}fail(e){this.reportFailure(e,0)}reportFailure(e,t){!this.active||this.readyReported||this.failureReported||(this.failureReported=!0,this.clearTimer(),this.dispatch({type:"card_fields_failed",reason:e,elapsedMs:Math.max(t,this.elapsed())}))}end(){this.active=!1,this.clearTimer(),this.detachWatchers()}elapsed(){return Math.max(0,Math.round(this.options.now()-this.startedAt))}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}detachWatchers(){this.detach?.(),this.detach=null}dispatch(e){try{this.options.report?.(e)}catch{}for(let t of Array.from(this.handlers))nr(()=>t(e))}};var lr=4,Y="flopay-vault",cr=3e4,dr=ar+cr,ur="Card authentication timed out.",Je={ready:["vault.widget.ready","vault_ready"],submitting:["vault.submission.started","vault_submit"],blocked:["operation.state_transition","vault_submit"],action_required:["vault.action.required","three_ds_handoff"]};function hr(r){return r.class==="lifecycle"?r.name:r.class==="technical_error"?r.code:r.class==="expected_outcome"?r.outcome:"sdk.performance"}function D(r){let e={class:r.class,stage:r.stage};"code"in r&&(e.code=r.code),"provider"in r&&r.provider&&(e.provider=r.provider),"paymentMethodCategory"in r&&r.paymentMethodCategory&&(e.paymentMethodCategory=r.paymentMethodCategory),"outcome"in r&&(e.outcome=r.outcome),"durationMs"in r&&r.durationMs!==void 0&&(e.durationMs=r.durationMs),"durationMode"in r&&r.durationMode&&(e.durationMode=r.durationMode);try{globalThis.Sentry?.addBreadcrumb?.({category:"flopay.telemetry",level:r.class==="technical_error"?"error":"info",message:hr(r),data:e})}catch{}}function N(r,e){return or({eventId:"11111111-1111-4111-8111-111111111111",name:r,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var mr=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function pr(r){return typeof r=="string"&&mr.has(r)?r:"unknown"}var yr=new Set(["verification_failed","verification_expired"]);function gr(r){return r==null?!0:typeof r=="string"&&yr.has(r)}var fr="vault_mount";function vr(r){return r.failureStage===fr}function oe(r,e){return r&&!vr(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:pr(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function Qe(r,e,t="checkout"){return t==="card_setup"?r.type==="decline"?"card_setup_declined":"card_setup_succeeded":r.type==="decline"?"payment_declined":r.outcome==="authorized"||e==="manual"?"payment_authorized":"payment_succeeded"}function Cr(r,e,t,n="checkout"){let{type:s}=r;if(s==="complete"||s==="decline")return We({eventId:"22222222-2222-4222-8222-222222222222",outcome:Qe(r,t,n),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(s==="error"){let a=oe(e,r);return ir({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[i,o]=Je[s];return N(i,o)}function Tr(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Y&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function br(r){if(typeof r!="object"||r===null)return;let e=r;if(typeof e.code!="string"||e.code.trim()==="")return;let t=typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0;return t?{code:e.code,message:t}:{code:e.code}}function _r(r){if(typeof r!="object"||r===null)return;let e=r,t=e.status;if(!(typeof e.id!="string"||e.id.trim()===""||typeof e.brand!="string"||e.brand.trim()===""||typeof e.lastFour!="string"||!/^\d{4}$/.test(e.lastFour)||typeof e.expiryMonth!="number"||!Number.isInteger(e.expiryMonth)||e.expiryMonth<1||e.expiryMonth>12||typeof e.expiryYear!="number"||!Number.isInteger(e.expiryYear)||e.expiryYear<1970||e.expiryYear>9999||t!=="pending"&&t!=="active"&&t!=="deleted"))return{id:e.id,brand:e.brand,lastFour:e.lastFour,expiryMonth:e.expiryMonth,expiryYear:e.expiryYear,status:t}}function Sr(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Y&&e.type==="validation"&&Array.isArray(e.messages)}function Rr(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Y&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}function Ar(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Y&&e.type==="fields_interactive"}function Er(r){let e=r.capabilities;return Array.isArray(e)&&e.includes("fields_interactive")}var kr=["number","expiry","cvv","name"];function wr(r){if(r===null||typeof r!="object")return;let e=r,t={};for(let n of kr){let s=e[n];typeof s=="string"&&(t[n]=s)}return t}var ae=class{constructor(e={},t){this.provider="pcivault";this.container=null;this.messageHandler=null;this.actionOverlay=null;this.threeDsReturnHandler=null;this.actionChallenge=null;this.lastChallengeTelemetry=null;this.actionOverlayPreviousFocus=null;this.actionOverlayTimer=null;this.messageToken=null;this.expectedOrigin=null;this.theme=void 0;this.submitGateBlocked=!1;this.cardFieldOrder=null;this.cardAutoFocus=!0;this.cardBrandIcons=!1;this.submitLabel=void 0;this.cardFieldPlaceholders=void 0;this.mountStartedAt=0;this.vaultReadyReported=!1;this.verificationRequired=!1;this.submissionStarted=!1;this.submissionStartedAt=null;this.listeners=new Map;this.config=e,this.cardFields=new $({timeoutMs:e.cardFieldsTimeoutMs,now:()=>this.telemetryReporter?.now?.()??_(),report:n=>this.reportCardFields(n)}),this.ownsTelemetryReporter=!t&&e.telemetry!==!1,this.telemetryReporter=t?.reporter??(this.ownsTelemetryReporter?new A({billingApiUrl:$e(e.billingApiUrl),sdkVersion:Ye}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new A({billingApiUrl:$e(this.config.billingApiUrl),sdkVersion:Ye}));let n=this.telemetryReporter;if(this.config.operation==="card_setup"&&n&&this.setupTelemetryReporter!==n){this.setupTelemetryReporter=n;try{n.beginCheckout({checkoutMode:"setup"})}catch{}}if(this.mountStartedAt=this.telemetryReporter?.now?.()??_(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,this.cardFields.begin(),typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),new Ge("The vault card form is only available in the browser.","api_error",{code:"card_capture_no_window"});if(!t?.html?.trim())throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),new Ge("No vault capture widget HTML was provided to mount the secure card form.","api_error",{code:"card_capture_no_widget_html"});this.container=e,this.verificationRequired=t.verificationRequired===!0,this.messageToken=t.messageToken??null,this.expectedOrigin=t.expectedOrigin??this.config.expectedOrigin??null,this.theme=t.theme,t.submitLabel!==void 0&&(this.submitLabel=t.submitLabel);try{this.attachMessageListener(),this.injectWidget(e,t.html),this.cardFields.watch(e)}catch(s){throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),s}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postCardBrandIcons(),this.postCardFieldPlaceholders(),this.postSubmitLabel(),D(N("vault.widget.mounted","vault_mount")),this.telemetryReporter?.log({name:"vault.widget.mounted",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?.performance?.({stage:"vault_mount",durationMs:Math.max(0,(this.telemetryReporter.now?.()??_())-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),this.emit("ready",{sessionId:this.config.sessionId})}reportVaultLoadFailure(){this.telemetryReporter?.error({errorCode:"VAULT_LOAD_FAILED",failureCategory:"provider_runtime",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})}on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>{this.listeners.get(e)?.delete(t)}}onCardFields(e){return this.cardFields.subscribe(e)}failCardFieldsMount(){this.cardFields.fail("other"),this.cardFields.end()}reportCardFields(e){let t=e.type==="card_fields_ready",n=this.config.sessionId;this.telemetryReporter?.log({name:t?"vault.fields.ready":"vault.fields.failed",stage:t?"vault_ready":"vault_mount",provider:"pcivault",paymentMethodCategory:"card",elapsedMs:e.elapsedMs,...e.type==="card_fields_failed"?{loadFailureReason:e.reason}:{},...n?{checkoutSessionId:n}:{}})}unmount(){if(this.cardFields.end(),this.actionChallenge){let{telemetry:e}=this.actionChallenge;e.record("abort_observed",{reason:"component_unmount",evidenceBasis:"signal_reason"}),e.terminal("abort",{reason:"component_unmount",evidenceBasis:"signal_reason"})}this.lastChallengeTelemetry=null,this.hideActionRequiredOverlay(),this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.container&&(this.container.replaceChildren(),this.container=null),this.messageToken=null,this.expectedOrigin=null,this.ownsTelemetryReporter&&(this.telemetryReporter?.destroy(),this.telemetryReporter=void 0)}injectWidget(e,t){e.innerHTML=t;let n=Array.from(e.querySelectorAll("script"));for(let s of n){let i=document.createElement("script");for(let o of Array.from(s.attributes))i.setAttribute(o.name,o.value);i.text=s.text,s.replaceWith(i)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let n=t.data;if(Rr(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;this.applyHeight(n.height);return}if(Sr(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let c=n.messages.filter(d=>typeof d=="string"&&d.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:c||void 0});return}if(Ar(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let c=typeof n.sessionId=="string"?n.sessionId:void 0;if(this.config.sessionId&&c&&c!==this.config.sessionId)return;this.cardFields.ready();return}if(!Tr(n)||this.messageToken&&n.messageToken!==this.messageToken)return;let s=this.config.sessionId,i=typeof n.sessionId=="string"?n.sessionId:void 0;if(s&&i&&i!==s||(n.type==="complete"||n.type==="decline")&&s&&i!==s)return;let o=_r(n.paymentMethod),a=br(n.vaultOutcome),l={...n.sessionId??this.config.sessionId?{sessionId:n.sessionId??this.config.sessionId}:{},...n.outcome?{outcome:n.outcome}:{},...n.paymentId?{paymentId:n.paymentId}:{},...n.authorizationExpiresAt?{authorizationExpiresAt:n.authorizationExpiresAt}:{},...n.failureOutcome?{failureOutcome:n.failureOutcome}:{},...n.intentId?{intentId:n.intentId}:{},...n.declineReason?{declineReason:n.declineReason}:{},...n.message?{message:n.message}:{},...a?{vaultOutcome:a}:{},...o?{paymentMethod:o}:{}};n.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??_()),this.isVerificationStateError(n)?(D(N("operation.state_transition","vault_mount")),this.telemetryReporter?.log({name:"operation.state_transition",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})):(D(Cr(n,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(n),n.type==="error"&&oe(this.submissionStarted,n).errorCode==="VAULT_LOAD_FAILED"&&this.cardFields.fail("load_error")),n.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postCardBrandIcons(),this.postCardFieldPlaceholders(),this.postSubmitLabel(),Er(n)||this.cardFields.ready()),n.type==="action_required"&&n.nextActionRedirectUrl&&this.showActionRequiredOverlay(n.nextActionRedirectUrl),(n.type==="complete"||n.type==="decline"||n.type==="error"||n.type==="submitting")&&(this.endActionChallengeFromWidget(n.type),this.hideActionRequiredOverlay()),n.type!=="action_required"&&this.emit(n.type,l)};this.messageHandler=e,window.addEventListener("message",e)}isVerificationStateError(e){return e.type==="error"&&this.verificationRequired&&!this.submissionStarted&&gr(e.failureOutcome)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;let{type:n}=e;if(n==="ready"&&!this.vaultReadyReported&&(this.vaultReadyReported=!0,t.performance({stage:"vault_ready",durationMs:Math.max(0,t.now()-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card",requestCategory:"provider_sdk"})),n==="complete"||n==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:Qe(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="error"){let o=oe(this.submissionStarted,e);t.log({name:"vault.terminal",stage:o.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...o,provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="action_required"){t.log({name:"vault.action.required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),t.log({name:"vault.three_ds.handoff",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});let o=this.submissionStartedAt;this.submissionStartedAt=null,o!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-o),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[s,i]=Je[n];t.log({name:s,stage:i,provider:"pcivault",paymentMethodCategory:"card"})}applyTheme(e){this.theme=e,this.postTheme()}postTheme(){this.theme!==void 0&&this.postToHostedWindow({source:"flopay-vault-host",type:"theme",theme:this.theme},this.directiveTargetOrigin())}setSubmitGate(e){this.submitGateBlocked=e,this.postSubmitGate()}postSubmitGate(){this.postToHostedWindow({source:"flopay-vault-host",type:"gate",blocked:this.submitGateBlocked},this.directiveTargetOrigin())}setCardFieldOrder(e,t){this.cardFieldOrder=e,this.cardAutoFocus=t,this.postCardFieldOrder()}postCardFieldOrder(){this.postToHostedWindow({source:"flopay-vault-host",type:"fieldOrder",order:this.cardFieldOrder,autoFocus:this.cardAutoFocus},this.directiveTargetOrigin())}setCardBrandIcons(e){this.cardBrandIcons=e===!0,this.postCardBrandIcons()}setCardFieldPlaceholders(e){let t=wr(e),n=t===void 0&&this.cardFieldPlaceholders!==void 0;this.cardFieldPlaceholders=t,this.postCardFieldPlaceholders(n?{}:t)}postCardFieldPlaceholders(e=this.cardFieldPlaceholders){let t=this.config.sessionId,{messageToken:n,expectedOrigin:s}=this;e===void 0||!t||!n||!s||this.postToHostedWindow({source:"flopay-vault-host",type:"cardFieldPlaceholders",sessionId:t,messageToken:n,placeholders:{...e}},s)}postCardBrandIcons(){this.postToHostedWindow({source:"flopay-vault-host",type:"cardBrandIcons",show:this.cardBrandIcons},this.directiveTargetOrigin())}setSubmitLabel(e){this.submitLabel=e,this.postSubmitLabel()}postSubmitLabel(){let e=this.submitLabel,t=this.config.sessionId,{messageToken:n,expectedOrigin:s}=this;e===void 0||!t||!n||!s||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:t,messageToken:n,label:e},s)}hostedWindow(){return this.container?.querySelector("iframe")?.contentWindow??null}postToHostedWindow(e,t){let n=this.hostedWindow();if(n)try{n.postMessage(e,t)}catch{}}directiveTargetOrigin(){return this.expectedOrigin??"*"}emit(e,t){for(let n of this.listeners.get(e)??[])n(t)}showActionRequiredOverlay(e){if(typeof document>"u")return;if(this.actionOverlay){let h=this.actionOverlay.querySelector("iframe");h instanceof HTMLIFrameElement&&h.src!==e&&(h.src=e),this.armActionRequiredTimeout();return}this.actionOverlayPreviousFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;let t=ge(this.beginActionChallengeAttempt()),n=Ce(e),s=!1,i=h=>{if(s)return;let y=ve(h,n);y&&(s=!0,t.record("policy_violation",{reason:y,evidenceBasis:"parent_csp_event"}))},o=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},a={telemetry:t,loaded:!1,detach:()=>{document.removeEventListener("securitypolicyviolation",i),window.removeEventListener("pagehide",o)}};this.actionChallenge=a,this.lastChallengeTelemetry=t,t.record("handoff_planned"),X(e)==="invalid"&&t.record("action_invalid",{reason:"invalid_url"}),document.addEventListener("securitypolicyviolation",i),window.addEventListener("pagehide",o);let l=document.createElement("div");l.setAttribute("data-flopay-action-required","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let c=document.createElement("iframe");c.setAttribute("title","Card authentication"),c.setAttribute("allow","payment"),c.tabIndex=0,c.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),c.addEventListener("load",()=>{a.loaded||(a.loaded=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"}))}),c.src=e,l.appendChild(c);let d=document.createElement("button");d.type="button",d.setAttribute("aria-label","Close card authentication"),d.textContent="\xD7",d.style.cssText=["position:fixed","top:20px","right:20px","width:40px","height:40px","border:0","border-radius:9999px","background:#fff","color:#0f172a","font-size:28px","line-height:40px","cursor:pointer","box-shadow:0 4px 14px rgba(0,0,0,0.25)"].join(";"),d.addEventListener("click",()=>this.abandonActionRequiredOverlay()),l.appendChild(d),l.addEventListener("click",h=>{h.target===l&&this.abandonActionRequiredOverlay()});let m=0,u=h=>{let y=h.data,f=!!y&&typeof y=="object"&&y.source==="flopay-vault-3ds-return";if(h.source!==c.contentWindow){f&&m<lr&&(m+=1,t.record("return_rejected",{reason:"untrusted_source",evidenceBasis:"message_origin_check"}));return}f&&(t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),D(N("vault.three_ds.returned","three_ds_return")),this.telemetryReporter?.log({name:"vault.three_ds.returned",stage:"three_ds_return",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay())};window.addEventListener("message",u),this.threeDsReturnHandler=u,t.record("render_attempted");try{document.body.appendChild(l)}catch(h){throw t.record("render_failed"),this.hideActionRequiredOverlay(),this.actionOverlayPreviousFocus=null,h}t.record("container_attached"),t.record("navigation_assigned");let g=fe(l);g&&t.record("container_visibility",{reason:g,evidenceBasis:"parent_computed_style"}),this.actionOverlay=l,c.focus(),this.armActionRequiredTimeout(),D(N("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},dr)}reportChallengeAbandoned(){D(We({eventId:"77777777-7777-4777-8777-777777777777",outcome:"customer_abandoned",stage:"three_ds_handoff",sequence:0,provider:"pcivault",paymentMethodCategory:"card"})),this.telemetryReporter?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"})}timeOutActionRequiredOverlay(){if(this.actionChallenge){let{telemetry:e,loaded:t}=this.actionChallenge;t||e.record("load_unconfirmed",{evidenceBasis:"no_load_signal"}),e.record("timer_expired",{reason:"window_elapsed",evidenceBasis:"timer"}),e.terminal("timer",{reason:"window_elapsed",evidenceBasis:"timer"})}this.reportChallengeAbandoned(),this.hideActionRequiredOverlay(),this.emit("error",{...this.config.sessionId?{sessionId:this.config.sessionId}:{},message:ur})}abandonActionRequiredOverlay(){if(this.actionOverlay){if(this.actionChallenge){let{telemetry:e}=this.actionChallenge;e.record("cancel_requested",{reason:"buyer_cancel",evidenceBasis:"signal_reason"}),e.terminal("cancel",{reason:"buyer_cancel",evidenceBasis:"signal_reason"})}this.reportChallengeAbandoned(),this.hideActionRequiredOverlay(),this.emit("challenge_dismissed",{...this.config.sessionId?{sessionId:this.config.sessionId}:{}})}}beginActionChallengeAttempt(){try{return this.telemetryReporter?.beginThreeDsChallenge?.()}catch{return}}endActionChallengeFromWidget(e){let t=this.actionChallenge,n=t?.telemetry??this.lastChallengeTelemetry;if(this.lastChallengeTelemetry=null,!!n){if(e==="submitting"){if(!t)return;n.record("abort_observed",{reason:"unspecified",evidenceBasis:"signal_reason"}),n.terminal("abort",{reason:"unspecified",evidenceBasis:"signal_reason"});return}t&&n.terminal("status_poll",{evidenceBasis:"server_status"}),e==="complete"&&n.reconcile("succeeded"),e==="decline"&&n.reconcile("declined")}}hideActionRequiredOverlay(){if(this.actionChallenge){let t=this.actionChallenge;this.actionChallenge=null;try{t.detach()}catch{}t.telemetry.record("teardown")}if(this.actionOverlayTimer&&(clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=null),this.threeDsReturnHandler&&(window.removeEventListener("message",this.threeDsReturnHandler),this.threeDsReturnHandler=null),!this.actionOverlay)return;this.actionOverlay.parentNode?.removeChild(this.actionOverlay),this.actionOverlay=null;let e=this.actionOverlayPreviousFocus;this.actionOverlayPreviousFocus=null,e?.isConnected&&e.focus()}applyHeight(e){let t=this.container?.querySelector("iframe");if(!t)return;let n=Math.max(0,Math.min(Math.ceil(e),2e3));t.style.height=`${n}px`}};function Qr(r,e){let t=ae;return new t(r,{reporter:e})}export{ue as a,he as b,P as c,z as d,Q as e,ce as f,de as g,ge as h,X as i,Fr as j,fe as k,ve as l,Ce as m,_ as n,A as o,Qt as p,se as q,Hr as r,ae as s,Qr as t};