@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/README.md +4 -2
- package/dist/card-setup.cjs +1 -1
- package/dist/card-setup.mjs +1 -1
- package/dist/checkout-runtime/contract.d.ts +54 -0
- package/dist/checkout-runtime/index.d.ts +6 -0
- package/dist/checkout-runtime-loader.d.ts +17 -0
- package/dist/chunk-5OENCIZW.mjs +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.mjs +1 -1
- package/dist/payment-api.d.ts +14 -0
- package/package.json +2 -2
- package/dist/chunk-AKNIWZAJ.mjs +0 -1
package/README.md
CHANGED
|
@@ -97,6 +97,8 @@ Nothing may be charged before `claimed` settles: the billing API rejects process
|
|
|
97
97
|
|
|
98
98
|
For detached creation, `timeoutMs` is a fresh per-phase budget: the shell POST gets the full value, and after it succeeds the initial claim PATCH gets the full value again under a different `AbortSignal` (12 seconds each by default), so time spent creating a usable shell never starves its catalog claim. Detached creation requires billing API v1.7.12 or newer and `checkoutMode: 'full'`, and is skipped when `tokenizedData` is supplied. There is no fallback to the one-shot create; pass `deferDataAttachment: false` to force it. Because catalog validation moves to the claim, an invalid product or coupon surfaces as the same `422`, later in the flow. The claim body is fingerprinted by the billing API, so the SDK replays a byte-identical payload across retries, and a materially different claim for an already-claimed session returns `409` without retrying.
|
|
99
99
|
|
|
100
|
+
**Stripe account routing.** The shell also carries the cart's distinct catalogue product codes as `routingProducts: [{ code }]`, one entry per code, resolved the way the claim's lines resolve them. It is a routing hint only: the billing API uses it to advertise the cart's Stripe account on the first response, never stores it, and still treats the claim as the authority. An empty cart, a cart without product codes, and a one-shot create send no `routingProducts` key, so their request is unchanged. When the claim nevertheless changes the advertised Stripe account, the billing API hides Apple Pay and Google Pay from the claimed session unless the client declared `stripe-account-switch-v1`. `new PaymentAPI(billingApiUrl, { stripeAccountSwitch: true })` adds that token in `x-flo-sdk-capabilities` to the shell POST and to every claim. Set it only when your integration loads Stripe.js for the claimed account and re-mounts its wallet buttons there, as `@flopay/react`'s `FloPayCheckout` does; the default `PaymentAPI` never declares it.
|
|
101
|
+
|
|
100
102
|
### Server-side card gateways (Worldpay)
|
|
101
103
|
|
|
102
104
|
The billing API can process hosted-vault and eligible saved cards through an approved Worldpay Corporate Gateway entirely server-side. Whether a session can use it is the billing API's decision, made from the merchant's active gateways and the saved method's eligibility. `PaymentAPI` sends no gateway hint, provider selection, eligibility assertion, merchant code, or scheme reference. Everything stays provider-neutral, so existing integrations change nothing:
|
|
@@ -107,7 +109,7 @@ The billing API can process hosted-vault and eligible saved cards through an app
|
|
|
107
109
|
- Eligible saved-card Auto, Confirm, returning-buyer, and subscription checkouts call the same provider-neutral `/process` route without `tokenizedData`. Immediate success and authorization use the existing Flo shapes; a `202 checkout_processing` response is reconciled through its nonce-protected status URL, including decline, buyer action, and terminal error states.
|
|
108
110
|
- When a saved method cannot be used, `stored_payment_method_unsupported` is preserved as an actionable Flo error with the instruction to choose another payment method. The SDK never silently switches to a different charging behavior. Scheduled subscription rebills, retries, dunning, and stored-credential eligibility remain billing-API responsibilities.
|
|
109
111
|
|
|
110
|
-
`PaymentAPI` Auto creates advertise only the generic `async-auto-checkout-v1` response capability so the billing API may return the asynchronous status envelope. It is not a Worldpay capability or routing request; Confirm and Full creates send no capability header. Do not add gateway selection or provider-specific branches to a create request, whether through this SDK or a request you build yourself: the billing API owns that decision.
|
|
112
|
+
`PaymentAPI` Auto creates advertise only the generic `async-auto-checkout-v1` response capability so the billing API may return the asynchronous status envelope. It is not a Worldpay capability or routing request; Confirm and Full creates send no capability header unless the `PaymentAPI` opted into the Stripe account switch (below). Do not add gateway selection or provider-specific branches to a create request, whether through this SDK or a request you build yourself: the billing API owns that decision.
|
|
111
113
|
|
|
112
114
|
### Hosted card capture
|
|
113
115
|
|
|
@@ -362,7 +364,7 @@ await api.reportSessionIntentDecline('session_uuid', 'session_nonce', {
|
|
|
362
364
|
|--------|-------------|
|
|
363
365
|
| `loadFloPay(publishableKey, options?)` | Initializes the SDK and resolves a `FloPay`. Shares successful and in-flight work by key and options; failed work stays retryable. |
|
|
364
366
|
| `FloPay` | Main SDK class, created by `loadFloPay()` |
|
|
365
|
-
| `PaymentAPI` | Billing API client: `new PaymentAPI(billingApiUrl, { telemetry })` |
|
|
367
|
+
| `PaymentAPI` | Billing API client: `new PaymentAPI(billingApiUrl, { telemetry, stripeAccountSwitch })`; `stripeAccountSwitch` (default `false`) declares `stripe-account-switch-v1` on detached creates and claims |
|
|
366
368
|
| `createCheckoutSession(options)` | Creates a checkout session and redirects. Resolves a `CheckoutSessionResult`. |
|
|
367
369
|
| `createCheckoutSessionWithRetries(options)` | Like `createCheckoutSession`, with up to two retries (three attempts) inside one total deadline, using jittered exponential backoff |
|
|
368
370
|
| `PciVaultCardCapture` | `CardCaptureAdapter` implementation that injects the billing API's hosted card form |
|
package/dist/card-setup.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Q=Object.defineProperty;var Be=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var He=Object.prototype.hasOwnProperty;var je=(n,e)=>{for(var t in e)Q(n,t,{get:e[t],enumerable:!0})},Ke=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ze(e))!He.call(n,s)&&s!==t&&Q(n,s,{get:()=>e[s],enumerable:!(r=Be(e,s))||r.enumerable});return n};var Ge=n=>Ke(Q({},"__esModule",{value:!0}),n);var or={};je(or,{PaymentAPI:()=>D,PciVaultCardCapture:()=>Y,clearSetupRedirectParams:()=>xe,readSetupRedirectReturn:()=>Oe});module.exports=Ge(or);var l=require("@flopay/shared");function ie(n){return typeof n=="string"&&n.trim()?n:void 0}function oe(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 P(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 $e(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function q(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",d),d=()=>{o!==void 0&&clearTimeout(o),a(),i($e())};if(e.aborted){d();return}o=setTimeout(()=>{a(),s()},r),e.addEventListener("abort",d,{once:!0})})}var Ye="flopay_session_display:";var N=new Map;function V(n){return`${Ye}${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(V(n),JSON.stringify(s));return}catch{}N.set(n,s)}function ae(n){if(!n)return null;let e=X();if(e)try{let r=e.getItem(V(n));if(r){let s=JSON.parse(r);if(s&&typeof s.expiresAt=="number"&&s.expiresAt>Date.now())return s.data;e.removeItem(V(n))}}catch{}let t=N.get(n);if(t){if(t.expiresAt>Date.now())return t.data;N.delete(n)}return null}function le(n){if(!n)return;N.delete(n);let e=X();if(e)try{e.removeItem(V(n))}catch{}}var b=require("@flopay/shared");var ee=require("@flopay/shared"),We=32,de=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function Je(){let n=globalThis,e=n[de];if(e instanceof Map)return e;let t=new Map;try{Object.defineProperty(n,de,{configurable:!0,enumerable:!1,writable:!1,value:t})}catch{}return t}function Qe(n,e){let t=Je(),r=t.get(n);if(r)return r;for(;t.size>=We;){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 Xe=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),Ze=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function ce(n,e={}){let t=(0,ee.isThreeDsChallengeAttemptId)(e.attemptId)?e.attemptId.toLowerCase():n.newAttemptId(),r=()=>{try{let a=n.now();return Number.isFinite(a)?a:0}catch{return 0}},s=Qe(t,r());(e.provider==="stripe"||e.provider==="worldpay")&&(s.provider=e.provider);let i=s.provider,o=(a,d)=>{if(s.terminated&&!Ze.has(a))return;let c={attemptId:t,phase:a,attemptSequence:s.nextSequence,elapsedMs:Math.max(0,r()-s.startedAt),provider:i};s.nextSequence+=1,d.reason!==void 0&&(c.reason=d.reason),d.evidenceBasis!==void 0&&(c.evidenceBasis=d.evidenceBasis),d.terminalSource!==void 0&&(c.terminalSource=d.terminalSource),d.providerOutcome!==void 0&&(c.providerOutcome=d.providerOutcome);try{n.emit(c,Xe.has(a))}catch{}};return{attemptId:t,record(a,d={}){a==="browser_terminal"||a==="provider_reconciled"||o(a,{reason:d.reason,evidenceBasis:d.evidenceBasis})},terminal(a,d={}){s.terminated||(o("browser_terminal",{terminalSource:a,reason:d.reason,evidenceBasis:d.evidenceBasis}),s.terminated=!0)},reconcile(a){s.reconciled.has(a)||(s.reconciled.add(a),o("provider_reconciled",{providerOutcome:a,evidenceBasis:"provider_fact"}))}}}function ue(n){let e=null;try{e=(0,ee.isThreeDsChallengeAttemptId)(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 te(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 he(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 me(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 pe(n){try{return te(n)==="valid"?new URL(n).origin:null}catch{return null}}var et="/v1/sdk-telemetry/events",B=16,ye=64,tt=1500,ge=1e3,rt=64,nt="00000000-0000-4000-8000-000000000000",st={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},it=48;function E(){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 ot(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function at(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 S(){return globalThis.performance?.now()??0}var k=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(/\/+$/,"")}${et}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=E(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??S,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((0,b.buildTelemetryLogEvent)({...this.checkoutContext,...e,eventId:E(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=(0,b.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:nt,sequence:0}),r=at(t),s=this.now();this.pruneReportedFailures(s);let i=this.reportedFailures.get(r);if(i!==void 0&&s>=i&&s-i<ge){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((0,b.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:E(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,b.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:E(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,b.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:E(),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 ce({now:()=>this.now(),newAttemptId:E,emit:(t,r)=>this.recordThreeDsChallenge(t,r)},e)}recordThreeDsChallenge(e,t){if(!this.canCollect()||this.threeDsChallengeCount>=it)return;let r=(0,b.buildTelemetryLogEvent)({...this.checkoutContext,...e,name:"three_ds.challenge",stage:"three_ds_handoff",eventId:E(),sequence:this.sequence++});if(!(this.queue.length>=ye)){if(this.threeDsChallengeCount+=1,this.queue.push(r),t){this.drainQueue();return}if(this.queue.length>=B){this.flush();return}this.scheduleFlush()}}now(){try{return this.clock()}catch{return S()}}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>=ge)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=rt;){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>=ye||this.eventCounts[e.class]>=st[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=B){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,B);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,B);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=(0,b.serializeTelemetryBatch)(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:E()});if(ot(t)>b.TELEMETRY_MAX_BATCH_BYTES)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 d=>{if(d.status!==202)return null;let c=null;try{c=await d.json()}catch{}return c?.status==="disabled"?"disabled":null}).catch(()=>null),o=new Promise(d=>{s=setTimeout(()=>{r?.abort(),d(null)},tt)});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)}},fe=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),ve=globalThis;ve[fe]===void 0&&Object.defineProperty(ve,fe,{configurable:!0,enumerable:!1,writable:!1,value:n=>new k(n)});function lt(n){return n==="on_session"||n==="off_session"}function dt(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function ct(n){let e=n.vaultOutcome;if(!(!e||e.code!==l.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED))return typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0}var ut="x-flopay-process-result-source",ht="status",ke=new WeakSet;function mt(n,e){let t=new l.FloPayError(n,"api_error",{code:e,statusCode:500});return ke.add(t),t}function pt(n){return typeof n=="object"&&n!==null&&ke.has(n)}function Ce(n){return n?.result==="DECLINE"||n?.result==="ERROR"}var yt=50,I=new Map;function gt(n,e){return I.get(n)?.has(e)===!0}function ft(n,e){let t=I.get(n)??new Set;if(t.add(e),I.delete(n),I.set(n,t),I.size>yt){let r=I.keys().next().value;r!==void 0&&I.delete(r)}}function vt(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 Te=0,be=500,z=15e3,_e=15e3,Ct=3e3,Tt=1e4,bt=1e4;function U(n){return typeof n=="object"&&n!==null}function M(n,e){return ie(n?.[e])}function Re(n,e){return oe(n?.[e])}function _t(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function j(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 re(n){return n instanceof Error&&n.name==="AbortError"}function R(){return new l.FloPayError(l.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}async function w(n,e){let t=await n.json().catch(()=>null),r=U(t?.error)?t.error:null,s=Re(t,"message")??Re(r,"message")??e,i=M(t,"code")??M(t,"gatewayErrorCode")??M(r,"code")??`http_${n.status}`;return(0,l.withTelemetryHttpDiagnostics)(new l.FloPayError(s,"api_error",{code:i,statusCode:n.status}),n)}async function Rt(n){if(n.status!==403)return!1;let e=await n.clone().json().catch(()=>null),t=U(e?.error)?e.error:null;return(M(e,"code")??M(t,"code"))==="verification_required"}function St(n){if(!(!U(n)||typeof n.required!="boolean"))return{required:n.required,provider:"turnstile"}}async function At(n){let e=n.status===400?await n.clone().json().catch(()=>null):null;return(0,l.classifyPaymentRejection)(n.status,e)}function Se(n){return n===400||n===422}var K=2;async function H(n,e,t=K,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 j(150*2**o,e?.signal??void 0)}}var wt=2e3,Et=1e4,kt=150;async function Mt(n){try{let t=(await n.json())?.data?.status;return t==="closed"||t==="not_open"?t:"failed"}catch{return"failed"}}async function Ae(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")},Et)});try{let a=await Promise.race([fetch(n,{...e,signal:r.signal}),o]);return a==="timeout"?"failed":a.status>=500?"retry":a.ok?await Mt(a):"failed"}catch{return r.signal.aborted?"failed":"retry"}finally{clearTimeout(i),t?.removeEventListener("abort",s)}}function It(n,e){return new Promise(t=>{let r=setTimeout(t,e);n.then(()=>{clearTimeout(r),t()},()=>{clearTimeout(r),t()})})}var Pt=Symbol.for("@flopay/js.session-create.telemetry.v1");function Dt(n){return n[Pt]}function Ft(n){return"now"in n||"onFirstByte"in n||"onSessionCreateFailure"in n||"onRetry"in n}function Me(n){let e=(0,l.isCardHolderNamePlaceholder)(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 Ie(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 we(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function Ot(n){let e={};if(n.country&&(e.country=n.country),!(0,l.isCardHolderNamePlaceholder)(n.firstName,n.lastName)){let t=we(n.firstName),r=we(n.lastName);t&&(e.firstName=t),r&&(e.lastName=r)}return Object.keys(e).length>0?e:void 0}function xt(n,e){let t={clientId:n.clientId,checkoutVersion:l.SDK_VERSION,successUrl:n.successUrl,cancelUrl:n.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};n.captureMethod==="manual"&&(t.captureMethod=n.captureMethod);let r=Ot(n.account);return r&&(t.accountData=r),Ie(t,n),t}function Ee(n,e,t){return{currency:e,products:t.map(r=>(0,l.buildProductPayload)(r,e)),couponCodes:n.couponCodes??[],accountData:Me(n.account)}}function Ut(n,e,t){return{currency:e,products:t.map(r=>(0,l.buildProductPayload)(r,e)),couponCodes:n.couponCodes??[]}}function Lt(n){let e={},t=(0,l.isCardHolderNamePlaceholder)(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 A=class A{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=Ft(t);this.telemetryHooks=r?t:void 0,this.directTelemetry=r||t.telemetry===!1?void 0:new k({billingApiUrl:this.baseUrl,sdkVersion:l.SDK_VERSION})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,s,i="unknown"){let o=(0,l.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...o,...pt(e)?{reason:"capture_failed"}:{},stage:r,requestCategory:s,paymentMethodCategory:i})}reportAccountSnapshotFailure(e,t){let r=(0,l.classifyTelemetryFailure)(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()??S()}catch{return S()}}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 d={[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION};t&&(d["x-checkout-session-token"]=t);let c=!1;try{let u=await H(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:d,signal:s},K,m=>{this.telemetryHooks?.onRetry?.("session_read",m),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:m})},m=>{a=m,o=this.telemetryTimestamp()});c=!0;let p=Math.max(0,this.telemetryTimestamp()-o);try{this.telemetryHooks?.onFirstByte?.(p,a)}catch{}let h=`${Math.floor(u.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:h,attempt:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:p,durationMode:"machine",requestCategory:"session_read",statusClass:h,attempt:a}),!u.ok)throw await w(u,"Failed to get checkout session");let f=await u.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:h}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"session_read",statusClass:h}),{...f,data:this.mergeCachedDisplayData(f.data)}}catch(u){throw c&&(0,l.markSessionResponseReceived)(u),r&&this.directTelemetry?.error({...(0,l.classifyTelemetryFailure)(u,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),u}}cacheSessionDisplayData(e,t,r){Z(e,t,r)}clearSessionDisplayData(e){le(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,s=A.activeVaultCaptureRequests.get(r);if(s!==void 0)return s;let i=A.pendingThreeDsAbandonReports.get(e),o=i===void 0?this.requestVaultCapture(e,t):It(i,wt).then(()=>this.requestVaultCapture(e,t));A.activeVaultCaptureRequests.set(r,o);try{return await o}finally{A.activeVaultCaptureRequests.get(r)===o&&A.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),bt);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 H(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:o,signal:r.signal},K,c=>{this.telemetryHooks?.onRetry?.("vault_capture",c),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:c})});if(await Rt(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 w(a,"Failed to load the secure card form");let d=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(d)}catch(a){let d=r.signal.aborted?new l.FloPayError("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(d,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),d}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(0,l.markSessionResponseReceived)(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 l.FloPayError("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,...d}=t,c=vt(t.tokenizedData),u,p;try{u=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(d)}),p=u}catch(h){if(re(h))throw this.reportDirectFailure(h,"PAYMENT_PROCESSING_FAILED","processing","process_payment",s),h;u=await this.reconcileProcessPayment(t.sessionId,{...r,nonce:o,paymentMethodCategory:s,submittedIntentId:c})}if(!u.ok&&u.status!==202){let h=await At(u);return h?this.directTelemetry?.terminal({outcome:h,stage:"processing",requestCategory:"process_payment",statusClass:"4xx",paymentMethodCategory:s}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:(0,l.telemetryStatusClass)(u.status),failureCategory:u.status>=500?"server_error":void 0,paymentMethodCategory:s,...(0,l.readTelemetryHttpDiagnostics)(p)}),u}try{let h=await this.resolveProcessResponse(u,t.sessionId,{...r,nonce:o,paymentMethodCategory:s,submittedIntentId:c});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,l.telemetryStatusClass)(h.status),paymentMethodCategory:s}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,l.telemetryStatusClass)(h.status),paymentMethodCategory:s}),h}catch(h){throw h instanceof l.FloPayError&&h.code==="checkout_processing_timeout"||this.reportDirectFailure(h,"PAYMENT_PROCESSING_FAILED","processing","process_payment",s),h}}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??Tt,a=new AbortController,d=()=>a.abort();s?.signal&&(s.signal.aborted?a.abort():s.signal.addEventListener("abort",d,{once:!0}));let c=setTimeout(()=>a.abort(),o);try{let u;try{u=await H(`${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},K,p=>{this.telemetryHooks?.onRetry?.("account_snapshot",p),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:p})})}finally{clearTimeout(c),s?.signal?.removeEventListener("abort",d)}if(!u.ok)throw await w(u,"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(u){throw this.reportAccountSnapshotFailure(u,s?.telemetryMode??"blocking"),u}}async createSessionIntent(e,t,r,s){if(!t)throw new l.FloPayError("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",d=typeof o=="string"&&o.length>0&&!a&&(typeof i.paymentMethodId=="string"||i.paymentMethodId===null),c=i.provider==="stripe"&&(i.paymentMethodCategory==="wallet"||i.paymentMethodCategory==="apm")&&(i.intentKind==="payment"||i.intentKind==="setup"),u=i.provider==="paypal"&&i.paymentMethodCategory==="wallet"&&i.paymentMethodId===null&&(i.paymentMethodType==="paypal"&&i.intentKind==="payment"||i.paymentMethodType===l.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&(i.intentKind==="payment"||i.intentKind==="setup"));if(!d||!c&&!u)throw new l.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let p=i.authorizationAttemptId;if(p!==void 0&&!(0,l.isUuidV4)(p))throw new l.FloPayError("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let h=(0,l.isUuidV4)(p)?p:(0,l.randomUuidV4)();this.beginDirectTelemetryCheckout(e);let f=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let m={"Content-Type":"application/json","x-checkout-session-token":t,[l.IDEMPOTENCY_KEY_HEADER]:s?.idempotencyKey||h},g=!1;try{let v=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:m,body:JSON.stringify({...r,authorizationAttemptId:h}),signal:s?.signal});if(!v.ok){g=!0;let J=await w(v,"Failed to create checkout intent"),Ve=(0,l.classifyTelemetryFailure)(J,"PAYMENT_PROCESSING_FAILED");throw Se(J.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...Ve,stage:"processing",requestCategory:"intent_create"}),J}let C=await v.json();if(v.status===202&&U(C)&&C.type==="checkout_processing")return g=!0,await this.settleProcessingSessionIntent(C,v,e,t,r);let _=C.data;if(!_||typeof _!="object")throw new l.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let y=_,se=y.paymentMethodType,Ue=(y.paymentMethodCategory==="wallet"||y.paymentMethodCategory==="apm")&&typeof se=="string"&&se.trim().toLowerCase()!=="card"&&(typeof y.paymentMethodId=="string"||y.paymentMethodId===null)&&typeof y.providerObjectId=="string",Le=y.provider==="stripe"&&(y.intentKind==="payment"||y.intentKind==="setup")&&typeof y.clientSecret=="string",qe=y.provider==="paypal"&&y.paymentMethodCategory==="wallet"&&y.paymentMethodId===null&&(y.paymentMethodType==="paypal"&&y.intentKind==="payment"&&(y.providerObjectType==="order"||y.providerObjectType==="subscription")||y.paymentMethodType===l.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&y.intentKind==="payment"&&y.providerObjectType==="order"||y.paymentMethodType===l.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&y.intentKind==="setup"&&y.providerObjectType==="setup_token")&&y.clientSecret===null,Ne=y.provider===r.provider&&y.paymentMethodCategory===r.paymentMethodCategory&&y.paymentMethodType===r.paymentMethodType&&y.paymentMethodId===r.paymentMethodId&&y.intentKind===r.intentKind;if(!Ue||!Le&&!qe||!Ne)throw new l.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:(0,l.telemetryStatusClass)(v.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,l.telemetryStatusClass)(v.status)}),y}catch(v){throw g||this.reportDirectFailure(v,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),v}}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 l.FloPayError&&a.code==="checkout_processing_timeout"?new l.FloPayError(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=A.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 Ae(i,o,s);if(a!=="retry")return a;if(s?.aborted)return"failed";await j(kt,s);let d=await Ae(i,o,s);return d==="retry"?"failed":d}catch{return"failed"}}async reportSessionIntentDecline(e,t,r,s){if(!t)throw new l.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let i=r,o=i.providerDeclineReason,a=i.paymentMethodType,d=i.providerIntentId,c=typeof o=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(o)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(o),u=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&c,p=i.provider==="stripe"&&(i.paymentMethodCategory==="wallet"||i.paymentMethodCategory==="apm")&&(d===void 0||typeof d=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(d)),h=i.provider==="paypal"&&i.paymentMethodCategory==="wallet"&&i.paymentMethodType==="paypal"&&d===void 0;if(!u||!p&&!h)throw new l.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let f=h?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:o}:{provider:"stripe",paymentMethodCategory:i.paymentMethodCategory,paymentMethodType:i.paymentMethodType,providerDeclineReason:o,...typeof d=="string"?{providerIntentId:d}:{}},m=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(f),signal:s?.signal});if(!m.ok)throw await w(m,"Failed to report checkout decline")}async resolvePaymentMethodLayout(e,t,r,s){if(!t)throw new l.FloPayError("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,[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION},body:JSON.stringify(r),signal:s?.signal});if(i.status===404||i.status===405)return null;if(!i.ok)throw await w(i,"Failed to resolve the payment method layout");let o=await i.json();return(0,l.normalizePaymentMethodLayout)(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(0,l.withTelemetryHttpDiagnostics)(new l.FloPayError("Failed to fetch payments","api_error",{statusCode:a.status}),a);let d=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"}),d}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if((0,l.isDetachedSessionEligible)(e)){let i=e.account.email?.trim();if(i&&!(0,l.isValidEmail)(i))throw new l.FloPayError("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=P(e.timeoutMs??12e3),s={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let i=await this.createAndFetchSessionRequest(e,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??(0,l.foldIntoProducts)(e.items,e.subscriptions);(0,l.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:s});let i=(0,l.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,s);if(!i)throw new l.FloPayError("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:l.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:i,checkoutMode:e.checkoutMode??"full",products:s.map(c=>(0,l.buildProductPayload)(c,i)),accountData:Me(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(o.captureMethod=e.captureMethod),e.tokenizedData&&(o.tokenizedData=e.tokenizedData),Ie(o,e);let a=await this.postCheckoutSessionCreate(o,e,t,r),d=!1;try{let c=await a.json();if(c.data&&"gateways"in c.data){this.autoCacheDisplayData(c.data.uuid,e);let h=this.mergeCachedDisplayData(c.data),f=this.normalizeRawSession(h);return c.vault&&f.data.session&&(f.data.session.vault=this.toVaultBlock(c.vault)),{...f,autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}let u=c.data?.uuid;if(!u)throw new l.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(u,e),this.adoptDirectTelemetryCheckout(u),d=!0,{...await this.getUnifiedCheckoutSession(u),autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}catch(c){throw d?c:(0,l.markSessionResponseReceived)(c)}}async postCheckoutSessionCreate(e,t,r,s){let i={"Content-Type":"application/json",[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION},o=(0,l.resolveIdempotencyKey)(t.idempotencyKey);o&&(i[l.IDEMPOTENCY_KEY_HEADER]=o),t.checkoutMode==="auto"&&(i[l.FLO_SDK_CAPABILITIES_HEADER]=l.ASYNC_AUTO_CHECKOUT_CAPABILITY);let a,d=!1,c=Dt(t),u=(h,f,m)=>{d||(d=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:m,attempt:h}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-f),durationMode:"machine",requestCategory:"session_create",statusClass:m,attempt:h}))},p=h=>{try{this.telemetryHooks?.onRetry?.("session_create",h),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:h})}catch{}};for(let h=0;h<3;h++){s.attempt=h;let f=this.telemetryTimestamp();try{c?.onAttempt?.(h)}catch{}try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:i,body:JSON.stringify(e),signal:r})}catch(v){if(s.statusClass=r.aborted||v instanceof Error&&v.name==="AbortError"?"timeout":"network_error",r.aborted||v instanceof Error&&v.name==="AbortError"||h>=2)throw v;let C=h+1;p(C),await q(h,r);continue}let m=(0,l.telemetryStatusClass)(a.status);if(s.statusClass=m,a.status===204)throw u(h,f,m),new l.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(a.ok){u(h,f,m);break}let g=await w(a,"Failed to create checkout session");if(g.code===l.IDEMPOTENCY_IN_PROGRESS_CODE&&h<2){p(h+1),await q(h,r);continue}throw u(h,f,m),g}if(!a)throw new TypeError("Checkout-session creation exhausted its retry budget.");return a}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=P(e.timeoutMs??12e3),s={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let i=e.products??(0,l.foldIntoProducts)(e.items,e.subscriptions);try{(0,l.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:i})}catch(C){throw r.clear(),this.reportSessionCreateFailure(C,t,s),C}let o=(0,l.resolveSessionCurrency)(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 l.FloPayError("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{Ee(e,o,i)}catch(C){throw r.clear(),this.reportSessionCreateFailure(C,t,s),C}let a,d,c=!1;try{let C=await this.postCheckoutSessionCreate(xt(e,o),e,r.signal,s);if(c=!0,d=await C.json(),!d.data||!("gateways"in d.data))throw new l.FloPayError("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(d.data)),d.vault&&a.data.session&&(a.data.session.vault=this.toVaultBlock(d.vault))}catch(C){throw r.clear(),c&&(0,l.markSessionResponseReceived)(C),this.reportSessionCreateFailure(C,t,s),C}let u=a.data.session?.id??d.data.uuid??"",p=a.data.session?.clientSecret??d.data.nonce??"";if(!u||!p){r.clear();let C=new l.FloPayError("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(u),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 h=!e.account.email?.trim(),f=P(e.timeoutMs??12e3),m=this.claimCheckoutSession(u,p,h?Ut(e,o,i):Ee(e,o,i),{params:e,startedAt:t,deadline:f,createAttempt:s.attempt}),g=h?void 0:m,v=(C={})=>{if(g!==void 0)return g;let _={...e,account:{...e.account,...C,email:C.email?.trim()||e.account.email?.trim()}};return(0,l.isValidEmail)(_.account.email)?(g=m.then(()=>{let y=this.telemetryTimestamp();return this.claimCheckoutSession(u,p,Lt(_.account),{params:_,startedAt:y,deadline:P(e.timeoutMs??12e3),createAttempt:0})}),g.catch(()=>{}),g):Promise.reject(new l.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return m.catch(()=>{}),{shell:a,sessionId:u,nonce:p,claimed:m,claim:v}}async claimCheckoutSession(e,t,r,s){let i=s?.startedAt??this.telemetryTimestamp(),o=this.telemetryTimestamp(),a=s?.deadline??P(12e3),d=JSON.stringify(r),c="unknown",u=0,p=!1;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let h;for(u=0;u<3;u++){try{h=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION},body:d,signal:a.signal})}catch(g){let v=a.signal.aborted||g instanceof Error&&g.name==="AbortError";if(c=v?"timeout":"network_error",v||u>=2)throw g;try{this.telemetryHooks?.onRetry?.("session_claim",u+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:u+1})}catch{}await q(u,a.signal);continue}if(c=(0,l.telemetryStatusClass)(h.status),h.ok)break;throw await w(h,"Failed to attach checkout session data")}if(!h)throw new TypeError("Checkout-session claim exhausted its retry budget.");p=!0;let f=await h.json();if(!f.data?.gateways)throw new l.FloPayError("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});s?.params&&this.autoCacheDisplayData(f.data.uuid??e,s.params);let m=this.normalizeRawSession(this.mergeCachedDisplayData(f.data));return f.vault&&m.data.session&&(m.data.session.vault=this.toVaultBlock(f.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:c}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_claim",statusClass:c,attempt:u}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:c}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-i),durationMode:"machine",requestCategory:"session_create",statusClass:c,attempt:s?.createAttempt??u}),m}catch(h){throw p&&(0,l.markSessionResponseReceived)(h),this.reportSessionCreateFailure(h,o,{attempt:u,statusClass:c},"session_claim"),h}finally{a.clear()}}reportSessionCreateFailure(e,t,r,s="session_create"){if(!(e instanceof l.FloPayError&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let i=(0,l.classifyTelemetryFailure)(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 l.FloPayError&&e.type==="validation_error"||e instanceof l.FloPayError&&Se(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 l.FloPayError&&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??z,o=Date.now()+i,a=new AbortController,d=!1,c,u=setTimeout(()=>{c=setTimeout(()=>{d=!0,a.abort()},_e)},i),p=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?p():t?.signal?.addEventListener("abort",p,{once:!0});let h=this.clampRetryAfterMs(t?.initialDelayMs??Te),f=0;try{if(t?.statusUrl){let m=await this.waitForCheckoutStatus(e,{initialDelayMs:h,timeoutMs:i,nonce:t.nonce,statusUrl:t.statusUrl,pollAfterAction:t.continueAfterActionRequired,signal:a.signal});if(m){let g=await this.resolveCheckoutSessionStatus(e,m,t.nonce,a.signal,()=>d);return this.reportRecoveryCompleted(r,s,t.challengeAttemptId),g}}for(;;){let m=o-Date.now();if(m<=0)throw R();if(h>0){try{f+=1,this.telemetryHooks?.onRetry?.("session_read",f),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:s,attempt:f})}catch{}if(await j(Math.min(h,m),a.signal),Date.now()>=o)throw R()}let g=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,a.signal),v=g.data.session?.status;if(v==="authorized"||v==="complete"||v==="expired")return this.reportRecoveryCompleted(r,s,t?.challengeAttemptId),g;if(Date.now()>=o)throw R();h=this.clampRetryAfterMs(Math.max(h*2,be))}}catch(m){let g=d&&re(m)?R():m;throw this.reportDirectFailure(g,"RECOVERY_FAILED","recovery","session_read",s),g}finally{clearTimeout(u),clearTimeout(c),t?.signal?.removeEventListener("abort",p)}}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 c=o.code===l.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE;throw new l.FloPayError(c?l.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"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 mt("Payment could not be completed. Please try again.",o?.code??"payment_processing_error");let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,r,s)}catch(c){if(!i?.()||!re(c))throw c;a={providers:[],mode:"tokenize",data:{},raw:t}}let d=a.data.session;return d&&o?.result==="SUCCESS"?{...a,data:{...a.data,session:{...d,status:"complete"}}}:d&&o?.result==="AUTHORIZED"?{...a,data:{...a.data,session:{...d,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:d&&t.status==="completed"?{...a,data:{...a.data,session:{...d,status:"complete"}}}:d&&t.status==="authorized"?{...a,data:{...a.data,session:{...d,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:d&&t.status==="expired"?{...a,data:{...a.data,session:{...d,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??z,s=Date.now()+r,i=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let o=s-Date.now();if(o<=0||i>0&&(await j(Math.min(i,o),t.signal),Date.now()>=s))throw R();let a=s-Date.now();if(a<=0)throw R();let d=new AbortController,c,u=t.signal?new Promise((_,y)=>{c=y}):null,p=()=>{d.abort(t.signal?.reason),c?.(t.signal?.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))};t.signal?.aborted?p():t.signal?.addEventListener("abort",p,{once:!0});let h,f=t.signal?null:new Promise((_,y)=>{h=setTimeout(()=>{y(R()),d.abort()},a+_e)}),m;try{let _=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,d.signal);m=await Promise.race([_,f,u].filter(y=>y!==null))}finally{h!==void 0&&clearTimeout(h),t.signal?.removeEventListener("abort",p)}if(!m)return null;let g=Ce(m.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,m,t.submittedIntentId);if(m.status==="completed"||m.status==="authorized"||m.status==="expired"||m.status==="voided")return g?{...m,latestTransactionAttempt:null}:m;let v=m.latestTransactionAttempt?.result,C=t.pollAfterAction===!0&&v==="ACTION_REQUIRED";if(!g&&v!==void 0&&v!=="PENDING"&&!C)return m;i=this.clampRetryAfterMs(Math.max(i*2,be))}}isOwnFailedAttempt(e,t,r){let s=t.latestTransactionAttempt?.providerIntentId??null;return r!==void 0?s===r:s===null?!0:!gt(t.uuid||e,s)}rememberReportedFailure(e,t){let r=t.latestTransactionAttempt;!Ce(r)||!r.providerIntentId||ft(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 u=new URL(r,`${this.baseUrl}/`),p=new URL(i);u.origin===p.origin&&(o=u.toString())}catch{}let a={[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION};t&&(a["x-checkout-session-token"]=t);let d=await H(o,{headers:a,signal:s});if(d.status===404||d.status===405)return null;if(!d.ok)throw await w(d,"Failed to get checkout session status");let c=await d.json();return U(c.data)&&"latestTransactionAttempt"in c.data?c.data:null}normalizeRawSession(e){let t=e.gateways??{},r=[],s={session:this.toCheckoutSession(e)},i=t.stripe;if(i?.publishableKey){r.push("stripe");let d=[e.stripeClientSecret,i.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);s.stripe={clientSecret:d??"",publishableKey:i.publishableKey??void 0,paypalPublishableKey:i.paypalPublishableKey??void 0,environment:i.environment,enabledPaymentMethods:Array.isArray(i.enabledPaymentMethods)?i.enabledPaymentMethods.filter(c=>typeof c=="string"):void 0}}let o=t.paypal;return o?.publishableKey&&(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((c,u)=>c+(u.overrideAmount??u.totalAmount??0),0),i=r?e.totalAmount:s,o=Math.round(i*100),a=e.currency??t[0]?.currency??"USD",d="payment";return e.checkoutMode==="setup"?d="setup":t.some(c=>c.type==="subscription")&&(d="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:d,status:this.toCheckoutSessionStatus(e.status),amount:o,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:(0,l.normalizeCheckoutFailureOutcome)(e.outcome)??(0,l.normalizeCheckoutFailureOutcome)(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}:{},...lt(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(dt)}:{},buyerIdentified:e.buyerIdentified,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(c=>({...c,totalAmount:typeof c.totalAmount=="number"?c.totalAmount:void 0,overrideAmount:typeof c.overrideAmount=="number"?c.overrideAmount:null,currency:typeof c.currency=="string"?c.currency:void 0,metadata:c.metadata??null})),successUrl:e.successUrl,cancelUrl:e.cancelUrl,coupons:e.coupons,subtotalAmount:e.subtotalAmount,discountAmount:e.discountAmount,totalAmount:e.totalAmount,createdAt:e.createdAt,gateways:e.gateways,accountData:e.accountData,tagsData:e.tagsData}}toVaultBlock(e){let t=St(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??z,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={[ut]:ht},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,d=a?.code===l.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE,c=a?.declineReason??void 0;return new Response(JSON.stringify({type:c??"authorization_declined",message:d?l.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.",code:a?.code??c??"authorization_declined",...c?{declineCode:c}:{}}),{status:400,headers:o})}if(s==="ACTION_REQUIRED"&&e.latestTransactionAttempt?.gateway==="paypal"&&e.latestTransactionAttempt.providerIntentId)return new Response(JSON.stringify({type:"paypal_direct_required",message:"PayPal authorization required",orderId:e.latestTransactionAttempt.providerIntentId}),{status:400,headers:o});if(s==="ACTION_REQUIRED"&&e.latestTransactionAttempt?.nextActionRedirectUrl)return new Response(JSON.stringify({type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:e.latestTransactionAttempt.nextActionRedirectUrl}),{status:400,headers:o});if(s==="ERROR"||e.status==="voided")return new Response(JSON.stringify({type:"unknown",code:e.latestTransactionAttempt?.code??"payment_processing_error",message:ct(e)??"Payment could not be completed. Please try again."}),{status:500,headers:o});throw R()}async reconcileProcessPayment(e,t){let r=t?.pollTimeoutMs??z,s=Date.now()+r,i=null;try{i=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:r,nonce:t?.nonce,submittedIntentId:t?.submittedIntentId})}catch(d){if(this.reportDirectFailure(d,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),d instanceof l.FloPayError&&d.code==="checkout_processing_timeout")throw d}if(i)return this.toProcessResponseFromStatus(i,e,t?.nonce);let o=s-Date.now();if(o<=0)throw R();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 l.FloPayError(r?"Authorization has expired.":"Checkout session has expired.","api_error",{code:r?"authorization_expired":"checkout_session_expired"})}throw R()}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:M(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs(_t(e,"retryAfterMs")??o??Te),statusUrl:M(e,"statusUrl"),sessionUrl:M(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,Ct))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??(0,l.foldIntoProducts)(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let s=t.products!==void 0,i=(0,l.resolveSessionCurrency)(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=ae(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),d=a?r.get(a):void 0;return{...o,name:o.name??d?.name??null,totalAmount:o.totalAmount??d?.totalAmount,overrideAmount:o.overrideAmount??d?.overrideAmount,currency:o.currency??d?.currency}});return{...e,currency:e.currency??t?.currency,products:i}}};A.activeVaultCaptureRequests=new Map,A.pendingThreeDsAbandonReports=new Map;var D=A;var T=require("@flopay/shared");var $=require("@flopay/shared");function Pe(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 G=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=(0,$.resolveCardFieldsTimeoutMs)(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=Pe(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=Pe(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))(0,$.invokeMerchantCallback)(()=>t(e))}};var qt=4,W="flopay-vault",Nt=3e4,Vt=T.THREE_DS_CHALLENGE_WINDOW_MS+Nt,Bt="Card authentication timed out.",De={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 zt(n){return n.class==="lifecycle"?n.name:n.class==="technical_error"?n.code:n.class==="expected_outcome"?n.outcome:"sdk.performance"}function F(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:zt(n),data:e})}catch{}}function L(n,e){return(0,T.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var Ht=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function jt(n){return typeof n=="string"&&Ht.has(n)?n:"unknown"}var Kt=new Set(["verification_failed","verification_expired"]);function Gt(n){return n==null?!0:typeof n=="string"&&Kt.has(n)}var $t="vault_mount";function Yt(n){return n.failureStage===$t}function ne(n,e){return n&&!Yt(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:jt(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function Fe(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 Wt(n,e,t,r="checkout"){let{type:s}=n;if(s==="complete"||s==="decline")return(0,T.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:Fe(n,t,r),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(s==="error"){let a=ne(e,n);return(0,T.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[i,o]=De[s];return L(i,o)}function Jt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===W&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function Qt(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 Xt(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 Zt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===W&&e.type==="validation"&&Array.isArray(e.messages)}function er(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===W&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}function tr(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===W&&e.type==="fields_interactive"}function rr(n){let e=n.capabilities;return Array.isArray(e)&&e.includes("fields_interactive")}var nr=["number","expiry","cvv","name"];function sr(n){if(n===null||typeof n!="object")return;let e=n,t={};for(let r of nr){let s=e[r];typeof s=="string"&&(t[r]=s)}return t}var Y=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 G({timeoutMs:e.cardFieldsTimeoutMs,now:()=>this.telemetryReporter?.now?.()??S(),report:r=>this.reportCardFields(r)}),this.ownsTelemetryReporter=!t&&e.telemetry!==!1,this.telemetryReporter=t?.reporter??(this.ownsTelemetryReporter?new k({billingApiUrl:(0,T.resolveBillingApiUrl)(e.billingApiUrl),sdkVersion:T.SDK_VERSION}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new k({billingApiUrl:(0,T.resolveBillingApiUrl)(this.config.billingApiUrl),sdkVersion:T.SDK_VERSION}));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?.()??S(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,this.cardFields.begin(),typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),new T.FloPayError("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 T.FloPayError("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(),F(L("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?.()??S())-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(er(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(Zt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let c=r.messages.filter(u=>typeof u=="string"&&u.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:c||void 0});return}if(tr(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let c=typeof r.sessionId=="string"?r.sessionId:void 0;if(this.config.sessionId&&c&&c!==this.config.sessionId)return;this.cardFields.ready();return}if(!Jt(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=Xt(r.paymentMethod),a=Qt(r.vaultOutcome),d={...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?.()??S()),this.isVerificationStateError(r)?(F(L("operation.state_transition","vault_mount")),this.telemetryReporter?.log({name:"operation.state_transition",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})):(F(Wt(r,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(r),r.type==="error"&&ne(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(),rr(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,d)};this.messageHandler=e,window.addEventListener("message",e)}isVerificationStateError(e){return e.type==="error"&&this.verificationRequired&&!this.submissionStarted&&Gt(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:Fe(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="error"){let o=ne(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]=De[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=(0,T.buildCardFieldLabelsPayload)(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=sr(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 m=this.actionOverlay.querySelector("iframe");m instanceof HTMLIFrameElement&&m.src!==e&&(m.src=e),this.armActionRequiredTimeout();return}this.actionOverlayPreviousFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;let t=ue(this.beginActionChallengeAttempt()),r=pe(e),s=!1,i=m=>{if(s)return;let g=me(m,r);g&&(s=!0,t.record("policy_violation",{reason:g,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"),te(e)==="invalid"&&t.record("action_invalid",{reason:"invalid_url"}),document.addEventListener("securitypolicyviolation",i),window.addEventListener("pagehide",o);let d=document.createElement("div");d.setAttribute("data-flopay-action-required","1"),d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-label","Card authentication"),d.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let c=document.createElement("iframe");c.setAttribute("title","Card authentication"),c.setAttribute("allow","payment"),c.tabIndex=0,c.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),c.addEventListener("load",()=>{a.loaded||(a.loaded=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"}))}),c.src=e,d.appendChild(c);let u=document.createElement("button");u.type="button",u.setAttribute("aria-label","Close card authentication"),u.textContent="\xD7",u.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(";"),u.addEventListener("click",()=>this.abandonActionRequiredOverlay()),d.appendChild(u),d.addEventListener("click",m=>{m.target===d&&this.abandonActionRequiredOverlay()});let p=0,h=m=>{let g=m.data,v=!!g&&typeof g=="object"&&g.source==="flopay-vault-3ds-return";if(m.source!==c.contentWindow){v&&p<qt&&(p+=1,t.record("return_rejected",{reason:"untrusted_source",evidenceBasis:"message_origin_check"}));return}v&&(t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),F(L("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",h),this.threeDsReturnHandler=h,t.record("render_attempted");try{document.body.appendChild(d)}catch(m){throw t.record("render_failed"),this.hideActionRequiredOverlay(),this.actionOverlayPreviousFocus=null,m}t.record("container_attached"),t.record("navigation_assigned");let f=he(d);f&&t.record("container_visibility",{reason:f,evidenceBasis:"parent_computed_style"}),this.actionOverlay=d,c.focus(),this.armActionRequiredTimeout(),F(L("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},Vt)}reportChallengeAbandoned(){F((0,T.buildTelemetryTerminalEvent)({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:Bt})}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 D((0,T.resolveBillingApiUrl)(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`}};var ir=["setup_intent","setup_intent_client_secret","redirect_status"];function Oe(){if(typeof window>"u")return null;let n=new URLSearchParams(window.location.search);return!n.has("setup_intent")||!n.has("redirect_status")?null:{failed:n.get("redirect_status")==="failed"}}function xe(){if(typeof window>"u")return;let n=new URL(window.location.href),e=!1;for(let t of ir)n.searchParams.has(t)&&(n.searchParams.delete(t),e=!0);e&&window.history.replaceState(window.history.state,"",n.toString())}0&&(module.exports={PaymentAPI,PciVaultCardCapture,clearSetupRedirectParams,readSetupRedirectReturn});
|
|
1
|
+
"use strict";var Q=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var je=Object.prototype.hasOwnProperty;var Ke=(n,e)=>{for(var t in e)Q(n,t,{get:e[t],enumerable:!0})},Ge=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of He(e))!je.call(n,i)&&i!==t&&Q(n,i,{get:()=>e[i],enumerable:!(r=ze(e,i))||r.enumerable});return n};var $e=n=>Ge(Q({},"__esModule",{value:!0}),n);var lr={};Ke(lr,{PaymentAPI:()=>D,PciVaultCardCapture:()=>Y,clearSetupRedirectParams:()=>Ue,readSetupRedirectReturn:()=>xe});module.exports=$e(lr);var l=require("@flopay/shared");function se(n){return typeof n=="string"&&n.trim()?n:void 0}function oe(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 P(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 Ye(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function q(n,e){let t=150*2**n,r=Math.round(t*(.75+Math.random()*.5));return new Promise((i,s)=>{let o,a=()=>e.removeEventListener("abort",d),d=()=>{o!==void 0&&clearTimeout(o),a(),s(Ye())};if(e.aborted){d();return}o=setTimeout(()=>{a(),i()},r),e.addEventListener("abort",d,{once:!0})})}var We="flopay_session_display:";var N=new Map;function V(n){return`${We}${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,i={data:e,expiresAt:Date.now()+r},s=X();if(s)try{s.setItem(V(n),JSON.stringify(i));return}catch{}N.set(n,i)}function ae(n){if(!n)return null;let e=X();if(e)try{let r=e.getItem(V(n));if(r){let i=JSON.parse(r);if(i&&typeof i.expiresAt=="number"&&i.expiresAt>Date.now())return i.data;e.removeItem(V(n))}}catch{}let t=N.get(n);if(t){if(t.expiresAt>Date.now())return t.data;N.delete(n)}return null}function le(n){if(!n)return;N.delete(n);let e=X();if(e)try{e.removeItem(V(n))}catch{}}var b=require("@flopay/shared");var ee=require("@flopay/shared"),Je=32,de=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function Qe(){let n=globalThis,e=n[de];if(e instanceof Map)return e;let t=new Map;try{Object.defineProperty(n,de,{configurable:!0,enumerable:!1,writable:!1,value:t})}catch{}return t}function Xe(n,e){let t=Qe(),r=t.get(n);if(r)return r;for(;t.size>=Je;){let s=t.keys().next();if(s.done)break;t.delete(s.value)}let i={nextSequence:0,startedAt:e,terminated:!1,reconciled:new Set,provider:"unknown"};return t.set(n,i),i}var Ze=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),et=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function ce(n,e={}){let t=(0,ee.isThreeDsChallengeAttemptId)(e.attemptId)?e.attemptId.toLowerCase():n.newAttemptId(),r=()=>{try{let a=n.now();return Number.isFinite(a)?a:0}catch{return 0}},i=Xe(t,r());(e.provider==="stripe"||e.provider==="worldpay")&&(i.provider=e.provider);let s=i.provider,o=(a,d)=>{if(i.terminated&&!et.has(a))return;let c={attemptId:t,phase:a,attemptSequence:i.nextSequence,elapsedMs:Math.max(0,r()-i.startedAt),provider:s};i.nextSequence+=1,d.reason!==void 0&&(c.reason=d.reason),d.evidenceBasis!==void 0&&(c.evidenceBasis=d.evidenceBasis),d.terminalSource!==void 0&&(c.terminalSource=d.terminalSource),d.providerOutcome!==void 0&&(c.providerOutcome=d.providerOutcome);try{n.emit(c,Ze.has(a))}catch{}};return{attemptId:t,record(a,d={}){a==="browser_terminal"||a==="provider_reconciled"||o(a,{reason:d.reason,evidenceBasis:d.evidenceBasis})},terminal(a,d={}){i.terminated||(o("browser_terminal",{terminalSource:a,reason:d.reason,evidenceBasis:d.evidenceBasis}),i.terminated=!0)},reconcile(a){i.reconciled.has(a)||(i.reconciled.add(a),o("provider_reconciled",{providerOutcome:a,evidenceBasis:"provider_fact"}))}}}function ue(n){let e=null;try{e=(0,ee.isThreeDsChallengeAttemptId)(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 te(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 he(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 pe(n,e){if(!e)return null;try{let t=n,r=String(t.effectiveDirective||t.violatedDirective||"").trim().split(/\s+/)[0],i=null;return r==="frame-src"&&(i="frame_src"),r==="child-src"&&(i="child_src"),!i||typeof t.blockedURI!="string"?null:new URL(t.blockedURI).origin===e?i:null}catch{return null}}function me(n){try{return te(n)==="valid"?new URL(n).origin:null}catch{return null}}var tt="/v1/sdk-telemetry/events",B=16,ye=64,rt=1500,ge=1e3,nt=64,it="00000000-0000-4000-8000-000000000000",st={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},ot=48;function E(){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 at(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function lt(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 S(){return globalThis.performance?.now()??0}var k=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(/\/+$/,"")}${tt}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=E(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??S,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((0,b.buildTelemetryLogEvent)({...this.checkoutContext,...e,eventId:E(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=(0,b.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:it,sequence:0}),r=lt(t),i=this.now();this.pruneReportedFailures(i);let s=this.reportedFailures.get(r);if(s!==void 0&&i>=s&&i-s<ge){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,i),this.enqueue((0,b.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:E(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,b.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:E(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,b.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:E(),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 ce({now:()=>this.now(),newAttemptId:E,emit:(t,r)=>this.recordThreeDsChallenge(t,r)},e)}recordThreeDsChallenge(e,t){if(!this.canCollect()||this.threeDsChallengeCount>=ot)return;let r=(0,b.buildTelemetryLogEvent)({...this.checkoutContext,...e,name:"three_ds.challenge",stage:"three_ds_handoff",eventId:E(),sequence:this.sequence++});if(!(this.queue.length>=ye)){if(this.threeDsChallengeCount+=1,this.queue.push(r),t){this.drainQueue();return}if(this.queue.length>=B){this.flush();return}this.scheduleFlush()}}now(){try{return this.clock()}catch{return S()}}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>=ge)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=nt;){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>=ye||this.eventCounts[e.class]>=st[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=B){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,B);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,B);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=(0,b.serializeTelemetryBatch)(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:E()});if(at(t)>b.TELEMETRY_MAX_BATCH_BYTES)return;let r=typeof AbortController>"u"?null:new AbortController,i=null;try{let s=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 d=>{if(d.status!==202)return null;let c=null;try{c=await d.json()}catch{}return c?.status==="disabled"?"disabled":null}).catch(()=>null),o=new Promise(d=>{i=setTimeout(()=>{r?.abort(),d(null)},rt)});await Promise.race([s,o])==="disabled"&&this.disableFromIngestion()}catch{}finally{i&&clearTimeout(i)}}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)}},fe=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),ve=globalThis;ve[fe]===void 0&&Object.defineProperty(ve,fe,{configurable:!0,enumerable:!1,writable:!1,value:n=>new k(n)});function dt(n){return n==="on_session"||n==="off_session"}function ct(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function ut(n){let e=n.vaultOutcome;if(!(!e||e.code!==l.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED))return typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0}var ht="x-flopay-process-result-source",pt="status",Me=new WeakSet;function mt(n,e){let t=new l.FloPayError(n,"api_error",{code:e,statusCode:500});return Me.add(t),t}function yt(n){return typeof n=="object"&&n!==null&&Me.has(n)}function Ce(n){return n?.result==="DECLINE"||n?.result==="ERROR"}var gt=50,I=new Map;function ft(n,e){return I.get(n)?.has(e)===!0}function vt(n,e){let t=I.get(n)??new Set;if(t.add(e),I.delete(n),I.set(n,t),I.size>gt){let r=I.keys().next().value;r!==void 0&&I.delete(r)}}function Ct(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 Te=0,be=500,z=15e3,_e=15e3,Tt=3e3,bt=1e4,_t=1e4;function U(n){return typeof n=="object"&&n!==null}function M(n,e){return se(n?.[e])}function Re(n,e){return oe(n?.[e])}function Rt(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function j(n,e){return e?new Promise((t,r)=>{let i=()=>{clearTimeout(s),r(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},s=setTimeout(()=>{e.removeEventListener("abort",i),t()},n);e.aborted?i():e.addEventListener("abort",i,{once:!0})}):new Promise(t=>setTimeout(t,n))}function re(n){return n instanceof Error&&n.name==="AbortError"}function R(){return new l.FloPayError(l.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}async function w(n,e){let t=await n.json().catch(()=>null),r=U(t?.error)?t.error:null,i=Re(t,"message")??Re(r,"message")??e,s=M(t,"code")??M(t,"gatewayErrorCode")??M(r,"code")??`http_${n.status}`;return(0,l.withTelemetryHttpDiagnostics)(new l.FloPayError(i,"api_error",{code:s,statusCode:n.status}),n)}async function St(n){if(n.status!==403)return!1;let e=await n.clone().json().catch(()=>null),t=U(e?.error)?e.error:null;return(M(e,"code")??M(t,"code"))==="verification_required"}function At(n){if(!(!U(n)||typeof n.required!="boolean"))return{required:n.required,provider:"turnstile"}}async function wt(n){let e=n.status===400?await n.clone().json().catch(()=>null):null;return(0,l.classifyPaymentRejection)(n.status,e)}function Se(n){return n===400||n===422}var K=2;async function H(n,e,t=K,r,i){let s;for(let o=0;;o++)try{return i?.(o),await fetch(n,e)}catch(a){if(e?.signal?.aborted||a instanceof Error&&a.name==="AbortError")throw a;if(s=a,o>=t)throw s;try{r?.(o+1)}catch{}await j(150*2**o,e?.signal??void 0)}}var Et=2e3,kt=1e4,Mt=150;async function It(n){try{let t=(await n.json())?.data?.status;return t==="closed"||t==="not_open"?t:"failed"}catch{return"failed"}}async function Ae(n,e,t){let r=new AbortController,i=()=>r.abort();t?.addEventListener("abort",i,{once:!0});let s,o=new Promise(a=>{s=setTimeout(()=>{r.abort(),a("timeout")},kt)});try{let a=await Promise.race([fetch(n,{...e,signal:r.signal}),o]);return a==="timeout"?"failed":a.status>=500?"retry":a.ok?await It(a):"failed"}catch{return r.signal.aborted?"failed":"retry"}finally{clearTimeout(s),t?.removeEventListener("abort",i)}}function Pt(n,e){return new Promise(t=>{let r=setTimeout(t,e);n.then(()=>{clearTimeout(r),t()},()=>{clearTimeout(r),t()})})}var we="stripe-account-switch-v1",Dt=Symbol.for("@flopay/js.session-create.telemetry.v1");function Ft(n){return n[Dt]}function Ot(n){return"now"in n||"onFirstByte"in n||"onSessionCreateFailure"in n||"onRetry"in n}function Ie(n){let e=(0,l.isCardHolderNamePlaceholder)(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 Pe(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 Ee(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function xt(n){let e={};if(n.country&&(e.country=n.country),!(0,l.isCardHolderNamePlaceholder)(n.firstName,n.lastName)){let t=Ee(n.firstName),r=Ee(n.lastName);t&&(e.firstName=t),r&&(e.lastName=r)}return Object.keys(e).length>0?e:void 0}function Ut(n,e,t){let r={clientId:n.clientId,checkoutVersion:l.SDK_VERSION,successUrl:n.successUrl,cancelUrl:n.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};n.captureMethod==="manual"&&(r.captureMethod=n.captureMethod);let i=xt(n.account);i&&(r.accountData=i),Pe(r,n);let s=Lt(t);return s&&(r.routingProducts=s),r}function Lt(n){let e=new Set;for(let t of n){let r=[t.code,t.providerItemId,t.providerPlanId].map(i=>typeof i=="string"?i.trim():"").find(i=>i.length>0);r&&e.add(r)}return e.size>0?Array.from(e,t=>({code:t})):void 0}function ke(n,e,t){return{currency:e,products:t.map(r=>(0,l.buildProductPayload)(r,e)),couponCodes:n.couponCodes??[],accountData:Ie(n.account)}}function qt(n,e,t){return{currency:e,products:t.map(r=>(0,l.buildProductPayload)(r,e)),couponCodes:n.couponCodes??[]}}function Nt(n){let e={},t=(0,l.isCardHolderNamePlaceholder)(n.firstName,n.lastName);for(let[r,i]of Object.entries(n)){if(t&&r.endsWith("Name")||typeof i!="string")continue;let s=i.trim();s&&(e[r]=s)}return{accountData:e}}var A=class A{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=Ot(t);this.telemetryHooks=r?t:void 0,this.stripeAccountSwitch=!r&&t.stripeAccountSwitch===!0,this.directTelemetry=r||t.telemetry===!1?void 0:new k({billingApiUrl:this.baseUrl,sdkVersion:l.SDK_VERSION})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,i,s="unknown"){let o=(0,l.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...o,...yt(e)?{reason:"capture_failed"}:{},stage:r,requestCategory:i,paymentMethodCategory:s})}reportAccountSnapshotFailure(e,t){let r=(0,l.classifyTelemetryFailure)(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()??S()}catch{return S()}}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,i){this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp(),o=s,a=0;this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let d={[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION};t&&(d["x-checkout-session-token"]=t);let c=!1;try{let u=await H(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:d,signal:i},K,h=>{this.telemetryHooks?.onRetry?.("session_read",h),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:h})},h=>{a=h,o=this.telemetryTimestamp()});c=!0;let y=Math.max(0,this.telemetryTimestamp()-o);try{this.telemetryHooks?.onFirstByte?.(y,a)}catch{}let p=`${Math.floor(u.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:p,attempt:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:y,durationMode:"machine",requestCategory:"session_read",statusClass:p,attempt:a}),!u.ok)throw await w(u,"Failed to get checkout session");let m=await u.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:p}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"session_read",statusClass:p}),{...m,data:this.mergeCachedDisplayData(m.data)}}catch(u){throw c&&(0,l.markSessionResponseReceived)(u),r&&this.directTelemetry?.error({...(0,l.classifyTelemetryFailure)(u,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),u}}cacheSessionDisplayData(e,t,r){Z(e,t,r)}clearSessionDisplayData(e){le(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,i=A.activeVaultCaptureRequests.get(r);if(i!==void 0)return i;let s=A.pendingThreeDsAbandonReports.get(e),o=s===void 0?this.requestVaultCapture(e,t):Pt(s,Et).then(()=>this.requestVaultCapture(e,t));A.activeVaultCaptureRequests.set(r,o);try{return await o}finally{A.activeVaultCaptureRequests.get(r)===o&&A.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,i=setTimeout(()=>r.abort(),_t);this.beginDirectTelemetryCheckout(e);let s=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 H(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:o,signal:r.signal},K,c=>{this.telemetryHooks?.onRetry?.("vault_capture",c),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:c})});if(await St(a))return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"4xx"}),{verification:{required:!0,provider:"turnstile"}};if(!a.ok)throw await w(a,"Failed to load the secure card form");let d=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(d)}catch(a){let d=r.signal.aborted?new l.FloPayError("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(d,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),d}finally{clearTimeout(i)}}async getUnifiedCheckoutSession(e,t){let r=await this.getCheckoutSession(e,t);return this.normalizeCheckoutSessionResponse(r)}async getUnifiedCheckoutSessionForRecovery(e,t,r){let i=await this.fetchCheckoutSession(e,t,!1,r);return this.normalizeCheckoutSessionResponse(i)}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(0,l.markSessionResponseReceived)(t)}}async processPayment(e,t,r){this.beginDirectTelemetryCheckout(t.sessionId);let i=t.paymentMethodCategory??"unknown";if(!t.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:i}),new l.FloPayError("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:i});let{nonce:o,paymentMethodCategory:a,...d}=t,c=Ct(t.tokenizedData),u,y;try{u=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(d)}),y=u}catch(p){if(re(p))throw this.reportDirectFailure(p,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),p;u=await this.reconcileProcessPayment(t.sessionId,{...r,nonce:o,paymentMethodCategory:i,submittedIntentId:c})}if(!u.ok&&u.status!==202){let p=await wt(u);return p?this.directTelemetry?.terminal({outcome:p,stage:"processing",requestCategory:"process_payment",statusClass:"4xx",paymentMethodCategory:i}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:(0,l.telemetryStatusClass)(u.status),failureCategory:u.status>=500?"server_error":void 0,paymentMethodCategory:i,...(0,l.readTelemetryHttpDiagnostics)(y)}),u}try{let p=await this.resolveProcessResponse(u,t.sessionId,{...r,nonce:o,paymentMethodCategory:i,submittedIntentId:c});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,l.telemetryStatusClass)(p.status),paymentMethodCategory:i}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,l.telemetryStatusClass)(p.status),paymentMethodCategory:i}),p}catch(p){throw p instanceof l.FloPayError&&p.code==="checkout_processing_timeout"||this.reportDirectFailure(p,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),p}}async patchAccountSnapshot(e,t,r,i){this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let o=i?.timeoutMs??bt,a=new AbortController,d=()=>a.abort();i?.signal&&(i.signal.aborted?a.abort():i.signal.addEventListener("abort",d,{once:!0}));let c=setTimeout(()=>a.abort(),o);try{let u;try{u=await H(`${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},K,y=>{this.telemetryHooks?.onRetry?.("account_snapshot",y),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:y})})}finally{clearTimeout(c),i?.signal?.removeEventListener("abort",d)}if(!u.ok)throw await w(u,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(u){throw this.reportAccountSnapshotFailure(u,i?.telemetryMode??"blocking"),u}}async createSessionIntent(e,t,r,i){if(!t)throw new l.FloPayError("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=r,o=s.paymentMethodType,a=typeof o=="string"&&o.trim().toLowerCase()==="card",d=typeof o=="string"&&o.length>0&&!a&&(typeof s.paymentMethodId=="string"||s.paymentMethodId===null),c=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(s.intentKind==="payment"||s.intentKind==="setup"),u=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodId===null&&(s.paymentMethodType==="paypal"&&s.intentKind==="payment"||s.paymentMethodType===l.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&(s.intentKind==="payment"||s.intentKind==="setup"));if(!d||!c&&!u)throw new l.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let y=s.authorizationAttemptId;if(y!==void 0&&!(0,l.isUuidV4)(y))throw new l.FloPayError("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let p=(0,l.isUuidV4)(y)?y:(0,l.randomUuidV4)();this.beginDirectTelemetryCheckout(e);let m=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,[l.IDEMPOTENCY_KEY_HEADER]:i?.idempotencyKey||p},g=!1;try{let C=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:h,body:JSON.stringify({...r,authorizationAttemptId:p}),signal:i?.signal});if(!C.ok){g=!0;let J=await w(C,"Failed to create checkout intent"),Be=(0,l.classifyTelemetryFailure)(J,"PAYMENT_PROCESSING_FAILED");throw Se(J.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...Be,stage:"processing",requestCategory:"intent_create"}),J}let v=await C.json();if(C.status===202&&U(v)&&v.type==="checkout_processing")return g=!0,await this.settleProcessingSessionIntent(v,C,e,t,r);let _=v.data;if(!_||typeof _!="object")throw new l.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let f=_,ie=f.paymentMethodType,Le=(f.paymentMethodCategory==="wallet"||f.paymentMethodCategory==="apm")&&typeof ie=="string"&&ie.trim().toLowerCase()!=="card"&&(typeof f.paymentMethodId=="string"||f.paymentMethodId===null)&&typeof f.providerObjectId=="string",qe=f.provider==="stripe"&&(f.intentKind==="payment"||f.intentKind==="setup")&&typeof f.clientSecret=="string",Ne=f.provider==="paypal"&&f.paymentMethodCategory==="wallet"&&f.paymentMethodId===null&&(f.paymentMethodType==="paypal"&&f.intentKind==="payment"&&(f.providerObjectType==="order"||f.providerObjectType==="subscription")||f.paymentMethodType===l.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&f.intentKind==="payment"&&f.providerObjectType==="order"||f.paymentMethodType===l.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&f.intentKind==="setup"&&f.providerObjectType==="setup_token")&&f.clientSecret===null,Ve=f.provider===r.provider&&f.paymentMethodCategory===r.paymentMethodCategory&&f.paymentMethodType===r.paymentMethodType&&f.paymentMethodId===r.paymentMethodId&&f.intentKind===r.intentKind;if(!Le||!qe&&!Ne||!Ve)throw new l.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:(0,l.telemetryStatusClass)(C.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-m),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,l.telemetryStatusClass)(C.status)}),f}catch(C){throw g||this.reportDirectFailure(C,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),C}}async settleProcessingSessionIntent(e,t,r,i,s){let o=this.toCheckoutProcessingPending(e,t,r);try{return{settled:!0,response:await this.resolveCheckoutProcessing(o,r,{nonce:i,paymentMethodCategory:s.provider==="paypal"?"paypal":s.paymentMethodCategory})}}catch(a){throw a instanceof l.FloPayError&&a.code==="checkout_processing_timeout"?new l.FloPayError(a.message,a.type,{code:a.code,statusCode:202,sessionId:o.sessionId,cause:a}):a}}closeThreeDsChallenge(e,t,r,i={}){if(!e||!t||!r||i.signal?.aborted)return Promise.resolve("failed");let s=this.requestThreeDsChallengeClose(e,t,r,i.signal),o=A.pendingThreeDsAbandonReports;return o.set(e,s),s.then(()=>{o.get(e)===s&&o.delete(e)}),s}async requestThreeDsChallengeClose(e,t,r,i){let s=`${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 Ae(s,o,i);if(a!=="retry")return a;if(i?.aborted)return"failed";await j(Mt,i);let d=await Ae(s,o,i);return d==="retry"?"failed":d}catch{return"failed"}}async reportSessionIntentDecline(e,t,r,i){if(!t)throw new l.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=r,o=s.providerDeclineReason,a=s.paymentMethodType,d=s.providerIntentId,c=typeof o=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(o)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(o),u=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&c,y=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(d===void 0||typeof d=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(d)),p=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodType==="paypal"&&d===void 0;if(!u||!y&&!p)throw new l.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let m=p?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:o}:{provider:"stripe",paymentMethodCategory:s.paymentMethodCategory,paymentMethodType:s.paymentMethodType,providerDeclineReason:o,...typeof d=="string"?{providerIntentId:d}:{}},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(m),signal:i?.signal});if(!h.ok)throw await w(h,"Failed to report checkout decline")}async resolvePaymentMethodLayout(e,t,r,i){if(!t)throw new l.FloPayError("resolvePaymentMethodLayout requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/payment-method-layout`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION},body:JSON.stringify(r),signal:i?.signal});if(s.status===404||s.status===405)return null;if(!s.ok)throw await w(s,"Failed to resolve the payment method layout");let o=await s.json();return(0,l.normalizePaymentMethodLayout)(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 i=t?.page??1,s=t?.limit??1,o=new URLSearchParams({email:e,page:String(i),limit:String(s),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(0,l.withTelemetryHttpDiagnostics)(new l.FloPayError("Failed to fetch payments","api_error",{statusCode:a.status}),a);let d=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"}),d}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if((0,l.isDetachedSessionEligible)(e)){let s=e.account.email?.trim();if(s&&!(0,l.isValidEmail)(s))throw new l.FloPayError("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=P(e.timeoutMs??12e3),i={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let s=await this.createAndFetchSessionRequest(e,r.signal,i);return this.adoptDirectTelemetryCheckout(s.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:i.statusClass}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:i.statusClass,attempt:i.attempt}),s}catch(s){throw this.reportSessionCreateFailure(s,t,i),s}finally{r.clear()}}async createAndFetchSessionRequest(e,t,r){let i=e.products??(0,l.foldIntoProducts)(e.items,e.subscriptions);(0,l.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:i});let s=(0,l.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,i);if(!s)throw new l.FloPayError("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:l.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:s,checkoutMode:e.checkoutMode??"full",products:i.map(c=>(0,l.buildProductPayload)(c,s)),accountData:Ie(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(o.captureMethod=e.captureMethod),e.tokenizedData&&(o.tokenizedData=e.tokenizedData),Pe(o,e);let a=await this.postCheckoutSessionCreate(o,e,t,r),d=!1;try{let c=await a.json();if(c.data&&"gateways"in c.data){this.autoCacheDisplayData(c.data.uuid,e);let p=this.mergeCachedDisplayData(c.data),m=this.normalizeRawSession(p);return c.vault&&m.data.session&&(m.data.session.vault=this.toVaultBlock(c.vault)),{...m,autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}let u=c.data?.uuid;if(!u)throw new l.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(u,e),this.adoptDirectTelemetryCheckout(u),d=!0,{...await this.getUnifiedCheckoutSession(u),autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}catch(c){throw d?c:(0,l.markSessionResponseReceived)(c)}}async postCheckoutSessionCreate(e,t,r,i){let s={"Content-Type":"application/json",[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION},o=(0,l.resolveIdempotencyKey)(t.idempotencyKey);o&&(s[l.IDEMPOTENCY_KEY_HEADER]=o);let a=[];t.checkoutMode==="auto"&&a.push(l.ASYNC_AUTO_CHECKOUT_CAPABILITY),this.stripeAccountSwitch&&e.deferDataAttachment===!0&&a.push(we),a.length>0&&(s[l.FLO_SDK_CAPABILITIES_HEADER]=a.join(", "));let d,c=!1,u=Ft(t),y=(m,h,g)=>{c||(c=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:g,attempt:m}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-h),durationMode:"machine",requestCategory:"session_create",statusClass:g,attempt:m}))},p=m=>{try{this.telemetryHooks?.onRetry?.("session_create",m),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:m})}catch{}};for(let m=0;m<3;m++){i.attempt=m;let h=this.telemetryTimestamp();try{u?.onAttempt?.(m)}catch{}try{d=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:s,body:JSON.stringify(e),signal:r})}catch(v){if(i.statusClass=r.aborted||v instanceof Error&&v.name==="AbortError"?"timeout":"network_error",r.aborted||v instanceof Error&&v.name==="AbortError"||m>=2)throw v;let _=m+1;p(_),await q(m,r);continue}let g=(0,l.telemetryStatusClass)(d.status);if(i.statusClass=g,d.status===204)throw y(m,h,g),new l.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(d.ok){y(m,h,g);break}let C=await w(d,"Failed to create checkout session");if(C.code===l.IDEMPOTENCY_IN_PROGRESS_CODE&&m<2){p(m+1),await q(m,r);continue}throw y(m,h,g),C}if(!d)throw new TypeError("Checkout-session creation exhausted its retry budget.");return d}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=P(e.timeoutMs??12e3),i={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let s=e.products??(0,l.foldIntoProducts)(e.items,e.subscriptions);try{(0,l.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:s})}catch(v){throw r.clear(),this.reportSessionCreateFailure(v,t,i),v}let o=(0,l.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,s);if(!o)throw r.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new l.FloPayError("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{ke(e,o,s)}catch(v){throw r.clear(),this.reportSessionCreateFailure(v,t,i),v}let a,d,c=!1;try{let v=await this.postCheckoutSessionCreate(Ut(e,o,s),e,r.signal,i);if(c=!0,d=await v.json(),!d.data||!("gateways"in d.data))throw new l.FloPayError("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(d.data)),d.vault&&a.data.session&&(a.data.session.vault=this.toVaultBlock(d.vault))}catch(v){throw r.clear(),c&&(0,l.markSessionResponseReceived)(v),this.reportSessionCreateFailure(v,t,i),v}let u=a.data.session?.id??d.data.uuid??"",y=a.data.session?.clientSecret??d.data.nonce??"";if(!u||!y){r.clear();let v=new l.FloPayError("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(v,t,i),v}r.clear(),this.adoptDirectTelemetryCheckout(u),this.directTelemetry?.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",statusClass:i.statusClass,paymentMethodCategory:"card"}),this.directTelemetry?.performance({stage:"session_shell",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:i.statusClass,attempt:i.attempt,paymentMethodCategory:"card"});let p=!e.account.email?.trim(),m=P(e.timeoutMs??12e3),h=this.claimCheckoutSession(u,y,p?qt(e,o,s):ke(e,o,s),{params:e,startedAt:t,deadline:m,createAttempt:i.attempt}),g=p?void 0:h,C=(v={})=>{if(g!==void 0)return g;let _={...e,account:{...e.account,...v,email:v.email?.trim()||e.account.email?.trim()}};return(0,l.isValidEmail)(_.account.email)?(g=h.then(()=>{let f=this.telemetryTimestamp();return this.claimCheckoutSession(u,y,Nt(_.account),{params:_,startedAt:f,deadline:P(e.timeoutMs??12e3),createAttempt:0})}),g.catch(()=>{}),g):Promise.reject(new l.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return h.catch(()=>{}),{shell:a,sessionId:u,nonce:y,claimed:h,claim:C}}async claimCheckoutSession(e,t,r,i){let s=i?.startedAt??this.telemetryTimestamp(),o=this.telemetryTimestamp(),a=i?.deadline??P(12e3),d=JSON.stringify(r),c="unknown",u=0,y=!1;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let p;for(u=0;u<3;u++){try{p=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION,...this.stripeAccountSwitch?{[l.FLO_SDK_CAPABILITIES_HEADER]:we}:{}},body:d,signal:a.signal})}catch(g){let C=a.signal.aborted||g instanceof Error&&g.name==="AbortError";if(c=C?"timeout":"network_error",C||u>=2)throw g;try{this.telemetryHooks?.onRetry?.("session_claim",u+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:u+1})}catch{}await q(u,a.signal);continue}if(c=(0,l.telemetryStatusClass)(p.status),p.ok)break;throw await w(p,"Failed to attach checkout session data")}if(!p)throw new TypeError("Checkout-session claim exhausted its retry budget.");y=!0;let m=await p.json();if(!m.data?.gateways)throw new l.FloPayError("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});i?.params&&this.autoCacheDisplayData(m.data.uuid??e,i.params);let h=this.normalizeRawSession(this.mergeCachedDisplayData(m.data));return m.vault&&h.data.session&&(h.data.session.vault=this.toVaultBlock(m.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:c}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_claim",statusClass:c,attempt:u}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:c}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"session_create",statusClass:c,attempt:i?.createAttempt??u}),h}catch(p){throw y&&(0,l.markSessionResponseReceived)(p),this.reportSessionCreateFailure(p,o,{attempt:u,statusClass:c},"session_claim"),p}finally{a.clear()}}reportSessionCreateFailure(e,t,r,i="session_create"){if(!(e instanceof l.FloPayError&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let s=(0,l.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(this.directTelemetry?.performance({stage:i,durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:i==="session_claim"?"session_claim":"session_create",statusClass:s.statusClass,attempt:r.attempt}),e instanceof l.FloPayError&&e.type==="validation_error"||e instanceof l.FloPayError&&Se(e.statusCode)){this.directTelemetry?.terminal({outcome:"validation_rejected",stage:i,requestCategory:i==="session_claim"?"session_claim":"session_create",...e.type==="validation_error"?{}:{statusClass:"4xx"}});return}e instanceof l.FloPayError&&e.code==="session_auto_completed"||this.directTelemetry?.error({...s,stage:i,requestCategory:i==="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(),i=t?.paymentMethodCategory??"saved";this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:i});let s=t?.timeoutMs??z,o=Date.now()+s,a=new AbortController,d=!1,c,u=setTimeout(()=>{c=setTimeout(()=>{d=!0,a.abort()},_e)},s),y=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?y():t?.signal?.addEventListener("abort",y,{once:!0});let p=this.clampRetryAfterMs(t?.initialDelayMs??Te),m=0;try{if(t?.statusUrl){let h=await this.waitForCheckoutStatus(e,{initialDelayMs:p,timeoutMs:s,nonce:t.nonce,statusUrl:t.statusUrl,pollAfterAction:t.continueAfterActionRequired,signal:a.signal});if(h){let g=await this.resolveCheckoutSessionStatus(e,h,t.nonce,a.signal,()=>d);return this.reportRecoveryCompleted(r,i,t.challengeAttemptId),g}}for(;;){let h=o-Date.now();if(h<=0)throw R();if(p>0){try{m+=1,this.telemetryHooks?.onRetry?.("session_read",m),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:i,attempt:m})}catch{}if(await j(Math.min(p,h),a.signal),Date.now()>=o)throw R()}let g=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,a.signal),C=g.data.session?.status;if(C==="authorized"||C==="complete"||C==="expired")return this.reportRecoveryCompleted(r,i,t?.challengeAttemptId),g;if(Date.now()>=o)throw R();p=this.clampRetryAfterMs(Math.max(p*2,be))}}catch(h){let g=d&&re(h)?R():h;throw this.reportDirectFailure(g,"RECOVERY_FAILED","recovery","session_read",i),g}finally{clearTimeout(u),clearTimeout(c),t?.signal?.removeEventListener("abort",y)}}reportRecoveryCompleted(e,t,r){let i={stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t};if(this.directTelemetry?.log({name:"operation.recovery.completed",...i}),r)try{this.directTelemetry?.beginThreeDsChallenge({attemptId:r}).record("recovery_read_completed",{evidenceBasis:"server_status"})}catch{}this.directTelemetry?.performance({...i,durationMs:Math.max(0,this.telemetryTimestamp()-e),durationMode:"machine"})}async resolveCheckoutSessionStatus(e,t,r,i,s){let o=t.latestTransactionAttempt;if(this.rememberReportedFailure(e,t),o?.result==="DECLINE"){let c=o.code===l.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE;throw new l.FloPayError(c?l.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"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 mt("Payment could not be completed. Please try again.",o?.code??"payment_processing_error");let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,r,i)}catch(c){if(!s?.()||!re(c))throw c;a={providers:[],mode:"tokenize",data:{},raw:t}}let d=a.data.session;return d&&o?.result==="SUCCESS"?{...a,data:{...a.data,session:{...d,status:"complete"}}}:d&&o?.result==="AUTHORIZED"?{...a,data:{...a.data,session:{...d,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:d&&t.status==="completed"?{...a,data:{...a.data,session:{...d,status:"complete"}}}:d&&t.status==="authorized"?{...a,data:{...a.data,session:{...d,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:d&&t.status==="expired"?{...a,data:{...a.data,session:{...d,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??z,i=Date.now()+r,s=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let o=i-Date.now();if(o<=0||s>0&&(await j(Math.min(s,o),t.signal),Date.now()>=i))throw R();let a=i-Date.now();if(a<=0)throw R();let d=new AbortController,c,u=t.signal?new Promise((_,f)=>{c=f}):null,y=()=>{d.abort(t.signal?.reason),c?.(t.signal?.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))};t.signal?.aborted?y():t.signal?.addEventListener("abort",y,{once:!0});let p,m=t.signal?null:new Promise((_,f)=>{p=setTimeout(()=>{f(R()),d.abort()},a+_e)}),h;try{let _=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,d.signal);h=await Promise.race([_,m,u].filter(f=>f!==null))}finally{p!==void 0&&clearTimeout(p),t.signal?.removeEventListener("abort",y)}if(!h)return null;let g=Ce(h.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,h,t.submittedIntentId);if(h.status==="completed"||h.status==="authorized"||h.status==="expired"||h.status==="voided")return g?{...h,latestTransactionAttempt:null}:h;let C=h.latestTransactionAttempt?.result,v=t.pollAfterAction===!0&&C==="ACTION_REQUIRED";if(!g&&C!==void 0&&C!=="PENDING"&&!v)return h;s=this.clampRetryAfterMs(Math.max(s*2,be))}}isOwnFailedAttempt(e,t,r){let i=t.latestTransactionAttempt?.providerIntentId??null;return r!==void 0?i===r:i===null?!0:!ft(t.uuid||e,i)}rememberReportedFailure(e,t){let r=t.latestTransactionAttempt;!Ce(r)||!r.providerIntentId||vt(t.uuid||e,r.providerIntentId)}async fetchCheckoutStatus(e,t,r,i){let s=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,o=s;if(r)try{let u=new URL(r,`${this.baseUrl}/`),y=new URL(s);u.origin===y.origin&&(o=u.toString())}catch{}let a={[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION};t&&(a["x-checkout-session-token"]=t);let d=await H(o,{headers:a,signal:i});if(d.status===404||d.status===405)return null;if(!d.ok)throw await w(d,"Failed to get checkout session status");let c=await d.json();return U(c.data)&&"latestTransactionAttempt"in c.data?c.data:null}normalizeRawSession(e){let t=e.gateways??{},r=[],i={session:this.toCheckoutSession(e)},s=t.stripe;if(s?.publishableKey){r.push("stripe");let d=[e.stripeClientSecret,s.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);i.stripe={clientSecret:d??"",publishableKey:s.publishableKey??void 0,paypalPublishableKey:s.paypalPublishableKey??void 0,environment:s.environment,enabledPaymentMethods:Array.isArray(s.enabledPaymentMethods)?s.enabledPaymentMethods.filter(c=>typeof c=="string"):void 0}}let o=t.paypal;return o?.publishableKey&&(r.push("paypal"),i.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:i,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],r=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),i=t.reduce((c,u)=>c+(u.overrideAmount??u.totalAmount??0),0),s=r?e.totalAmount:i,o=Math.round(s*100),a=e.currency??t[0]?.currency??"USD",d="payment";return e.checkoutMode==="setup"?d="setup":t.some(c=>c.type==="subscription")&&(d="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:d,status:this.toCheckoutSessionStatus(e.status),amount:o,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:(0,l.normalizeCheckoutFailureOutcome)(e.outcome)??(0,l.normalizeCheckoutFailureOutcome)(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}:{},...dt(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(ct)}:{},buyerIdentified:e.buyerIdentified,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(c=>({...c,totalAmount:typeof c.totalAmount=="number"?c.totalAmount:void 0,overrideAmount:typeof c.overrideAmount=="number"?c.overrideAmount:null,currency:typeof c.currency=="string"?c.currency:void 0,metadata:c.metadata??null})),successUrl:e.successUrl,cancelUrl:e.cancelUrl,coupons:e.coupons,subtotalAmount:e.subtotalAmount,discountAmount:e.discountAmount,totalAmount:e.totalAmount,createdAt:e.createdAt,gateways:e.gateways,accountData:e.accountData,tagsData:e.tagsData}}toVaultBlock(e){let t=At(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 i=await e.json().catch(()=>null),s=this.toCheckoutProcessingPending(i,e,t);return this.resolveCheckoutProcessing(s,t,r)}async resolveCheckoutProcessing(e,t,r){let i=r?.pollTimeoutMs??z,s=Date.now()+i;if(e.statusUrl){let a=await this.waitForCheckoutStatus(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:i,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:s-Date.now(),nonce:r?.nonce,paymentMethodCategory:r?.paymentMethodCategory});return this.toProcessResponseFromSession(o,t)}async toProcessResponseFromStatus(e,t,r){let i=e.latestTransactionAttempt?.result,s={[ht]:pt},o={"Content-Type":"application/json",...s};if(e.status==="completed"||i==="SUCCESS")return new Response(null,{status:204,statusText:"No Content",headers:s});if(e.status==="authorized"||i==="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),i==="DECLINE"){let a=e.latestTransactionAttempt,d=a?.code===l.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE,c=a?.declineReason??void 0;return new Response(JSON.stringify({type:c??"authorization_declined",message:d?l.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.",code:a?.code??c??"authorization_declined",...c?{declineCode:c}:{}}),{status:400,headers:o})}if(i==="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(i==="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(i==="ERROR"||e.status==="voided")return new Response(JSON.stringify({type:"unknown",code:e.latestTransactionAttempt?.code??"payment_processing_error",message:ut(e)??"Payment could not be completed. Please try again."}),{status:500,headers:o});throw R()}async reconcileProcessPayment(e,t){let r=t?.pollTimeoutMs??z,i=Date.now()+r,s=null;try{s=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:r,nonce:t?.nonce,submittedIntentId:t?.submittedIntentId})}catch(d){if(this.reportDirectFailure(d,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),d instanceof l.FloPayError&&d.code==="checkout_processing_timeout")throw d}if(s)return this.toProcessResponseFromStatus(s,e,t?.nonce);let o=i-Date.now();if(o<=0)throw R();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 l.FloPayError(r?"Authorization has expired.":"Checkout session has expired.","api_error",{code:r?"authorization_expired":"checkout_session_expired"})}throw R()}toCheckoutProcessingPending(e,t,r){let i=t.headers.get("Retry-After"),s=i===null||i.trim()===""?void 0:Number(i),o=s!==void 0&&Number.isFinite(s)?s*1e3:void 0;return{type:"checkout_processing",sessionId:M(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs(Rt(e,"retryAfterMs")??o??Te),statusUrl:M(e,"statusUrl"),sessionUrl:M(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,Tt))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??(0,l.foldIntoProducts)(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let i=t.products!==void 0,s=(0,l.resolveSessionCurrency)(t.currency,i?void 0:t.items,i?void 0:t.subscriptions,r);Z(e,{currency:s??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??s??void 0}))})}mergeCachedDisplayData(e){let t=ae(e.uuid),r=new Map,i=o=>o?`code:${o}`:void 0;for(let o of t?.products??[]){let a=i(o.code);a&&r.set(a,o)}let s=(e.products??[]).map(o=>{let a=i(o.code),d=a?r.get(a):void 0;return{...o,name:o.name??d?.name??null,totalAmount:o.totalAmount??d?.totalAmount,overrideAmount:o.overrideAmount??d?.overrideAmount,currency:o.currency??d?.currency}});return{...e,currency:e.currency??t?.currency,products:s}}};A.activeVaultCaptureRequests=new Map,A.pendingThreeDsAbandonReports=new Map;var D=A;var T=require("@flopay/shared");var $=require("@flopay/shared");function De(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 G=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=(0,$.resolveCardFieldsTimeoutMs)(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 s of Array.from(e.querySelectorAll("script[src], iframe[src]"))){let o=De(s.getAttribute("src"));if(o&&t.add(o),s.tagName==="SCRIPT"){let a=()=>this.fail("load_error");s.addEventListener("error",a),r.push(()=>s.removeEventListener("error",a))}}let i=s=>{let o=De(s.blockedURI);o&&t.has(o)&&this.fail("blocked")};document.addEventListener("securitypolicyviolation",i),r.push(()=>document.removeEventListener("securitypolicyviolation",i)),this.detach=()=>{for(let s of r)s()}}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))(0,$.invokeMerchantCallback)(()=>t(e))}};var Vt=4,W="flopay-vault",Bt=3e4,zt=T.THREE_DS_CHALLENGE_WINDOW_MS+Bt,Ht="Card authentication timed out.",Fe={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 jt(n){return n.class==="lifecycle"?n.name:n.class==="technical_error"?n.code:n.class==="expected_outcome"?n.outcome:"sdk.performance"}function F(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:jt(n),data:e})}catch{}}function L(n,e){return(0,T.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var Kt=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function Gt(n){return typeof n=="string"&&Kt.has(n)?n:"unknown"}var $t=new Set(["verification_failed","verification_expired"]);function Yt(n){return n==null?!0:typeof n=="string"&&$t.has(n)}var Wt="vault_mount";function Jt(n){return n.failureStage===Wt}function ne(n,e){return n&&!Jt(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:Gt(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function Oe(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 Qt(n,e,t,r="checkout"){let{type:i}=n;if(i==="complete"||i==="decline")return(0,T.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:Oe(n,t,r),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(i==="error"){let a=ne(e,n);return(0,T.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[s,o]=Fe[i];return L(s,o)}function Xt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===W&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function Zt(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 er(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 tr(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===W&&e.type==="validation"&&Array.isArray(e.messages)}function rr(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===W&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}function nr(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===W&&e.type==="fields_interactive"}function ir(n){let e=n.capabilities;return Array.isArray(e)&&e.includes("fields_interactive")}var sr=["number","expiry","cvv","name"];function or(n){if(n===null||typeof n!="object")return;let e=n,t={};for(let r of sr){let i=e[r];typeof i=="string"&&(t[r]=i)}return t}var Y=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 G({timeoutMs:e.cardFieldsTimeoutMs,now:()=>this.telemetryReporter?.now?.()??S(),report:r=>this.reportCardFields(r)}),this.ownsTelemetryReporter=!t&&e.telemetry!==!1,this.telemetryReporter=t?.reporter??(this.ownsTelemetryReporter?new k({billingApiUrl:(0,T.resolveBillingApiUrl)(e.billingApiUrl),sdkVersion:T.SDK_VERSION}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new k({billingApiUrl:(0,T.resolveBillingApiUrl)(this.config.billingApiUrl),sdkVersion:T.SDK_VERSION}));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?.()??S(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,this.cardFields.begin(),typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),new T.FloPayError("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 T.FloPayError("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(i){throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),i}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postCardBrandIcons(),this.postCardFieldLabels(),this.postCardFieldPlaceholders(),this.postSubmitLabel(),F(L("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?.()??S())-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 i of r){let s=document.createElement("script");for(let o of Array.from(i.attributes))s.setAttribute(o.name,o.value);s.text=i.text,i.replaceWith(s)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let r=t.data;if(rr(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(tr(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let c=r.messages.filter(u=>typeof u=="string"&&u.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:c||void 0});return}if(nr(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let c=typeof r.sessionId=="string"?r.sessionId:void 0;if(this.config.sessionId&&c&&c!==this.config.sessionId)return;this.cardFields.ready();return}if(!Xt(r)||this.messageToken&&r.messageToken!==this.messageToken)return;let i=this.config.sessionId,s=typeof r.sessionId=="string"?r.sessionId:void 0;if(i&&s&&s!==i||(r.type==="complete"||r.type==="decline")&&i&&s!==i)return;let o=er(r.paymentMethod),a=Zt(r.vaultOutcome),d={...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?.()??S()),this.isVerificationStateError(r)?(F(L("operation.state_transition","vault_mount")),this.telemetryReporter?.log({name:"operation.state_transition",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})):(F(Qt(r,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(r),r.type==="error"&&ne(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(),ir(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,d)};this.messageHandler=e,window.addEventListener("message",e)}isVerificationStateError(e){return e.type==="error"&&this.verificationRequired&&!this.submissionStarted&&Yt(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:Oe(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="error"){let o=ne(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[i,s]=Fe[r];t.log({name:i,stage:s,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=(0,T.buildCardFieldLabelsPayload)(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:i,expectedOrigin:s}=this;!r||!i||!s||this.postToHostedWindow({source:"flopay-vault-host",type:"cardFieldLabels",sessionId:r,messageToken:i,...e===void 0?{}:{show:e},...t===void 0?{}:{labels:{...t}}},s)}setCardFieldPlaceholders(e){let t=or(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:i}=this;e===void 0||!t||!r||!i||this.postToHostedWindow({source:"flopay-vault-host",type:"cardFieldPlaceholders",sessionId:t,messageToken:r,placeholders:{...e}},i)}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:i}=this;e===void 0||!t||!r||!i||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:t,messageToken:r,label:e},i)}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=ue(this.beginActionChallengeAttempt()),r=me(e),i=!1,s=h=>{if(i)return;let g=pe(h,r);g&&(i=!0,t.record("policy_violation",{reason:g,evidenceBasis:"parent_csp_event"}))},o=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},a={telemetry:t,loaded:!1,detach:()=>{document.removeEventListener("securitypolicyviolation",s),window.removeEventListener("pagehide",o)}};this.actionChallenge=a,this.lastChallengeTelemetry=t,t.record("handoff_planned"),te(e)==="invalid"&&t.record("action_invalid",{reason:"invalid_url"}),document.addEventListener("securitypolicyviolation",s),window.addEventListener("pagehide",o);let d=document.createElement("div");d.setAttribute("data-flopay-action-required","1"),d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-label","Card authentication"),d.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let c=document.createElement("iframe");c.setAttribute("title","Card authentication"),c.setAttribute("allow","payment"),c.tabIndex=0,c.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),c.addEventListener("load",()=>{a.loaded||(a.loaded=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"}))}),c.src=e,d.appendChild(c);let u=document.createElement("button");u.type="button",u.setAttribute("aria-label","Close card authentication"),u.textContent="\xD7",u.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(";"),u.addEventListener("click",()=>this.abandonActionRequiredOverlay()),d.appendChild(u),d.addEventListener("click",h=>{h.target===d&&this.abandonActionRequiredOverlay()});let y=0,p=h=>{let g=h.data,C=!!g&&typeof g=="object"&&g.source==="flopay-vault-3ds-return";if(h.source!==c.contentWindow){C&&y<Vt&&(y+=1,t.record("return_rejected",{reason:"untrusted_source",evidenceBasis:"message_origin_check"}));return}C&&(t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),F(L("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",p),this.threeDsReturnHandler=p,t.record("render_attempted");try{document.body.appendChild(d)}catch(h){throw t.record("render_failed"),this.hideActionRequiredOverlay(),this.actionOverlayPreviousFocus=null,h}t.record("container_attached"),t.record("navigation_assigned");let m=he(d);m&&t.record("container_visibility",{reason:m,evidenceBasis:"parent_computed_style"}),this.actionOverlay=d,c.focus(),this.armActionRequiredTimeout(),F(L("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},zt)}reportChallengeAbandoned(){F((0,T.buildTelemetryTerminalEvent)({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:Ht})}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 D((0,T.resolveBillingApiUrl)(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`}};var ar=["setup_intent","setup_intent_client_secret","redirect_status"];function xe(){if(typeof window>"u")return null;let n=new URLSearchParams(window.location.search);return!n.has("setup_intent")||!n.has("redirect_status")?null:{failed:n.get("redirect_status")==="failed"}}function Ue(){if(typeof window>"u")return;let n=new URL(window.location.href),e=!1;for(let t of ar)n.searchParams.has(t)&&(n.searchParams.delete(t),e=!0);e&&window.history.replaceState(window.history.state,"",n.toString())}0&&(module.exports={PaymentAPI,PciVaultCardCapture,clearSetupRedirectParams,readSetupRedirectReturn});
|
package/dist/card-setup.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{q as a,s as n}from"./chunk-
|
|
1
|
+
import{q as a,s as n}from"./chunk-5OENCIZW.mjs";var i=["setup_intent","setup_intent_client_secret","redirect_status"];function o(){if(typeof window>"u")return null;let e=new URLSearchParams(window.location.search);return!e.has("setup_intent")||!e.has("redirect_status")?null:{failed:e.get("redirect_status")==="failed"}}function u(){if(typeof window>"u")return;let e=new URL(window.location.href),t=!1;for(let r of i)e.searchParams.has(r)&&(e.searchParams.delete(r),t=!0);t&&window.history.replaceState(window.history.state,"",e.toString())}export{a as PaymentAPI,n as PciVaultCardCapture,u as clearSetupRedirectParams,o as readSetupRedirectReturn};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/** The events the runtime relays to the wrapper, with the payloads the 1.x checkout emitted. */
|
|
2
|
+
export type CheckoutRuntimeEventName = 'complete' | 'decline' | 'error' | 'cancel' | 'instruments' | 'cardFieldsReady' | 'cardFieldsFailed';
|
|
3
|
+
export interface CheckoutRuntimeEvent {
|
|
4
|
+
name: CheckoutRuntimeEventName;
|
|
5
|
+
payload?: unknown;
|
|
6
|
+
}
|
|
7
|
+
/** What a wrapper hands the runtime to mount one checkout. */
|
|
8
|
+
export interface CheckoutRuntimeMountOptions {
|
|
9
|
+
publishableKey: string;
|
|
10
|
+
/** A session the merchant's server created. */
|
|
11
|
+
sessionId?: string;
|
|
12
|
+
/** The session-bound token for `sessionId`. */
|
|
13
|
+
nonce?: string;
|
|
14
|
+
/**
|
|
15
|
+
* An inline-created session, used when no `sessionId` is given. It is the body of the
|
|
16
|
+
* billing API's `POST /v1/checkouts/sessions` request in the API's own wire shape
|
|
17
|
+
* (`currency`, `products`, `successUrl`, `cancelUrl`, `accountData`, `couponCodes` and so
|
|
18
|
+
* on), and the runtime sends it as given. It is not the 1.x SDK's session draft: the runtime
|
|
19
|
+
* does not fold `items` or `subscriptions` into `products`, resolve the currency or add
|
|
20
|
+
* `clientId`, `checkoutVersion` or `checkoutMode`. The runtime asks the API for the expanded
|
|
21
|
+
* session (`?expand=true`) and reads the session back when the API returns only its id.
|
|
22
|
+
*/
|
|
23
|
+
createSession?: Record<string, unknown>;
|
|
24
|
+
appearance?: Record<string, unknown>;
|
|
25
|
+
/** Merchant wording overrides, applied over the strings the API returns. */
|
|
26
|
+
strings?: Record<string, string>;
|
|
27
|
+
onEvent?: (event: CheckoutRuntimeEvent) => void;
|
|
28
|
+
}
|
|
29
|
+
/** The options a mounted checkout accepts after it is mounted. */
|
|
30
|
+
export type CheckoutRuntimeUpdateOptions = Partial<Pick<CheckoutRuntimeMountOptions, 'appearance' | 'strings' | 'onEvent'>>;
|
|
31
|
+
export interface CheckoutRuntimeHandle {
|
|
32
|
+
update(options: CheckoutRuntimeUpdateOptions): void;
|
|
33
|
+
unmount(): void;
|
|
34
|
+
}
|
|
35
|
+
/** The object the runtime script registers as `globalThis.FloPayCheckoutRuntime`. */
|
|
36
|
+
export interface CheckoutRuntime {
|
|
37
|
+
mount(container: HTMLElement, options: CheckoutRuntimeMountOptions): CheckoutRuntimeHandle;
|
|
38
|
+
}
|
|
39
|
+
/** A load, ready or failure signal from the runtime, always tied to its checkout session. */
|
|
40
|
+
export interface CheckoutRuntimeTelemetryEvent {
|
|
41
|
+
name: 'runtime.load' | 'runtime.ready' | 'runtime.failed';
|
|
42
|
+
checkoutSessionId: string;
|
|
43
|
+
/** The session's card gateway, exactly as the API names it, known to the runtime or not. */
|
|
44
|
+
cardGateway?: string;
|
|
45
|
+
reason?: string;
|
|
46
|
+
}
|
|
47
|
+
/** The runtime's own configuration. Wrappers never supply any of it. */
|
|
48
|
+
export interface CheckoutRuntimeConfig {
|
|
49
|
+
/** The Flo-origin page the runtime mounts as the checkout frame. */
|
|
50
|
+
frameUrl: string;
|
|
51
|
+
/** The API host every checkout request goes to. */
|
|
52
|
+
apiHost: string;
|
|
53
|
+
onTelemetry?: (event: CheckoutRuntimeTelemetryEvent) => void;
|
|
54
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { CheckoutRuntime, CheckoutRuntimeConfig } from './contract.js';
|
|
2
|
+
/**
|
|
3
|
+
* Creates the checkout runtime from its own configuration: the Flo-origin frame page and the
|
|
4
|
+
* API host every checkout request goes to. Wrappers never supply either.
|
|
5
|
+
*/
|
|
6
|
+
export declare function createCheckoutRuntime(config: CheckoutRuntimeConfig): CheckoutRuntime;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { CheckoutRuntime } from './checkout-runtime/contract.js';
|
|
2
|
+
/** Options for {@link loadCheckoutRuntime}. */
|
|
3
|
+
export interface LoadCheckoutRuntimeOptions {
|
|
4
|
+
/** The runtime script, served from the Flo origin. */
|
|
5
|
+
runtimeUrl: string;
|
|
6
|
+
/** How long the runtime has to register itself. Defaults to 10 seconds. */
|
|
7
|
+
timeoutMs?: number;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Loads the Flo-hosted checkout runtime script and resolves with the runtime it registers as
|
|
11
|
+
* `globalThis.FloPayCheckoutRuntime`. It holds no checkout logic: whatever the script registers
|
|
12
|
+
* is what the wrapper mounts. A script that cannot load, registers nothing, or does not register
|
|
13
|
+
* within `timeoutMs` (10 seconds by default) rejects with a `network_error` {@link FloPayError}
|
|
14
|
+
* (`runtime_load_failed` or `runtime_load_timeout`) the merchant can handle, and the next call
|
|
15
|
+
* tries again with a fresh script.
|
|
16
|
+
*/
|
|
17
|
+
export declare function loadCheckoutRuntime(options: LoadCheckoutRuntimeOptions): Promise<CheckoutRuntime>;
|