@flopay/js 1.19.1 → 1.20.1

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.d.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  export type { CardFieldsEvent, CardFieldsFailedEvent, CardFieldsFailureReason, CardFieldsReadyEvent, SentryEventLike, SentryStackFrameLike, } from '@flopay/shared';
2
2
  export { dropThirdPartyOnlyError } from '@flopay/shared';
3
+ export type { CheckoutRuntime, CheckoutRuntimeEvent, CheckoutRuntimeEventName, CheckoutRuntimeHandle, CheckoutRuntimeMountOptions, CheckoutRuntimeUpdateOptions, } from './checkout-runtime/contract.js';
4
+ export type { LoadCheckoutRuntimeOptions } from './checkout-runtime-loader.js';
5
+ export { loadCheckoutRuntime } from './checkout-runtime-loader.js';
3
6
  export { createCheckoutSession, createCheckoutSessionWithRetries, } from './create-checkout-session.js';
4
7
  export { FloPay } from './flopay.js';
5
8
  export { loadFloPay } from './load.js';
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 Ue,g as Oe,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-AKNIWZAJ.mjs";import{dropThirdPartyOnlyError as Kt}from"@flopay/shared";import{assertCaptureMethodEligible as Ne,buildProductPayload as qe,classifyTelemetryFailure as ze,FloPayError as U,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 U(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:A,utmMetadata:T,idempotencyKey:O}=e,F=me(O);if(w.length>te)throw new U(`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 b=Ke(A,i,d,S);if(!b)throw new U("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:b,checkoutMode:m,products:S.map(v=>qe(v,b)),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),T&&T.length>0&&(C.utmMetadata=T);let q=`${o.replace(/\/+$/,"")}/v1/checkouts/sessions`,L={"Content-Type":"application/json"};F&&(L[$e]=F);let _,R,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{}_=P.status;try{R=await P.json()}catch{}if(_>=400)throw He(Ge(_,R),P);if(_===201){let v=R?.data?.uuid,D=R?.data?.nonce;if(!v)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!D)throw new U("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||b)&&Q(v,{currency:b,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??b}))});let y=new URL(`${a.replace(/\/+$/,"")}/secure`);y.searchParams.set("id",v);for(let[u,k]of Object.entries(I))y.searchParams.set(u,k);if(f&&typeof window<"u"&&typeof document<"u"){let u=JSON.stringify({origin_url:l}),k=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(u)}; domain=.${k}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(D)}; domain=.${k}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=y.toString()),{status:201,redirectUrl:y.toString(),nonce:D}}return _===204?(typeof window<"u"&&(window.location.href=n),{status:204}):{status:_}}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 U&&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 U&&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 be(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 _e(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}),be(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,sessionToken:t?.sessionToken,billingApiUrl:this.config.billingApiUrl,cardFieldsTimeoutMs:t?.cardFieldsTimeoutMs},this.telemetryReporter):new Z({sessionId:t?.sessionId,captureMethod:t?.captureMethod,sessionToken:t?.sessionToken,billingApiUrl:this.config.billingApiUrl,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 Re}from"@flopay/shared";import{FloPayError as ke}from"@flopay/shared";import{loadStripe as tt}from"@stripe/stripe-js";import{toStripeAppearance as rt,toStripeAppearanceTheme as ot}from"@flopay/shared";var Ae=new WeakSet;function Te(e){return e instanceof ke&&Ae.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 ke("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw Ae.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:Re,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&&_e(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:Re,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:Te(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),A=yt(x);return a(A),A}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,A=0,T=0,O=!1,F=!1,S=!1,b=0,C=()=>{window.clearTimeout(x),window.clearInterval(A),window.clearTimeout(T),window.removeEventListener("message",v),window.removeEventListener("pagehide",L),document.removeEventListener("securitypolicyviolation",_),m.removeEventListener("load",R),e.signal?.removeEventListener("abort",B)},q=async()=>{if(!(f||O)){O=!0;try{let y=await c();if(f||!pt(y))return;f=!0,C(),t.terminal("status_poll",{evidenceBasis:"server_status"}),g(y)}finally{O=!1}}},L=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},_=y=>{if(S)return;let u=le(y,w);u&&(S=!0,t.record("policy_violation",{reason:u,evidenceBasis:"parent_csp_event"}))},R=()=>{F||(F=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"})),e.pollCompletionEndpoint!==!1&&(window.clearTimeout(T),T=window.setTimeout(()=>{q()},250))},B=()=>{f||(f=!0,C(),o(e.signal?.reason),I(H()))},P=y=>{f||b>=at||(b+=1,t.record("return_rejected",{reason:y,evidenceBasis:"message_origin_check"}))},v=y=>{let u=y.data,k=!!u&&typeof u=="object"&&u.source==="flopay-vault-3ds-return";if(y.source!==m.contentWindow){k&&P("untrusted_source");return}if(h&&y.origin!==h){k&&P("untrusted_origin");return}k&&(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&&(A=window.setInterval(()=>{q()},ct)),m.addEventListener("load",R),window.addEventListener("message",v),window.addEventListener("pagehide",L),document.addEventListener("securitypolicyviolation",_),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,Oe as clearSessionDisplayData,gt as completeSavedCardNextAction,Qe as createCheckoutSession,Xe as createCheckoutSessionWithRetries,H as createSavedCardActionAbortedError,Kt as dropThirdPartyOnlyError,Ue as getSessionDisplayData,st as loadFloPay,Me as runSavedCardChallenge,rt as toStripeAppearance,ot as toStripeAppearanceTheme};
1
+ import{a as W,b as G,c as J,d as se,e as Q,f as Ne,g as Be,h as X,i as ae,j as le,k as ce,l as de,m as ue,n as z,o as A,p as qe,q as ze,r as me,s as Z,t as pe}from"./chunk-5OENCIZW.mjs";import{dropThirdPartyOnlyError as tr}from"@flopay/shared";import{FloPayError as ye}from"@flopay/shared";var je="FloPayCheckoutRuntime",Ve=1e4,te=new Map;function Ke(e){return typeof e=="object"&&e!==null&&typeof e.mount=="function"}function ee(e){return new ye(e==="runtime_load_timeout"?"The checkout runtime did not load in time.":"The checkout runtime failed to load.","network_error",{code:e})}function $e(e,t){return new Promise((r,o)=>{let i=document.createElement("script"),s=!1,d=l=>{s||(s=!0,clearTimeout(n),i.removeEventListener("load",a),i.removeEventListener("error",c),l instanceof ye?(te.delete(e),i.remove(),o(l)):r(l))},a=()=>{let l=Reflect.get(globalThis,je);d(Ke(l)?l:ee("runtime_load_failed"))},c=()=>d(ee("runtime_load_failed")),n=setTimeout(()=>d(ee("runtime_load_timeout")),t);i.addEventListener("load",a),i.addEventListener("error",c),i.async=!0,i.src=e,document.head.appendChild(i)})}function He(e){let{runtimeUrl:t,timeoutMs:r=Ve}=e,o=te.get(t);if(o!==void 0)return o;let i=$e(t,r);return te.set(t,i),i}import{assertCaptureMethodEligible as Ye,buildProductPayload as We,classifyTelemetryFailure as Ge,FloPayError as U,foldIntoProducts as Je,IDEMPOTENCY_IN_PROGRESS_CODE as Qe,IDEMPOTENCY_KEY_HEADER as Xe,resolveIdempotencyKey as fe,resolveSessionCurrency as Ze,SDK_VERSION as ge,telemetryStatusClass as he,withTelemetryHttpDiagnostics as et}from"@flopay/shared";var oe=5,Ce=new WeakSet;function tt(e){(typeof e=="object"&&e!==null||typeof e=="function")&&Ce.add(e)}function rt(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&Ce.has(e)}function ot(e,t){let r=t?.error,o=W(t?.code)??W(r?.code)??`http_${e}`,i=G(t?.message)??G(r?.message)??nt(o,e);return new U(i,"api_error",{code:o,statusCode:e})}function nt(e,t){switch(e){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${oe}.`;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 ve(e,t,r){let{billingApiUrl:o,checkoutBaseUrl:i,items:s=[],subscriptions:d=[],products:a,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:P,utmMetadata:T,idempotencyKey:O}=e,F=fe(O);if(w.length>oe)throw new U(`Too many coupon codes \u2014 a checkout session accepts at most ${oe}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let k=a??Je(s,d);Ye({captureMethod:h,products:k});let _=Ze(P,s,d,k);if(!_)throw new U("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:ge,successUrl:n,cancelUrl:l,currency:_,checkoutMode:m,products:k.map(v=>We(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),T&&T.length>0&&(C.utmMetadata=T);let q=`${o.replace(/\/+$/,"")}/v1/checkouts/sessions`,L={"Content-Type":"application/json"};F&&(L[Xe]=F);let b,E,N={method:"POST",headers:L,body:JSON.stringify(C),signal:t},S;try{r?.startAttempt(),S=await fetch(q,N)}catch(v){throw tt(v),v}try{r?.record(S.status)}catch{}b=S.status;try{E=await S.json()}catch{}if(b>=400)throw et(ot(b,E),S);if(b===201){let v=E?.data?.uuid,M=E?.data?.nonce;if(!v)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!M)throw new U("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"});(k.length>0||_)&&Q(v,{currency:_,products:k.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(`${i.replace(/\/+$/,"")}/secure`);y.searchParams.set("id",v);for(let[u,R]of Object.entries(I))y.searchParams.set(u,R);if(f&&typeof window<"u"&&typeof document<"u"){let u=JSON.stringify({origin_url:l}),R=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(u)}; domain=.${R}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(M)}; domain=.${R}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=y.toString()),{status:201,redirectUrl:y.toString(),nonce:M}}return b===204?(typeof window<"u"&&(window.location.href=n),{status:204}):{status:b}}async function it(e){let t=_e(e),r=we(t),o=J(e.timeoutMs);try{let i=await ve(e,o.signal,r);return r.commit(),be(t,i),i}catch(i){throw r.commit(),j(t,i),i}finally{o.clear(),D(t.reporter)}}function we(e){let t=!1,r=e.startedAt,o;return{startAttempt(){r=e.reporter.now()},record(i){o={status:i,durationMs:Math.max(0,e.reporter.now()-r),attempt:e.attempt}},commit(){if(t||!o)return;t=!0;let i=he(o.status);e.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:i,attempt:o.attempt}),e.reporter.performance({stage:"session_first_byte",durationMs:o.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:i,attempt:o.attempt})}}}function _e(e){let t=new A({billingApiUrl:e.billingApiUrl,sdkVersion:ge,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 be(e,t){let r=he(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=Ge(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 U&&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 D(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}async function st(e){let{maxRetries:t=2,...r}=e,o=_e(e),i=we(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"}),D(o.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let s={...r,idempotencyKey:fe(r.idempotencyKey)},d=J(r.timeoutMs),a;for(let c=0;c<=t;c++){o.attempt=c;try{let n=await ve(s,d.signal,i);return i.commit(),be(o,n),d.clear(),D(o.reporter),n}catch(n){a=n;let l=n instanceof Error&&n.name==="AbortError",m=rt(n),h=n instanceof U&&n.code===Qe;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 se(c,d.signal)}catch(w){throw i.commit(),j(o,w),d.clear(),D(o.reporter),w}continue}throw i.commit(),j(o,n),d.clear(),D(o.reporter),n}}throw i.commit(),j(o,a),d.clear(),D(o.reporter),a??new Error("Unknown error during checkout session creation")}import{classifyTelemetryFailure as at,FloPayError as V,resolveBillingApiUrl as Pe,SDK_VERSION as lt}from"@flopay/shared";var ke=Symbol.for("@flopay/js.telemetry.bridge.v1");function Se(e,t,r){let o=()=>t?.now()??r();Object.defineProperty(e,ke,{configurable:!1,enumerable:!1,writable:!1,value:{error:s=>t?.error(s),log:s=>t?.log(s),performance:s=>t?.performance(s),terminal:s=>t?.terminal(s),now:o,elapsed:s=>Math.max(0,o()-s),setCheckoutContext:s=>t?.setCheckoutContext(s),beginCheckout:(s={})=>t?.beginCheckout(s)??o(),disable:()=>t?.disable(),subscribe:s=>t?.subscribe(s)??(()=>{}),flush:()=>t?.flush()??Promise.resolve()}})}function Re(e){return e[ke]}var K=class{now(){return this.telemetryReporter?.now?.()??z()}constructor(t,r,o){this.provider=t,this.config=r,this.telemetryReporter=o??new A({billingApiUrl:Pe(r.billingApiUrl),sdkVersion:lt,enabled:r.telemetry!==!1}),Se(this,this.telemetryReporter,z)}cardCapture(t){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?pe({sessionId:t?.sessionId,captureMethod:t?.captureMethod,sessionToken:t?.sessionToken,billingApiUrl:this.config.billingApiUrl,cardFieldsTimeoutMs:t?.cardFieldsTimeoutMs},this.telemetryReporter):new Z({sessionId:t?.sessionId,captureMethod:t?.captureMethod,sessionToken:t?.sessionToken,billingApiUrl:this.config.billingApiUrl,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=Pe(r??this.config.billingApiUrl),i=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let s,d,a=n=>{if(s===void 0)return;let l=s,m=d;s=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=me(o,{now:()=>this.telemetryReporter?.now()??z(),onFirstByte:(n,l)=>{s=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 a("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()-i,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),n}catch(n){let l=at(n,n instanceof V&&n.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw a(l.statusClass),this.telemetryReporter?.error({...l,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-i,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 Te(e,t,r){let o=K;return new o(e,t,r)}import{FloPayError as mt,resolveBillingApiUrl as ne,SDK_VERSION as xe}from"@flopay/shared";import{FloPayError as Ee}from"@flopay/shared";import{loadStripe as ct}from"@stripe/stripe-js";import{toStripeAppearance as dt,toStripeAppearanceTheme as ut}from"@flopay/shared";var Ae=new WeakSet;function Ie(e){return e instanceof Ee&&Ae.has(e)}var B=class{constructor(){this.name="stripe";this.stripe=null}async initialize(t){if(typeof window>"u")return;let r=await ct(t.publishableKey,{locale:t.locale??"auto"});if(!r){let o=new Ee("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw Ae.add(o),o}this.stripe=r}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var Fe=new Map;function ie(e){return Array.isArray(e)?e.map(ie):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,ie(r)])):e}function pt(e,t){return JSON.stringify([e,ne(t?.billingApiUrl),t?.telemetry!==!1,t?.locale??"auto",t?.apiVersion??null,ie(t?.appearance??null)])}var $=new Map;async function yt(e,t){if(!e){let a=new A({billingApiUrl:ne(t?.billingApiUrl),sdkVersion:xe,enabled:t?.telemetry!==!1});throw a.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),a.flush().catch(()=>{}).finally(()=>a.destroy()),new mt("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let r=pt(e,t),o=Fe.get(r);if(o)return t?.telemetry!==!1&&Re(o)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),o;let i=$.get(r);if(i)return i;let s={...t,publishableKey:e},d=(async()=>{let a=new A({billingApiUrl:ne(s.billingApiUrl),sdkVersion:xe,enabled:s.telemetry!==!1}),c=a.now();a.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),a.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),a.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let n=new B,l=a.now();try{await n.initialize(s)}catch(w){throw a.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:Ie(w)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),a.destroy(),w}let m=a.now();a.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),a.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),a.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),a.performance({stage:"sdk_initialize",durationMs:m-c,durationMode:"machine",provider:"stripe"}),a.performance({stage:"provider_ready",durationMs:m-l,durationMode:"machine",provider:"stripe"});let h=Te(n,s,a);return Fe.set(r,h),h})();$.set(r,d);try{return await d}finally{$.get(r)===d&&$.delete(r)}}import{FloPayError as Y,THREE_DS_CHALLENGE_WINDOW_MS as De}from"@flopay/shared";var ft=4,gt=1e3,ht=1e3,Ct=15e3;function vt(e){let t=!!e?.gateways?.stripe,r=!!e?.gateways?.worldpayCorporateGateway;return t===r?"unknown":t?"stripe":"worldpay"}function wt(e,t,r){try{return typeof e?.beginThreeDsChallenge!="function"?void 0:e.beginThreeDsChallenge(t,{provider:vt(r)})}catch{return}}function H(e){return new Y("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Ue(){return new Y("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Oe(e){return e.replace(/\/+$/,"")}function _t(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}function bt(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 Le(e){if(typeof document>"u"||typeof window>"u")throw new Y("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});let t=X(e.telemetry);t.record("handoff_planned");let r=ae(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=le(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"})},i=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 s=`${Oe(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(),Ct);try{let f=await fetch(s,{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),P=bt(x);return i(P),P}catch{return{status:"unknown"}}finally{window.clearTimeout(I),e.signal?.removeEventListener("abort",g)}},a,c=()=>e.pollCompletionEndpoint!==!1?d():(a??(a=d()),a),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=ue(e.nextActionRedirectUrl);try{let p=await new Promise((g,I)=>{let f=!1,x=0,P=0,T=0,O=!1,F=!1,k=!1,_=0,C=()=>{window.clearTimeout(x),window.clearInterval(P),window.clearTimeout(T),window.removeEventListener("message",v),window.removeEventListener("pagehide",L),document.removeEventListener("securitypolicyviolation",b),m.removeEventListener("load",E),e.signal?.removeEventListener("abort",N)},q=async()=>{if(!(f||O)){O=!0;try{let y=await c();if(f||!_t(y))return;f=!0,C(),t.terminal("status_poll",{evidenceBasis:"server_status"}),g(y)}finally{O=!1}}},L=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},b=y=>{if(k)return;let u=de(y,w);u&&(k=!0,t.record("policy_violation",{reason:u,evidenceBasis:"parent_csp_event"}))},E=()=>{F||(F=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"})),e.pollCompletionEndpoint!==!1&&(window.clearTimeout(T),T=window.setTimeout(()=>{q()},250))},N=()=>{f||(f=!0,C(),o(e.signal?.reason),I(H()))},S=y=>{f||_>=ft||(_+=1,t.record("return_rejected",{reason:y,evidenceBasis:"message_origin_check"}))},v=y=>{let u=y.data,R=!!u&&typeof u=="object"&&u.source==="flopay-vault-3ds-return";if(y.source!==m.contentWindow){R&&S("untrusted_source");return}if(h&&y.origin!==h){R&&S("untrusted_origin");return}R&&(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(Ue()))},De),e.pollCompletionEndpoint!==!1&&(P=window.setInterval(()=>{q()},ht)),m.addEventListener("load",E),window.addEventListener("message",v),window.addEventListener("pagehide",L),document.addEventListener("securitypolicyviolation",b),e.signal?.addEventListener("abort",N),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 M=ce(l);M&&t.record("container_visibility",{reason:M,evidenceBasis:"parent_computed_style"}),m.focus(),e.signal?.aborted&&N()});return p||await c()}finally{l.parentNode?.removeChild(l),t.record("teardown"),n?.isConnected&&n.focus()}}function Me(e,t){try{let r=t.data.session?.status;r==="complete"?e.reconcile("succeeded"):r==="authorized"&&e.reconcile("authorized")}catch{}}function kt(e){return new Y("Card was declined.","api_error",{code:e.declineReason??"authorization_declined",...e.gatewayDeclineReason?{declineCode:e.gatewayDeclineReason}:{}})}async function St(e,t){let r=`${Oe(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/status`,o=new AbortController,i=new AbortController,s=()=>{o.abort(e.signal?.reason),i.abort(e.signal?.reason)};e.signal?.aborted?s():e.signal?.addEventListener("abort",s,{once:!0});let d=X(e.telemetry),a=Le({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:gt,nonce:e.nonce,statusUrl:r,continueAfterActionRequired:!0,timeoutMs:De+15e3,signal:i.signal,...d.attemptId?{challengeAttemptId:d.attemptId}:{}});c.catch(()=>{}),a.catch(()=>{});try{let n=await Promise.race([a,c]);if("data"in n)return d.terminal("status_poll",{evidenceBasis:"server_status"}),Me(d,n),n;if(n.status==="declined")throw(e.createDeclineError??kt)(n);if(n.status==="timeout")throw Ue();let l=await c;return Me(d,l),l}catch(n){throw e.signal?.aborted||n instanceof Error&&n.name==="AbortError"?H(n):n}finally{e.signal?.removeEventListener("abort",s),o.abort(),i.abort()}}export{K as FloPay,ze as PaymentAPI,Z as PciVaultCardCapture,qe as SESSION_CREATE_TELEMETRY,B as StripeAdapter,wt as beginSavedCardChallengeTelemetry,Q as cacheSessionDisplayData,Be as clearSessionDisplayData,St as completeSavedCardNextAction,it as createCheckoutSession,st as createCheckoutSessionWithRetries,H as createSavedCardActionAbortedError,tr as dropThirdPartyOnlyError,Ne as getSessionDisplayData,He as loadCheckoutRuntime,yt as loadFloPay,Le as runSavedCardChallenge,dt as toStripeAppearance,ut as toStripeAppearanceTheme};
@@ -115,6 +115,18 @@ export type ThreeDsAbandonResult = 'closed' | 'not_open' | 'failed';
115
115
  export interface PaymentAPIOptions {
116
116
  /** Flo-owned privacy-safe telemetry is enabled by default; set false to opt out. */
117
117
  telemetry?: boolean;
118
+ /**
119
+ * Declare that the caller re-initialises Stripe and re-mounts its wallet
120
+ * buttons when a claim moves a detached checkout to another Stripe account.
121
+ * The detached create and every claim then carry the
122
+ * `stripe-account-switch-v1` capability, so the billing API keeps Apple Pay
123
+ * and Google Pay on such a claim instead of hiding them.
124
+ *
125
+ * Off by default. Set it only from an integration that really performs the
126
+ * switch (`@flopay/react`'s `FloPayCheckout` does): a caller that keeps its
127
+ * first Stripe instance would mount wallets on the wrong account.
128
+ */
129
+ stripeAccountSwitch?: boolean;
118
130
  }
119
131
  interface PaymentApiTelemetryHooks {
120
132
  now?: () => number;
@@ -140,6 +152,8 @@ export declare class PaymentAPI {
140
152
  private readonly baseUrl;
141
153
  private readonly directTelemetry?;
142
154
  private readonly telemetryHooks?;
155
+ /** Whether detached creates and claims declare the Stripe account switch. */
156
+ private readonly stripeAccountSwitch;
143
157
  private directTelemetryCheckoutId?;
144
158
  constructor(billingApiUrl: string, options?: PaymentAPIOptions);
145
159
  /** Dispose the reporter owned by direct public usage. Internal hooks are never disposed here. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flopay/js",
3
- "version": "1.19.1",
3
+ "version": "1.20.1",
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.19.1",
34
+ "@flopay/shared": "1.20.1",
35
35
  "@stripe/stripe-js": "^10.3.0"
36
36
  },
37
37
  "devDependencies": {
@@ -1 +0,0 @@
1
- var it="flopay_session_display:";var B=new Map;function z(n){return`${it}${n}`}function X(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function Z(n,e,t){if(!n)return;let r=t?.ttlMs??36e5,s={data:e,expiresAt:Date.now()+r},i=X();if(i)try{i.setItem(z(n),JSON.stringify(s));return}catch{}B.set(n,s)}function ue(n){if(!n)return null;let e=X();if(e)try{let r=e.getItem(z(n));if(r){let s=JSON.parse(r);if(s&&typeof s.expiresAt=="number"&&s.expiresAt>Date.now())return s.data;e.removeItem(z(n))}}catch{}let t=B.get(n);if(t){if(t.expiresAt>Date.now())return t.data;B.delete(n)}return null}function he(n){if(!n)return;B.delete(n);let e=X();if(e)try{e.removeItem(z(n))}catch{}}import{ASYNC_AUTO_CHECKOUT_CAPABILITY as St,assertCaptureMethodEligible as ke,buildProductPayload as ie,CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as At,CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED as wt,classifyPaymentRejection as Et,classifyTelemetryFailure as x,FLO_SDK_CAPABILITIES_HEADER as kt,FLO_SDK_VERSION_HEADER as U,FloPayError as v,foldIntoProducts as te,IDEMPOTENCY_IN_PROGRESS_CODE as Mt,IDEMPOTENCY_KEY_HEADER as Me,isCardHolderNamePlaceholder as oe,isDetachedSessionEligible as It,isUuidV4 as Ie,isValidEmail as De,markSessionResponseReceived as L,normalizeCheckoutFailureOutcome as Pe,normalizePaymentMethodLayout as Dt,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as re,randomUuidV4 as Pt,readTelemetryHttpDiagnostics as Ft,resolveIdempotencyKey as Ot,resolveSessionCurrency as ne,SDK_VERSION as E,STORED_PAYMENT_METHOD_UNSUPPORTED_CODE as Fe,STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE as Oe,telemetryStatusClass as M,withTelemetryHttpDiagnostics as je}from"@flopay/shared";function me(n){return typeof n=="string"&&n.trim()?n:void 0}function pe(n){if(typeof n=="string")return n.trim()?n:void 0;if(Array.isArray(n))return n.filter(t=>typeof t=="string"&&t.trim().length>0).join("; ")||void 0}function D(n=12e3){let e=Number.isFinite(n)&&n>=0?n:12e3,t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function ot(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function H(n,e){let t=150*2**n,r=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(ot())};if(e.aborted){l();return}o=setTimeout(()=>{a(),s()},r),e.addEventListener("abort",l,{once:!0})})}import{buildTelemetryErrorEvent as _e,buildTelemetryLogEvent as Re,buildTelemetryPerformanceEvent as ht,buildTelemetryTerminalEvent as mt,serializeTelemetryBatch as pt,TELEMETRY_MAX_BATCH_BYTES as yt}from"@flopay/shared";import{isThreeDsChallengeAttemptId as ge}from"@flopay/shared";var at=32,ye=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function lt(){let n=globalThis,e=n[ye];if(e instanceof Map)return e;let t=new Map;try{Object.defineProperty(n,ye,{configurable:!0,enumerable:!1,writable:!1,value:t})}catch{}return t}function dt(n,e){let t=lt(),r=t.get(n);if(r)return r;for(;t.size>=at;){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(n,s),s}var ct=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),ut=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function fe(n,e={}){let t=ge(e.attemptId)?e.attemptId.toLowerCase():n.newAttemptId(),r=()=>{try{let a=n.now();return Number.isFinite(a)?a:0}catch{return 0}},s=dt(t,r());(e.provider==="stripe"||e.provider==="worldpay")&&(s.provider=e.provider);let i=s.provider,o=(a,l)=>{if(s.terminated&&!ut.has(a))return;let d={attemptId:t,phase:a,attemptSequence:s.nextSequence,elapsedMs:Math.max(0,r()-s.startedAt),provider:i};s.nextSequence+=1,l.reason!==void 0&&(d.reason=l.reason),l.evidenceBasis!==void 0&&(d.evidenceBasis=l.evidenceBasis),l.terminalSource!==void 0&&(d.terminalSource=l.terminalSource),l.providerOutcome!==void 0&&(d.providerOutcome=l.providerOutcome);try{n.emit(d,ct.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 ve(n){let e=null;try{e=ge(n?.attemptId)?n?.attemptId??null:null}catch{e=null}return{attemptId:e,record(t,r){try{n?.record(t,r)}catch{}},terminal(t,r){try{n?.terminal(t,r)}catch{}},reconcile(t){try{n?.reconcile(t)}catch{}}}}function ee(n){if(typeof n!="string"||n.trim()==="")return"missing";try{let e=new URL(n);return e.protocol==="https:"||e.protocol==="http:"?"valid":"invalid"}catch{return"invalid"}}function zr(n){return n==="buyer_cancel"||n==="component_unmount"||n==="navigation"?n:"unspecified"}function Ce(n){try{if(typeof window>"u"||typeof window.getComputedStyle!="function")return null;for(let e=n;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 Te(n,e){if(!e)return null;try{let t=n,r=String(t.effectiveDirective||t.violatedDirective||"").trim().split(/\s+/)[0],s=null;return r==="frame-src"&&(s="frame_src"),r==="child-src"&&(s="child_src"),!s||typeof t.blockedURI!="string"?null:new URL(t.blockedURI).origin===e?s:null}catch{return null}}function be(n){try{return ee(n)==="valid"?new URL(n).origin:null}catch{return null}}var gt="/v1/sdk-telemetry/events",j=16,Se=64,ft=1500,Ae=1e3,vt=64,Ct="00000000-0000-4000-8000-000000000000",Tt={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},bt=48;function A(){try{return globalThis.crypto.randomUUID()}catch{let n=new Uint8Array(16);try{globalThis.crypto.getRandomValues(n)}catch{for(let t=0;t<n.length;t+=1)n[t]=Math.floor(Math.random()*256)}n[6]=(n[6]??0)&15|64,n[8]=(n[8]??0)&63|128;let e=[...n].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 _t(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function Rt(n){return JSON.stringify([n.code,n.failureCategory,n.reason,n.stage,n.provider,n.attempt,n.statusClass,n.requestCategory,n.paymentMethodCategory,n.walletType,n.operationOutcome,n.checkoutMode,n.layout,n.inAppBrowser,n.appFamily,n.popupCapability,n.presentationMode,n.terminalReason])}function _(){return globalThis.performance?.now()??0}var w=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(/\/+$/,"")}${gt}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=A(),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(Re({...this.checkoutContext,...e,eventId:A(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=_e({...this.checkoutContext,...e,eventId:Ct,sequence:0}),r=Rt(t),s=this.now();this.pruneReportedFailures(s);let i=this.reportedFailures.get(r);if(i!==void 0&&s>=i&&s-i<Ae){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(r,s),this.enqueue(_e({...this.checkoutContext,...e,eventId:A(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue(ht({...this.checkoutContext,...e,eventId:A(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue(mt({...this.checkoutContext,...e,eventId:A(),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 fe({now:()=>this.now(),newAttemptId:A,emit:(t,r)=>this.recordThreeDsChallenge(t,r)},e)}recordThreeDsChallenge(e,t){if(!this.canCollect()||this.threeDsChallengeCount>=bt)return;let r=Re({...this.checkoutContext,...e,name:"three_ds.challenge",stage:"three_ds_handoff",eventId:A(),sequence:this.sequence++});if(!(this.queue.length>=Se)){if(this.threeDsChallengeCount+=1,this.queue.push(r),t){this.drainQueue();return}if(this.queue.length>=j){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,r]of this.reportedFailures)(e<r||e-r>=Ae)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=vt;){let r=this.reportedFailures.keys().next();if(r.done)break;this.reportedFailures.delete(r.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>=Se||this.eventCounts[e.class]>=Tt[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=j){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,j);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,j);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=pt(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:A()});if(_t(t)>yt)return;let r=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:r?.signal}).then(async l=>{if(l.status!==202)return null;let d=null;try{d=await l.json()}catch{}return d?.status==="disabled"?"disabled":null}).catch(()=>null),o=new Promise(l=>{s=setTimeout(()=>{r?.abort(),l(null)},ft)});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)}},we=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),Ee=globalThis;Ee[we]===void 0&&Object.defineProperty(Ee,we,{configurable:!0,enumerable:!1,writable:!1,value:n=>new w(n)});function xt(n){return n==="on_session"||n==="off_session"}function Ut(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function Lt(n){let e=n.vaultOutcome;if(!(!e||e.code!==wt))return typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0}var qt="x-flopay-process-result-source",Nt="status",Ke=new WeakSet;function Vt(n,e){let t=new v(n,"api_error",{code:e,statusCode:500});return Ke.add(t),t}function Bt(n){return typeof n=="object"&&n!==null&&Ke.has(n)}function xe(n){return n?.result==="DECLINE"||n?.result==="ERROR"}var zt=50,I=new Map;function Ht(n,e){return I.get(n)?.has(e)===!0}function jt(n,e){let t=I.get(n)??new Set;if(t.add(e),I.delete(n),I.set(n,t),I.size>zt){let r=I.keys().next().value;r!==void 0&&I.delete(r)}}function Kt(n){let e=n?.threeDSecureActionResultTokenId;if(typeof e=="string"&&e.length>0)return e;if(n?.gateway==="paypal"&&n.type!=="paypal_setup_token"&&typeof n.id=="string"&&n.id.length>0)return n.id}var Ue=0,Le=500,K=15e3,qe=15e3,Gt=3e3,$t=1e4,Yt=1e4;function q(n){return typeof n=="object"&&n!==null}function k(n,e){return me(n?.[e])}function Ne(n,e){return pe(n?.[e])}function Wt(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function $(n,e){return e?new Promise((t,r)=>{let s=()=>{clearTimeout(i),r(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},i=setTimeout(()=>{e.removeEventListener("abort",s),t()},n);e.aborted?s():e.addEventListener("abort",s,{once:!0})}):new Promise(t=>setTimeout(t,n))}function se(n){return n instanceof Error&&n.name==="AbortError"}function b(){return new v(At,"api_error",{code:"checkout_processing_timeout"})}async function S(n,e){let t=await n.json().catch(()=>null),r=q(t?.error)?t.error:null,s=Ne(t,"message")??Ne(r,"message")??e,i=k(t,"code")??k(t,"gatewayErrorCode")??k(r,"code")??`http_${n.status}`;return je(new v(s,"api_error",{code:i,statusCode:n.status}),n)}async function Jt(n){if(n.status!==403)return!1;let e=await n.clone().json().catch(()=>null),t=q(e?.error)?e.error:null;return(k(e,"code")??k(t,"code"))==="verification_required"}function Qt(n){if(!(!q(n)||typeof n.required!="boolean"))return{required:n.required,provider:"turnstile"}}async function Xt(n){let e=n.status===400?await n.clone().json().catch(()=>null):null;return Et(n.status,e)}function Ve(n){return n===400||n===422}var Y=2;async function G(n,e,t=Y,r,s){let i;for(let o=0;;o++)try{return s?.(o),await fetch(n,e)}catch(a){if(e?.signal?.aborted||a instanceof Error&&a.name==="AbortError")throw a;if(i=a,o>=t)throw i;try{r?.(o+1)}catch{}await $(150*2**o,e?.signal??void 0)}}var Zt=2e3,er=1e4,tr=150;async function rr(n){try{let t=(await n.json())?.data?.status;return t==="closed"||t==="not_open"?t:"failed"}catch{return"failed"}}async function Be(n,e,t){let r=new AbortController,s=()=>r.abort();t?.addEventListener("abort",s,{once:!0});let i,o=new Promise(a=>{i=setTimeout(()=>{r.abort(),a("timeout")},er)});try{let a=await Promise.race([fetch(n,{...e,signal:r.signal}),o]);return a==="timeout"?"failed":a.status>=500?"retry":a.ok?await rr(a):"failed"}catch{return r.signal.aborted?"failed":"retry"}finally{clearTimeout(i),t?.removeEventListener("abort",s)}}function nr(n,e){return new Promise(t=>{let r=setTimeout(t,e);n.then(()=>{clearTimeout(r),t()},()=>{clearTimeout(r),t()})})}var sr=Symbol.for("@flopay/js.session-create.telemetry.v1");function ir(n){return n[sr]}function or(n){return"now"in n||"onFirstByte"in n||"onSessionCreateFailure"in n||"onRetry"in n}function Ge(n){let e=oe(n.firstName,n.lastName);return{userId:n.userId,firstName:e?null:n.firstName??null,lastName:e?null:n.lastName??null,email:n.email,country:n.country??null,gender:n.gender??null,city:n.city??null,state:n.state??null,zip:n.zip??null,addressLine1:n.addressLine1??null,addressLine2:n.addressLine2??null}}function $e(n,e){e.checkoutMetadata!==void 0&&(n.checkoutMetadata=e.checkoutMetadata),e.tagsData&&(n.tagsData=e.tagsData),e.utmMetadata&&e.utmMetadata.length>0&&(n.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(n.avsCheck=e.avsCheck),e.checkoutType&&(n.checkoutType=e.checkoutType),e.checkoutLayout&&(n.checkoutLayout=e.checkoutLayout),e.avsConfig&&(n.avsConfig=e.avsConfig)}function ze(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function ar(n){let e={};if(n.country&&(e.country=n.country),!oe(n.firstName,n.lastName)){let t=ze(n.firstName),r=ze(n.lastName);t&&(e.firstName=t),r&&(e.lastName=r)}return Object.keys(e).length>0?e:void 0}function lr(n,e){let t={clientId:n.clientId,checkoutVersion:E,successUrl:n.successUrl,cancelUrl:n.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};n.captureMethod==="manual"&&(t.captureMethod=n.captureMethod);let r=ar(n.account);return r&&(t.accountData=r),$e(t,n),t}function He(n,e,t){return{currency:e,products:t.map(r=>ie(r,e)),couponCodes:n.couponCodes??[],accountData:Ge(n.account)}}function dr(n,e,t){return{currency:e,products:t.map(r=>ie(r,e)),couponCodes:n.couponCodes??[]}}function cr(n){let e={},t=oe(n.firstName,n.lastName);for(let[r,s]of Object.entries(n)){if(t&&r.endsWith("Name")||typeof s!="string")continue;let i=s.trim();i&&(e[r]=i)}return{accountData:e}}var R=class R{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=or(t);this.telemetryHooks=r?t:void 0,this.directTelemetry=r||t.telemetry===!1?void 0:new w({billingApiUrl:this.baseUrl,sdkVersion:E})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,s,i="unknown"){let o=x(e,t);this.directTelemetry?.error({...o,...Bt(e)?{reason:"capture_failed"}:{},stage:r,requestCategory:s,paymentMethodCategory:i})}reportAccountSnapshotFailure(e,t){let r=x(e,"NETWORK_REQUEST_FAILED");if(t==="best_effort"&&r.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...r,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,r=!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 d=!1;try{let c=await G(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:l,signal:s},Y,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()});d=!0;let m=Math.max(0,this.telemetryTimestamp()-o);try{this.telemetryHooks?.onFirstByte?.(m,a)}catch{}let u=`${Math.floor(c.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}),!c.ok)throw await S(c,"Failed to get checkout session");let g=await c.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(c){throw d&&L(c),r&&this.directTelemetry?.error({...x(c,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),c}}cacheSessionDisplayData(e,t,r){Z(e,t,r)}clearSessionDisplayData(e){he(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,s=R.activeVaultCaptureRequests.get(r);if(s!==void 0)return s;let i=R.pendingThreeDsAbandonReports.get(e),o=i===void 0?this.requestVaultCapture(e,t):nr(i,Zt).then(()=>this.requestVaultCapture(e,t));R.activeVaultCaptureRequests.set(r,o);try{return await o}finally{R.activeVaultCaptureRequests.get(r)===o&&R.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),Yt);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 G(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:o,signal:r.signal},Y,d=>{this.telemetryHooks?.onRetry?.("vault_capture",d),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:d})});if(await Jt(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=r.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 r=await this.getCheckoutSession(e,t);return this.normalizeCheckoutSessionResponse(r)}async getUnifiedCheckoutSessionForRecovery(e,t,r){let s=await this.fetchCheckoutSession(e,t,!1,r);return this.normalizeCheckoutSessionResponse(s)}normalizeCheckoutSessionResponse(e){try{let t=this.normalizeRawSession(e.data),r=e.vault;return r&&t.data.session&&(t.data.session.vault=this.toVaultBlock(r)),t}catch(t){throw L(t)}}async processPayment(e,t,r){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,d=Kt(t.tokenizedData),c,m;try{c=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=c}catch(u){if(se(u))throw this.reportDirectFailure(u,"PAYMENT_PROCESSING_FAILED","processing","process_payment",s),u;c=await this.reconcileProcessPayment(t.sessionId,{...r,nonce:o,paymentMethodCategory:s,submittedIntentId:d})}if(!c.ok&&c.status!==202){let u=await Xt(c);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:M(c.status),failureCategory:c.status>=500?"server_error":void 0,paymentMethodCategory:s,...Ft(m)}),c}try{let u=await this.resolveProcessResponse(c,t.sessionId,{...r,nonce:o,paymentMethodCategory:s,submittedIntentId:d});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:M(u.status),paymentMethodCategory:s}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"process_payment",statusClass:M(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,r,s){this.beginDirectTelemetryCheckout(e);let i=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let o=s?.timeoutMs??$t,a=new AbortController,l=()=>a.abort();s?.signal&&(s.signal.aborted?a.abort():s.signal.addEventListener("abort",l,{once:!0}));let d=setTimeout(()=>a.abort(),o);try{let c;try{c=await G(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(r),signal:a.signal},Y,m=>{this.telemetryHooks?.onRetry?.("account_snapshot",m),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:m})})}finally{clearTimeout(d),s?.signal?.removeEventListener("abort",l)}if(!c.ok)throw await S(c,"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(c){throw this.reportAccountSnapshotFailure(c,s?.telemetryMode??"blocking"),c}}async createSessionIntent(e,t,r,s){if(!t)throw new v("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let i=r,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),d=i.provider==="stripe"&&(i.paymentMethodCategory==="wallet"||i.paymentMethodCategory==="apm")&&(i.intentKind==="payment"||i.intentKind==="setup"),c=i.provider==="paypal"&&i.paymentMethodCategory==="wallet"&&i.paymentMethodId===null&&(i.paymentMethodType==="paypal"&&i.intentKind==="payment"||i.paymentMethodType===re&&(i.intentKind==="payment"||i.intentKind==="setup"));if(!l||!d&&!c)throw new v("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let m=i.authorizationAttemptId;if(m!==void 0&&!Ie(m))throw new v("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let u=Ie(m)?m:Pt();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,[Me]: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({...r,authorizationAttemptId:u}),signal:s?.signal});if(!f.ok){y=!0;let Q=await S(f,"Failed to create checkout intent"),st=x(Q,"PAYMENT_PROCESSING_FAILED");throw Ve(Q.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...st,stage:"processing",requestCategory:"intent_create"}),Q}let C=await f.json();if(f.status===202&&q(C)&&C.type==="checkout_processing")return y=!0,await this.settleProcessingSessionIntent(C,f,e,t,r);let T=C.data;if(!T||typeof T!="object")throw new v("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let p=T,ce=p.paymentMethodType,et=(p.paymentMethodCategory==="wallet"||p.paymentMethodCategory==="apm")&&typeof ce=="string"&&ce.trim().toLowerCase()!=="card"&&(typeof p.paymentMethodId=="string"||p.paymentMethodId===null)&&typeof p.providerObjectId=="string",tt=p.provider==="stripe"&&(p.intentKind==="payment"||p.intentKind==="setup")&&typeof p.clientSecret=="string",rt=p.provider==="paypal"&&p.paymentMethodCategory==="wallet"&&p.paymentMethodId===null&&(p.paymentMethodType==="paypal"&&p.intentKind==="payment"&&(p.providerObjectType==="order"||p.providerObjectType==="subscription")||p.paymentMethodType===re&&p.intentKind==="payment"&&p.providerObjectType==="order"||p.paymentMethodType===re&&p.intentKind==="setup"&&p.providerObjectType==="setup_token")&&p.clientSecret===null,nt=p.provider===r.provider&&p.paymentMethodCategory===r.paymentMethodCategory&&p.paymentMethodType===r.paymentMethodType&&p.paymentMethodId===r.paymentMethodId&&p.intentKind===r.intentKind;if(!et||!tt&&!rt||!nt)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:M(f.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-g),durationMode:"machine",requestCategory:"intent_create",statusClass:M(f.status)}),p}catch(f){throw y||this.reportDirectFailure(f,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),f}}async settleProcessingSessionIntent(e,t,r,s,i){let o=this.toCheckoutProcessingPending(e,t,r);try{return{settled:!0,response:await this.resolveCheckoutProcessing(o,r,{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}}closeThreeDsChallenge(e,t,r,s={}){if(!e||!t||!r||s.signal?.aborted)return Promise.resolve("failed");let i=this.requestThreeDsChallengeClose(e,t,r,s.signal),o=R.pendingThreeDsAbandonReports;return o.set(e,i),i.then(()=>{o.get(e)===i&&o.delete(e)}),i}async requestThreeDsChallengeClose(e,t,r,s){let i=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/3ds/abandoned`,o={method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify({providerIntentId:r})};try{let a=await Be(i,o,s);if(a!=="retry")return a;if(s?.aborted)return"failed";await $(tr,s);let l=await Be(i,o,s);return l==="retry"?"failed":l}catch{return"failed"}}async reportSessionIntentDecline(e,t,r,s){if(!t)throw new v("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let i=r,o=i.providerDeclineReason,a=i.paymentMethodType,l=i.providerIntentId,d=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),c=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&d,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(!c||!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,r,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(r),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 Dt(o?.data)}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let r=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 je(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()-r),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(It(e)){let i=e.account.email?.trim();if(i&&!De(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(),r=D(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,r.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{r.clear()}}async createAndFetchSessionRequest(e,t,r){let s=e.products??te(e.items,e.subscriptions);ke({captureMethod:e.captureMethod,products:s});let i=ne(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(d=>ie(d,i)),accountData:Ge(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(o.captureMethod=e.captureMethod),e.tokenizedData&&(o.tokenizedData=e.tokenizedData),$e(o,e);let a=await this.postCheckoutSessionCreate(o,e,t,r),l=!1;try{let d=await a.json();if(d.data&&"gateways"in d.data){this.autoCacheDisplayData(d.data.uuid,e);let u=this.mergeCachedDisplayData(d.data),g=this.normalizeRawSession(u);return d.vault&&g.data.session&&(g.data.session.vault=this.toVaultBlock(d.vault)),{...g,autoProcessingError:d.autoProcessingError,autoProcessingAttempted:d.autoProcessingAttempted,autoProcessingPending:d.autoProcessingPending}}let c=d.data?.uuid;if(!c)throw new v("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(c,e),this.adoptDirectTelemetryCheckout(c),l=!0,{...await this.getUnifiedCheckoutSession(c),autoProcessingError:d.autoProcessingError,autoProcessingAttempted:d.autoProcessingAttempted,autoProcessingPending:d.autoProcessingPending}}catch(d){throw l?d:L(d)}}async postCheckoutSessionCreate(e,t,r,s){let i={"Content-Type":"application/json",[U]:E},o=Ot(t.idempotencyKey);o&&(i[Me]=o),t.checkoutMode==="auto"&&(i[kt]=St);let a,l=!1,d=ir(t),c=(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{d?.onAttempt?.(u)}catch{}try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:i,body:JSON.stringify(e),signal:r})}catch(f){if(s.statusClass=r.aborted||f instanceof Error&&f.name==="AbortError"?"timeout":"network_error",r.aborted||f instanceof Error&&f.name==="AbortError"||u>=2)throw f;let C=u+1;m(C),await H(u,r);continue}let h=M(a.status);if(s.statusClass=h,a.status===204)throw c(u,g,h),new v("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(a.ok){c(u,g,h);break}let y=await S(a,"Failed to create checkout session");if(y.code===Mt&&u<2){m(u+1),await H(u,r);continue}throw c(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(),r=D(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??te(e.items,e.subscriptions);try{ke({captureMethod:e.captureMethod,products:i})}catch(C){throw r.clear(),this.reportSessionCreateFailure(C,t,s),C}let o=ne(e.currency,e.items,e.subscriptions,i);if(!o)throw r.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{He(e,o,i)}catch(C){throw r.clear(),this.reportSessionCreateFailure(C,t,s),C}let a,l,d=!1;try{let C=await this.postCheckoutSessionCreate(lr(e,o),e,r.signal,s);if(d=!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 r.clear(),d&&L(C),this.reportSessionCreateFailure(C,t,s),C}let c=a.data.session?.id??l.data.uuid??"",m=a.data.session?.clientSecret??l.data.nonce??"";if(!c||!m){r.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}r.clear(),this.adoptDirectTelemetryCheckout(c),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=D(e.timeoutMs??12e3),h=this.claimCheckoutSession(c,m,u?dr(e,o,i):He(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 De(T.account.email)?(y=h.then(()=>{let p=this.telemetryTimestamp();return this.claimCheckoutSession(c,m,cr(T.account),{params:T,startedAt:p,deadline:D(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:c,nonce:m,claimed:h,claim:f}}async claimCheckoutSession(e,t,r,s){let i=s?.startedAt??this.telemetryTimestamp(),o=this.telemetryTimestamp(),a=s?.deadline??D(12e3),l=JSON.stringify(r),d="unknown",c=0,m=!1;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let u;for(c=0;c<3;c++){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(d=f?"timeout":"network_error",f||c>=2)throw y;try{this.telemetryHooks?.onRetry?.("session_claim",c+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:c+1})}catch{}await H(c,a.signal);continue}if(d=M(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:d}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_claim",statusClass:d,attempt:c}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:d}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"session_create",statusClass:d,attempt:s?.createAttempt??c}),h}catch(u){throw m&&L(u),this.reportSessionCreateFailure(u,o,{attempt:c,statusClass:d},"session_claim"),u}finally{a.clear()}}reportSessionCreateFailure(e,t,r,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:r.attempt}),e instanceof v&&e.type==="validation_error"||e instanceof v&&Ve(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 r=this.telemetryTimestamp(),s=t?.paymentMethodCategory??"saved";this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:s});let i=t?.timeoutMs??K,o=Date.now()+i,a=new AbortController,l=!1,d,c=setTimeout(()=>{d=setTimeout(()=>{l=!0,a.abort()},qe)},i),m=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?m():t?.signal?.addEventListener("abort",m,{once:!0});let u=this.clampRetryAfterMs(t?.initialDelayMs??Ue),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(r,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 $(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(r,s,t?.challengeAttemptId),y;if(Date.now()>=o)throw b();u=this.clampRetryAfterMs(Math.max(u*2,Le))}}catch(h){let y=l&&se(h)?b():h;throw this.reportDirectFailure(y,"RECOVERY_FAILED","recovery","session_read",s),y}finally{clearTimeout(c),clearTimeout(d),t?.signal?.removeEventListener("abort",m)}}reportRecoveryCompleted(e,t,r){let s={stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t};if(this.directTelemetry?.log({name:"operation.recovery.completed",...s}),r)try{this.directTelemetry?.beginThreeDsChallenge({attemptId:r}).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,r,s,i){let o=t.latestTransactionAttempt;if(this.rememberReportedFailure(e,t),o?.result==="DECLINE"){let d=o.code===Fe;throw new v(d?Oe:"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 Vt("Payment could not be completed. Please try again.",o?.code??"payment_processing_error");let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,r,s)}catch(d){if(!i?.()||!se(d))throw d;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 r=t.timeoutMs??K,s=Date.now()+r,i=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let o=s-Date.now();if(o<=0||i>0&&(await $(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,d,c=t.signal?new Promise((T,p)=>{d=p}):null,m=()=>{l.abort(t.signal?.reason),d?.(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+qe)}),h;try{let T=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,l.signal);h=await Promise.race([T,g,c].filter(p=>p!==null))}finally{u!==void 0&&clearTimeout(u),t.signal?.removeEventListener("abort",m)}if(!h)return null;let y=xe(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,Le))}}isOwnFailedAttempt(e,t,r){let s=t.latestTransactionAttempt?.providerIntentId??null;return r!==void 0?s===r:s===null?!0:!Ht(t.uuid||e,s)}rememberReportedFailure(e,t){let r=t.latestTransactionAttempt;!xe(r)||!r.providerIntentId||jt(t.uuid||e,r.providerIntentId)}async fetchCheckoutStatus(e,t,r,s){let i=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,o=i;if(r)try{let c=new URL(r,`${this.baseUrl}/`),m=new URL(i);c.origin===m.origin&&(o=c.toString())}catch{}let a={[U]:E};t&&(a["x-checkout-session-token"]=t);let l=await G(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 d=await l.json();return q(d.data)&&"latestTransactionAttempt"in d.data?d.data:null}normalizeRawSession(e){let t=e.gateways??{},r=[],s={session:this.toCheckoutSession(e)},i=t.stripe;if(i?.publishableKey){r.push("stripe");let l=[e.stripeClientSecret,i.stripeClientSecret].find(d=>typeof d=="string"&&d.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(d=>typeof d=="string"):void 0}}let o=t.paypal;return o?.publishableKey&&(r.push("paypal"),s.paypal={publishableKey:o.publishableKey,environment:o.environment,providerObjectType:o.providerObjectType,approvalPresentation:o.approvalPresentation}),{providers:r,mode:"tokenize",...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},data:s,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],r=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),s=t.reduce((d,c)=>d+(c.overrideAmount??c.totalAmount??0),0),i=r?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(d=>d.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:Pe(e.outcome)??Pe(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}:{},...xt(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(Ut)}:{},buyerIdentified:e.buyerIdentified,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(d=>({...d,totalAmount:typeof d.totalAmount=="number"?d.totalAmount:void 0,overrideAmount:typeof d.overrideAmount=="number"?d.overrideAmount:null,currency:typeof d.currency=="string"?d.currency:void 0,metadata:d.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=Qt(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,r){if(e.status!==202)return e;let s=await e.json().catch(()=>null),i=this.toCheckoutProcessingPending(s,e,t);return this.resolveCheckoutProcessing(i,t,r)}async resolveCheckoutProcessing(e,t,r){let s=r?.pollTimeoutMs??K,i=Date.now()+s;if(e.statusUrl){let a=await this.waitForCheckoutStatus(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:s,nonce:r?.nonce,statusUrl:e.statusUrl,submittedIntentId:r?.submittedIntentId});if(a)return this.toProcessResponseFromStatus(a,t,r?.nonce)}let o=await this.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:i-Date.now(),nonce:r?.nonce,paymentMethodCategory:r?.paymentMethodCategory});return this.toProcessResponseFromSession(o,t)}async toProcessResponseFromStatus(e,t,r){let s=e.latestTransactionAttempt?.result,i={[qt]:Nt},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,r);return this.toProcessResponseFromSession(a,t)}if(this.rememberReportedFailure(t,e),s==="DECLINE"){let a=e.latestTransactionAttempt,l=a?.code===Fe,d=a?.declineReason??void 0;return new Response(JSON.stringify({type:d??"authorization_declined",message:l?Oe:"Payment was declined. Please choose another payment method.",code:a?.code??d??"authorization_declined",...d?{declineCode:d}:{}}),{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:Lt(e)??"Payment could not be completed. Please try again."}),{status:500,headers:o});throw b()}async reconcileProcessPayment(e,t){let r=t?.pollTimeoutMs??K,s=Date.now()+r,i=null;try{i=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:r,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 r=e.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:r.paymentId,sessionId:r.id||t,authorizationExpiresAt:r.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(e.data.session?.status==="expired"){let r=e.data.session.failureOutcome==="authorization_expired"||e.data.session.captureMethod==="manual";throw new v(r?"Authorization has expired.":"Checkout session has expired.","api_error",{code:r?"authorization_expired":"checkout_session_expired"})}throw b()}toCheckoutProcessingPending(e,t,r){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")??r,retryAfterMs:this.clampRetryAfterMs(Wt(e,"retryAfterMs")??o??Ue),statusUrl:k(e,"statusUrl"),sessionUrl:k(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,Gt))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??te(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let s=t.products!==void 0,i=ne(t.currency,s?void 0:t.items,s?void 0:t.subscriptions,r);Z(e,{currency:i??void 0,products:r.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=ue(e.uuid),r=new Map,s=o=>o?`code:${o}`:void 0;for(let o of t?.products??[]){let a=s(o.code);a&&r.set(a,o)}let i=(e.products??[]).map(o=>{let a=s(o.code),l=a?r.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}}};R.activeVaultCaptureRequests=new Map,R.pendingThreeDsAbandonReports=new Map;var N=R;function Xr(n,e){let t=N;return new t(n,e)}import{buildCardFieldLabelsPayload as mr,buildTelemetryErrorEvent as pr,buildTelemetryLogEvent as yr,buildTelemetryTerminalEvent as Qe,FloPayError as We,resolveBillingApiUrl as ae,SDK_VERSION as Je,THREE_DS_CHALLENGE_WINDOW_MS as gr}from"@flopay/shared";import{invokeMerchantCallback as ur,resolveCardFieldsTimeoutMs as hr}from"@flopay/shared";function Ye(n){if(!n)return null;try{let e=new URL(n,window.location.href);return e.origin==="null"?null:e.origin}catch{return null}}var W=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=hr(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,r=[];for(let i of Array.from(e.querySelectorAll("script[src], iframe[src]"))){let o=Ye(i.getAttribute("src"));if(o&&t.add(o),i.tagName==="SCRIPT"){let a=()=>this.fail("load_error");i.addEventListener("error",a),r.push(()=>i.removeEventListener("error",a))}}let s=i=>{let o=Ye(i.blockedURI);o&&t.has(o)&&this.fail("blocked")};document.addEventListener("securitypolicyviolation",s),r.push(()=>document.removeEventListener("securitypolicyviolation",s)),this.detach=()=>{for(let i of r)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))ur(()=>t(e))}};var fr=4,J="flopay-vault",vr=3e4,Cr=gr+vr,Tr="Card authentication timed out.",Xe={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 br(n){return n.class==="lifecycle"?n.name:n.class==="technical_error"?n.code:n.class==="expected_outcome"?n.outcome:"sdk.performance"}function P(n){let e={class:n.class,stage:n.stage};"code"in n&&(e.code=n.code),"provider"in n&&n.provider&&(e.provider=n.provider),"paymentMethodCategory"in n&&n.paymentMethodCategory&&(e.paymentMethodCategory=n.paymentMethodCategory),"outcome"in n&&(e.outcome=n.outcome),"durationMs"in n&&n.durationMs!==void 0&&(e.durationMs=n.durationMs),"durationMode"in n&&n.durationMode&&(e.durationMode=n.durationMode);try{globalThis.Sentry?.addBreadcrumb?.({category:"flopay.telemetry",level:n.class==="technical_error"?"error":"info",message:br(n),data:e})}catch{}}function V(n,e){return yr({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var _r=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function Rr(n){return typeof n=="string"&&_r.has(n)?n:"unknown"}var Sr=new Set(["verification_failed","verification_expired"]);function Ar(n){return n==null?!0:typeof n=="string"&&Sr.has(n)}var wr="vault_mount";function Er(n){return n.failureStage===wr}function le(n,e){return n&&!Er(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:Rr(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function Ze(n,e,t="checkout"){return t==="card_setup"?n.type==="decline"?"card_setup_declined":"card_setup_succeeded":n.type==="decline"?"payment_declined":n.outcome==="authorized"||e==="manual"?"payment_authorized":"payment_succeeded"}function kr(n,e,t,r="checkout"){let{type:s}=n;if(s==="complete"||s==="decline")return Qe({eventId:"22222222-2222-4222-8222-222222222222",outcome:Ze(n,t,r),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(s==="error"){let a=le(e,n);return pr({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[i,o]=Xe[s];return V(i,o)}function Mr(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===J&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function Ir(n){if(typeof n!="object"||n===null)return;let e=n;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 Dr(n){if(typeof n!="object"||n===null)return;let e=n,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 Pr(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===J&&e.type==="validation"&&Array.isArray(e.messages)}function Fr(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===J&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}function Or(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===J&&e.type==="fields_interactive"}function xr(n){let e=n.capabilities;return Array.isArray(e)&&e.includes("fields_interactive")}var Ur=["number","expiry","cvv","name"];function Lr(n){if(n===null||typeof n!="object")return;let e=n,t={};for(let r of Ur){let s=e[r];typeof s=="string"&&(t[r]=s)}return t}var de=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.actionChallengeIntentId=null;this.messageToken=null;this.expectedOrigin=null;this.theme=void 0;this.submitGateBlocked=!1;this.cardFieldOrder=null;this.cardAutoFocus=!0;this.cardBrandIcons=!1;this.showCardFieldLabels=void 0;this.cardFieldLabels=void 0;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 W({timeoutMs:e.cardFieldsTimeoutMs,now:()=>this.telemetryReporter?.now?.()??_(),report:r=>this.reportCardFields(r)}),this.ownsTelemetryReporter=!t&&e.telemetry!==!1,this.telemetryReporter=t?.reporter??(this.ownsTelemetryReporter?new w({billingApiUrl:ae(e.billingApiUrl),sdkVersion:Je}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new w({billingApiUrl:ae(this.config.billingApiUrl),sdkVersion:Je}));let r=this.telemetryReporter;if(this.config.operation==="card_setup"&&r&&this.setupTelemetryReporter!==r){this.setupTelemetryReporter=r;try{r.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 We("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 We("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.postCardFieldLabels(),this.postCardFieldPlaceholders(),this.postSubmitLabel(),P(V("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 r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.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",r=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}:{},...r?{checkoutSessionId:r}:{}})}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 r=Array.from(e.querySelectorAll("script"));for(let s of r){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 r=t.data;if(Fr(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(Pr(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let d=r.messages.filter(c=>typeof c=="string"&&c.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:d||void 0});return}if(Or(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let d=typeof r.sessionId=="string"?r.sessionId:void 0;if(this.config.sessionId&&d&&d!==this.config.sessionId)return;this.cardFields.ready();return}if(!Mr(r)||this.messageToken&&r.messageToken!==this.messageToken)return;let s=this.config.sessionId,i=typeof r.sessionId=="string"?r.sessionId:void 0;if(s&&i&&i!==s||(r.type==="complete"||r.type==="decline")&&s&&i!==s)return;let o=Dr(r.paymentMethod),a=Ir(r.vaultOutcome),l={...r.sessionId??this.config.sessionId?{sessionId:r.sessionId??this.config.sessionId}:{},...r.outcome?{outcome:r.outcome}:{},...r.paymentId?{paymentId:r.paymentId}:{},...r.authorizationExpiresAt?{authorizationExpiresAt:r.authorizationExpiresAt}:{},...r.failureOutcome?{failureOutcome:r.failureOutcome}:{},...r.intentId?{intentId:r.intentId}:{},...r.declineReason?{declineReason:r.declineReason}:{},...r.message?{message:r.message}:{},...a?{vaultOutcome:a}:{},...o?{paymentMethod:o}:{}};r.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??_()),this.isVerificationStateError(r)?(P(V("operation.state_transition","vault_mount")),this.telemetryReporter?.log({name:"operation.state_transition",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})):(P(kr(r,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(r),r.type==="error"&&le(this.submissionStarted,r).errorCode==="VAULT_LOAD_FAILED"&&this.cardFields.fail("load_error")),r.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postCardBrandIcons(),this.postCardFieldLabels(),this.postCardFieldPlaceholders(),this.postSubmitLabel(),xr(r)||this.cardFields.ready()),r.type==="action_required"&&r.nextActionRedirectUrl&&(this.showActionRequiredOverlay(r.nextActionRedirectUrl),this.actionOverlay&&typeof r.intentId=="string"&&r.intentId&&(this.actionChallengeIntentId=r.intentId)),(r.type==="complete"||r.type==="decline"||r.type==="error"||r.type==="submitting")&&(this.endActionChallengeFromWidget(r.type),this.hideActionRequiredOverlay()),r.type!=="action_required"&&this.emit(r.type,l)};this.messageHandler=e,window.addEventListener("message",e)}isVerificationStateError(e){return e.type==="error"&&this.verificationRequired&&!this.submissionStarted&&Ar(e.failureOutcome)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;let{type:r}=e;if(r==="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"})),r==="complete"||r==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:Ze(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="error"){let o=le(this.submissionStarted,e);t.log({name:"vault.terminal",stage:o.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...o,provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="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]=Xe[r];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()}setShowCardFieldLabels(e){this.showCardFieldLabels=e===!0,this.postCardFieldLabels()}setCardFieldLabels(e){this.cardFieldLabels=mr(e),this.postCardFieldLabels()}postCardFieldLabels(){let e=this.showCardFieldLabels,t=this.cardFieldLabels;if(e===void 0&&t===void 0)return;let r=this.config.sessionId,{messageToken:s,expectedOrigin:i}=this;!r||!s||!i||this.postToHostedWindow({source:"flopay-vault-host",type:"cardFieldLabels",sessionId:r,messageToken:s,...e===void 0?{}:{show:e},...t===void 0?{}:{labels:{...t}}},i)}setCardFieldPlaceholders(e){let t=Lr(e),r=t===void 0&&this.cardFieldPlaceholders!==void 0;this.cardFieldPlaceholders=t,this.postCardFieldPlaceholders(r?{}:t)}postCardFieldPlaceholders(e=this.cardFieldPlaceholders){let t=this.config.sessionId,{messageToken:r,expectedOrigin:s}=this;e===void 0||!t||!r||!s||this.postToHostedWindow({source:"flopay-vault-host",type:"cardFieldPlaceholders",sessionId:t,messageToken:r,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:r,expectedOrigin:s}=this;e===void 0||!t||!r||!s||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:t,messageToken:r,label:e},s)}hostedWindow(){return this.container?.querySelector("iframe")?.contentWindow??null}postToHostedWindow(e,t){let r=this.hostedWindow();if(r)try{r.postMessage(e,t)}catch{}}directiveTargetOrigin(){return this.expectedOrigin??"*"}emit(e,t){for(let r of this.listeners.get(e)??[])r(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=ve(this.beginActionChallengeAttempt()),r=be(e),s=!1,i=h=>{if(s)return;let y=Te(h,r);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"),ee(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 d=document.createElement("iframe");d.setAttribute("title","Card authentication"),d.setAttribute("allow","payment"),d.tabIndex=0,d.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(";"),d.addEventListener("load",()=>{a.loaded||(a.loaded=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"}))}),d.src=e,l.appendChild(d);let c=document.createElement("button");c.type="button",c.setAttribute("aria-label","Close card authentication"),c.textContent="\xD7",c.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(";"),c.addEventListener("click",()=>this.abandonActionRequiredOverlay()),l.appendChild(c),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!==d.contentWindow){f&&m<fr&&(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"}),P(V("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=Ce(l);g&&t.record("container_visibility",{reason:g,evidenceBasis:"parent_computed_style"}),this.actionOverlay=l,d.focus(),this.armActionRequiredTimeout(),P(V("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},Cr)}reportChallengeAbandoned(){P(Qe({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.closeAbandonedChallenge(),this.hideActionRequiredOverlay(),this.emit("error",{...this.config.sessionId?{sessionId:this.config.sessionId}:{},message:Tr})}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.closeAbandonedChallenge(),this.hideActionRequiredOverlay(),this.emit("challenge_dismissed",{...this.config.sessionId?{sessionId:this.config.sessionId}:{}})}}closeAbandonedChallenge(){let e=this.actionChallengeIntentId;this.actionChallengeIntentId=null;let{sessionId:t,sessionToken:r}=this.config;if(!(!e||!t||!r))try{new N(ae(this.config.billingApiUrl),{telemetry:!1}).closeThreeDsChallenge(t,r,e).catch(()=>{})}catch{}}beginActionChallengeAttempt(){try{return this.telemetryReporter?.beginThreeDsChallenge?.()}catch{return}}endActionChallengeFromWidget(e){let t=this.actionChallenge,r=t?.telemetry??this.lastChallengeTelemetry;if(this.lastChallengeTelemetry=null,!!r){if(e==="submitting"){if(!t)return;r.record("abort_observed",{reason:"unspecified",evidenceBasis:"signal_reason"}),r.terminal("abort",{reason:"unspecified",evidenceBasis:"signal_reason"});return}t&&r.terminal("status_poll",{evidenceBasis:"server_status"}),e==="complete"&&r.reconcile("succeeded"),e==="decline"&&r.reconcile("declined")}}hideActionRequiredOverlay(){if(this.actionChallengeIntentId=null,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 r=Math.max(0,Math.min(Math.ceil(e),2e3));t.style.height=`${r}px`}};function ln(n,e){let t=de;return new t(n,{reporter:e})}export{me as a,pe as b,D as c,H as d,Z as e,ue as f,he as g,ve as h,ee as i,zr as j,Ce as k,Te as l,be as m,_ as n,w as o,sr as p,N as q,Xr as r,de as s,ln as t};