@flopay/js 1.20.15 → 2.0.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 +108 -339
- package/dist/card-setup.cjs +1 -1
- package/dist/card-setup.d.ts +6 -11
- package/dist/card-setup.mjs +1 -1
- package/dist/checkout-runtime/contract.d.ts +43 -1
- package/dist/checkout-runtime/provider-registry.d.ts +6 -0
- package/dist/checkout-runtime/providers/provider-rules.d.ts +88 -0
- package/dist/checkout-runtime/providers/session-gateways.d.ts +183 -0
- package/dist/checkout-runtime-payment-methods.d.ts +37 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +0 -9
- package/dist/index.mjs +1 -1
- package/dist/payment-api.d.ts +2 -2
- package/dist/pci-vault-card-capture.d.ts +2 -1
- package/dist/saved-card-action.d.ts +3 -5
- package/dist/stripe-method-names.d.ts +6 -0
- package/package.json +3 -4
- package/dist/chunk-YGLB52ZW.mjs +0 -1
- package/dist/flopay.d.ts +0 -63
- package/dist/load.d.ts +0 -24
- package/dist/stripe-adapter.d.ts +0 -13
- package/dist/telemetry-bridge.d.ts +0 -18
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { PaymentMethodGroupLayout } from '@flopay/shared';
|
|
2
2
|
import { FloPayError } from '@flopay/shared';
|
|
3
3
|
import type { CheckoutRuntimeEvent, CheckoutRuntimeLayout } from './checkout-runtime/contract.js';
|
|
4
|
-
import type { DescriptorRead } from './checkout-runtime/method-descriptors.js';
|
|
4
|
+
import type { DescriptorRead, PaymentMethodDescriptor } from './checkout-runtime/method-descriptors.js';
|
|
5
5
|
import type { JsonRecord } from './checkout-runtime/provider-kit.js';
|
|
6
6
|
export declare function isCompleteStatus(status: unknown): boolean;
|
|
7
7
|
/**
|
|
@@ -72,6 +72,30 @@ export declare function settleProviderReturn(found: ProviderReturn, context: {
|
|
|
72
72
|
outcomes: Outcomes;
|
|
73
73
|
active: () => boolean;
|
|
74
74
|
}): void;
|
|
75
|
+
/**
|
|
76
|
+
* The merchant's hide list (contract 2.5.0) as the runtime applies it: the names in it, so a value
|
|
77
|
+
* that is not a list hides nothing.
|
|
78
|
+
*/
|
|
79
|
+
export declare function readHiddenPaymentMethods(value: unknown): ReadonlySet<string>;
|
|
80
|
+
/**
|
|
81
|
+
* Whether the merchant hid this offered method: it is hidden when its method or its group is
|
|
82
|
+
* listed, and `card` hides either card surface. The wrappers list `card`, the PayPal method, the
|
|
83
|
+
* two wallet methods and `apms`, so a wallet is hidden on its own while the other stays. The rule
|
|
84
|
+
* reads only the method and the group, never the provider, and only removes what the session
|
|
85
|
+
* offers.
|
|
86
|
+
*/
|
|
87
|
+
export declare function isHiddenMethod(descriptor: PaymentMethodDescriptor, hidden: ReadonlySet<string>): boolean;
|
|
88
|
+
/**
|
|
89
|
+
* The merchant's allow list (contract 2.6.0) as the runtime applies it: the names in it, read as
|
|
90
|
+
* the hide list's are, or `undefined` when there is no list to apply. A value that is not a list,
|
|
91
|
+
* an empty list, or one with no name in it allows every offered method, as before.
|
|
92
|
+
*/
|
|
93
|
+
export declare function readEnabledPaymentMethods(value: unknown): ReadonlySet<string> | undefined;
|
|
94
|
+
/**
|
|
95
|
+
* Whether the merchant lets the checkout show a card surface: `card` is not hidden, and is
|
|
96
|
+
* allowed when there is an allow list. A method must be allowed and not hidden to be mounted.
|
|
97
|
+
*/
|
|
98
|
+
export declare function cardSurfaceAllowed(hidden: ReadonlySet<string>, enabled: ReadonlySet<string> | undefined): boolean;
|
|
75
99
|
/**
|
|
76
100
|
* Whether Flo's hosted card form is the session's card surface: for a 1.x answer, and for an
|
|
77
101
|
* advertisement that selects `hosted-card` or names no card surface at all. A `provider-frame`
|
|
@@ -93,6 +117,18 @@ export interface PaymentMethodsContext {
|
|
|
93
117
|
/** The resolved layout, when the API has already answered. */
|
|
94
118
|
initialLayout?: PaymentMethodGroupLayout;
|
|
95
119
|
strings: () => Record<string, string> | undefined;
|
|
120
|
+
/** The methods the merchant hid (contract 2.5.0), read by `readHiddenPaymentMethods`. */
|
|
121
|
+
hidden?: ReadonlySet<string>;
|
|
122
|
+
/**
|
|
123
|
+
* The methods the merchant allows (contract 2.6.0), read by `readEnabledPaymentMethods`;
|
|
124
|
+
* `undefined` allows every offered method.
|
|
125
|
+
*/
|
|
126
|
+
enabled?: ReadonlySet<string>;
|
|
127
|
+
/**
|
|
128
|
+
* An order the merchant already has (contract 2.6.0), handed to every adapter as
|
|
129
|
+
* `resumeOrderId`: the adapter whose button pays by order resumes it instead of creating one.
|
|
130
|
+
*/
|
|
131
|
+
resumeOrderId?: string;
|
|
96
132
|
}
|
|
97
133
|
export interface PaymentMethodsSurface {
|
|
98
134
|
setLayout(layout: PaymentMethodGroupLayout): void;
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var xe=Object.defineProperty;var zt=Object.getOwnPropertyDescriptor;var jt=Object.getOwnPropertyNames;var Ht=Object.prototype.hasOwnProperty;var Kt=(r,e)=>{for(var t in e)xe(r,t,{get:e[t],enumerable:!0})},Gt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of jt(e))!Ht.call(r,i)&&i!==t&&xe(r,i,{get:()=>e[i],enumerable:!(n=zt(e,i))||n.enumerable});return r};var $t=r=>Gt(xe({},"__esModule",{value:!0}),r);var En={};Kt(En,{FloPay:()=>ye,PaymentAPI:()=>G,PciVaultCardCapture:()=>X,SESSION_CREATE_TELEMETRY:()=>ze,StripeAdapter:()=>ie,beginSavedCardChallengeTelemetry:()=>Lt,cacheSessionDisplayData:()=>J,clearSessionDisplayData:()=>Te,completeSavedCardNextAction:()=>Bt,createCheckoutSession:()=>it,createCheckoutSessionWithRetries:()=>lt,createSavedCardActionAbortedError:()=>ge,dropThirdPartyOnlyError:()=>Vt.dropThirdPartyOnlyError,getSessionDisplayData:()=>Ce,loadCheckoutRuntime:()=>Ye,loadFloPay:()=>Ot,runSavedCardChallenge:()=>$e,toStripeAppearance:()=>se.toStripeAppearance,toStripeAppearanceTheme:()=>se.toStripeAppearanceTheme});module.exports=$t(En);var Vt=require("@flopay/shared");var Le=require("@flopay/shared"),Yt="FloPayCheckoutRuntime",Wt=1e4,Ue=new Map;function Jt(r){return typeof r=="object"&&r!==null&&typeof r.mount=="function"}function Oe(r){return new Le.FloPayError(r==="runtime_load_timeout"?"The checkout runtime did not load in time.":"The checkout runtime failed to load.","network_error",{code:r})}function Qt(r,e){return new Promise((t,n)=>{let i=document.createElement("script"),s=!1,o=u=>{s||(s=!0,clearTimeout(c),i.removeEventListener("load",a),i.removeEventListener("error",l),u instanceof Le.FloPayError?(Ue.delete(r),i.remove(),n(u)):t(u))},a=()=>{let u=Reflect.get(globalThis,Yt);o(Jt(u)?u:Oe("runtime_load_failed"))},l=()=>o(Oe("runtime_load_failed")),c=setTimeout(()=>o(Oe("runtime_load_timeout")),e);i.addEventListener("load",a),i.addEventListener("error",l),i.async=!0,i.src=r,document.head.appendChild(i)})}function Ye(r){let{runtimeUrl:e,timeoutMs:t=Wt}=r,n=Ue.get(e);if(n!==void 0)return n;let i=Qt(e,t);return Ue.set(e,i),i}var T=require("@flopay/shared");function le(r){return typeof r=="string"&&r.trim()?r:void 0}function ce(r){if(typeof r=="string")return r.trim()?r:void 0;if(Array.isArray(r))return r.filter(t=>typeof t=="string"&&t.trim().length>0).join("; ")||void 0}function L(r=12e3){let e=Number.isFinite(r)&&r>=0?r:12e3,t=new AbortController,n=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(n)}}function Xt(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function te(r,e){let t=150*2**r,n=Math.round(t*(.75+Math.random()*.5));return new Promise((i,s)=>{let o,a=()=>e.removeEventListener("abort",l),l=()=>{o!==void 0&&clearTimeout(o),a(),s(Xt())};if(e.aborted){l();return}o=setTimeout(()=>{a(),i()},n),e.addEventListener("abort",l,{once:!0})})}var Zt="flopay_session_display:";var fe=new Map;function ve(r){return`${Zt}${r}`}function qe(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function J(r,e,t){if(!r)return;let n=t?.ttlMs??36e5,i={data:e,expiresAt:Date.now()+n},s=qe();if(s)try{s.setItem(ve(r),JSON.stringify(i));return}catch{}fe.set(r,i)}function Ce(r){if(!r)return null;let e=qe();if(e)try{let n=e.getItem(ve(r));if(n){let i=JSON.parse(n);if(i&&typeof i.expiresAt=="number"&&i.expiresAt>Date.now())return i.data;e.removeItem(ve(r))}}catch{}let t=fe.get(r);if(t){if(t.expiresAt>Date.now())return t.data;fe.delete(r)}return null}function Te(r){if(!r)return;fe.delete(r);let e=qe();if(e)try{e.removeItem(ve(r))}catch{}}var k=require("@flopay/shared");var Ne=require("@flopay/shared"),er=32,We=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function tr(){let r=globalThis,e=r[We];if(e instanceof Map)return e;let t=new Map;try{Object.defineProperty(r,We,{configurable:!0,enumerable:!1,writable:!1,value:t})}catch{}return t}function rr(r,e){let t=tr(),n=t.get(r);if(n)return n;for(;t.size>=er;){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(r,i),i}var nr=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),ir=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function Je(r,e={}){let t=(0,Ne.isThreeDsChallengeAttemptId)(e.attemptId)?e.attemptId.toLowerCase():r.newAttemptId(),n=()=>{try{let a=r.now();return Number.isFinite(a)?a:0}catch{return 0}},i=rr(t,n());(e.provider==="stripe"||e.provider==="worldpay")&&(i.provider=e.provider);let s=i.provider,o=(a,l)=>{if(i.terminated&&!ir.has(a))return;let c={attemptId:t,phase:a,attemptSequence:i.nextSequence,elapsedMs:Math.max(0,n()-i.startedAt),provider:s};i.nextSequence+=1,l.reason!==void 0&&(c.reason=l.reason),l.evidenceBasis!==void 0&&(c.evidenceBasis=l.evidenceBasis),l.terminalSource!==void 0&&(c.terminalSource=l.terminalSource),l.providerOutcome!==void 0&&(c.providerOutcome=l.providerOutcome);try{r.emit(c,nr.has(a))}catch{}};return{attemptId:t,record(a,l={}){a==="browser_terminal"||a==="provider_reconciled"||o(a,{reason:l.reason,evidenceBasis:l.evidenceBasis})},terminal(a,l={}){i.terminated||(o("browser_terminal",{terminalSource:a,reason:l.reason,evidenceBasis:l.evidenceBasis}),i.terminated=!0)},reconcile(a){i.reconciled.has(a)||(i.reconciled.add(a),o("provider_reconciled",{providerOutcome:a,evidenceBasis:"provider_fact"}))}}}function de(r){let e=null;try{e=(0,Ne.isThreeDsChallengeAttemptId)(r?.attemptId)?r?.attemptId??null:null}catch{e=null}return{attemptId:e,record(t,n){try{r?.record(t,n)}catch{}},terminal(t,n){try{r?.terminal(t,n)}catch{}},reconcile(t){try{r?.reconcile(t)}catch{}}}}function ue(r){if(typeof r!="string"||r.trim()==="")return"missing";try{let e=new URL(r);return e.protocol==="https:"||e.protocol==="http:"?"valid":"invalid"}catch{return"invalid"}}function Qe(r){return r==="buyer_cancel"||r==="component_unmount"||r==="navigation"?r:"unspecified"}function be(r){try{if(typeof window>"u"||typeof window.getComputedStyle!="function")return null;for(let e=r;e;e=e.parentElement){let t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||t.visibility==="collapse"||t.opacity==="0")return"hidden"}return"visible"}catch{return null}}function _e(r,e){if(!e)return null;try{let t=r,n=String(t.effectiveDirective||t.violatedDirective||"").trim().split(/\s+/)[0],i=null;return n==="frame-src"&&(i="frame_src"),n==="child-src"&&(i="child_src"),!i||typeof t.blockedURI!="string"?null:new URL(t.blockedURI).origin===e?i:null}catch{return null}}function Re(r){try{return ue(r)==="valid"?new URL(r).origin:null}catch{return null}}var sr="/v1/sdk-telemetry/events",we=16,Xe=64,or=1500,Ze=1e3,ar=64,lr="00000000-0000-4000-8000-000000000000",cr={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},dr=48;function H(){try{return globalThis.crypto.randomUUID()}catch{let r=new Uint8Array(16);try{globalThis.crypto.getRandomValues(r)}catch{for(let t=0;t<r.length;t+=1)r[t]=Math.floor(Math.random()*256)}r[6]=(r[6]??0)&15|64,r[8]=(r[8]??0)&63|128;let e=[...r].map(t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}}function ur(r){try{return new TextEncoder().encode(r).byteLength}catch{return r.length}}function mr(r){return JSON.stringify([r.code,r.failureCategory,r.reason,r.stage,r.provider,r.attempt,r.statusClass,r.requestCategory,r.paymentMethodCategory,r.walletType,r.operationOutcome,r.checkoutMode,r.layout,r.inAppBrowser,r.appFamily,r.popupCapability,r.presentationMode,r.terminalReason])}function E(){return globalThis.performance?.now()??0}var A=class{constructor(e){this.ingestionDisabled=!1;this.queue=[];this.sequence=0;this.threeDsChallengeCount=0;this.flushTimer=null;this.flushInFlight=null;this.reportedFailures=new Map;this.checkoutContext={};this.checkoutStartedAt=null;this.destroyed=!1;this.observers=new Set;this.pageExitHandler=()=>{this.drainQueue()};this.visibilityHandler=()=>{typeof document<"u"&&document.visibilityState==="hidden"&&this.flush()};this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0};this.endpoint=`${e.billingApiUrl.replace(/\/+$/,"")}${sr}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=H(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??E,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,k.buildTelemetryLogEvent)({...this.checkoutContext,...e,eventId:H(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=(0,k.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:lr,sequence:0}),n=mr(t),i=this.now();this.pruneReportedFailures(i);let s=this.reportedFailures.get(n);if(s!==void 0&&i>=s&&i-s<Ze){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt,inAppBrowser:e.inAppBrowser,appFamily:e.appFamily,popupCapability:e.popupCapability,presentationMode:e.presentationMode,terminalReason:e.terminalReason});return}this.rememberReportedFailure(n,i),this.enqueue((0,k.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:H(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,k.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:H(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,k.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:H(),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 Je({now:()=>this.now(),newAttemptId:H,emit:(t,n)=>this.recordThreeDsChallenge(t,n)},e)}recordThreeDsChallenge(e,t){if(!this.canCollect()||this.threeDsChallengeCount>=dr)return;let n=(0,k.buildTelemetryLogEvent)({...this.checkoutContext,...e,name:"three_ds.challenge",stage:"three_ds_handoff",eventId:H(),sequence:this.sequence++});if(!(this.queue.length>=Xe)){if(this.threeDsChallengeCount+=1,this.queue.push(n),t){this.drainQueue();return}if(this.queue.length>=we){this.flush();return}this.scheduleFlush()}}now(){try{return this.clock()}catch{return E()}}subscribe(e){return this.destroyed?()=>{}:(this.observers.add(e),()=>this.observers.delete(e))}notify(e){if(!this.destroyed)for(let t of this.observers)try{t(e)}catch{}}pruneReportedFailures(e){for(let[t,n]of this.reportedFailures)(e<n||e-n>=Ze)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=ar;){let n=this.reportedFailures.keys().next();if(n.done)break;this.reportedFailures.delete(n.value)}this.reportedFailures.set(e,t)}setCheckoutContext(e){this.checkoutContext={checkoutMode:e.checkoutMode,layout:e.layout}}beginCheckout(e={}){return this.canCollect()?(this.drainQueue(),this.setCheckoutContext(e),this.sequence=0,this.threeDsChallengeCount=0,this.reportedFailures.clear(),this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0},this.checkoutStartedAt=this.now(),this.checkoutStartedAt):0}enqueue(e){if(this.canCollect()&&!(this.queue.length>=Xe||this.eventCounts[e.class]>=cr[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=we){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,we);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&&(typeof window<"u"&&window.removeEventListener("pagehide",this.pageExitHandler),typeof document<"u"&&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,we);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=(0,k.serializeTelemetryBatch)(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:H()});if(ur(t)>k.TELEMETRY_MAX_BATCH_BYTES)return;let n=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:n?.signal}).then(async l=>{if(l.status!==202)return null;let c=null;try{c=await l.json()}catch{}return c?.status==="disabled"?"disabled":null}).catch(()=>null),o=new Promise(l=>{i=setTimeout(()=>{n?.abort(),l(null)},or)});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)}},et=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),tt=globalThis;tt[et]===void 0&&Object.defineProperty(tt,et,{configurable:!0,enumerable:!1,writable:!1,value:r=>new A(r)});var Be=5,rt=new WeakSet;function pr(r){(typeof r=="object"&&r!==null||typeof r=="function")&&rt.add(r)}function hr(r){return(typeof r=="object"&&r!==null||typeof r=="function")&&rt.has(r)}function yr(r,e){let t=e?.error,n=le(e?.code)??le(t?.code)??`http_${r}`,i=ce(e?.message)??ce(t?.message)??gr(n,r);return new T.FloPayError(i,"api_error",{code:n,statusCode:r})}function gr(r,e){switch(r){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${Be}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${e}).`}}async function nt(r,e,t){let{billingApiUrl:n,checkoutBaseUrl:i,items:s=[],subscriptions:o=[],products:a,account:l,successUrl:c,cancelUrl:u,checkoutMode:h="confirm",captureMethod:p,couponCodes:y=[],checkoutMetadata:m,tagsData:g,redirectParams:C={},setCookie:f=!0,clientId:R,currency:v,utmMetadata:F,idempotencyKey:Y}=r,V=(0,T.resolveIdempotencyKey)(Y);if(y.length>Be)throw new T.FloPayError(`Too many coupon codes \u2014 a checkout session accepts at most ${Be}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let x=a??(0,T.foldIntoProducts)(s,o);(0,T.assertCaptureMethodEligible)({captureMethod:p,products:x});let I=(0,T.resolveSessionCurrency)(v,s,o,x);if(!I)throw new T.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 S={clientId:R,checkoutVersion:T.SDK_VERSION,successUrl:c,cancelUrl:u,currency:I,checkoutMode:h,products:x.map(P=>(0,T.buildProductPayload)(P,I)),accountData:{userId:l.userId,firstName:l.firstName??null,lastName:l.lastName??null,email:l.email,country:l.country??null,gender:l.gender??null,city:l.city??null,state:l.state??null,zip:l.zip??null,addressLine1:l.addressLine1??null,addressLine2:l.addressLine2??null},couponCodes:y};p==="manual"&&(S.captureMethod=p),m!==void 0&&(S.checkoutMetadata=m),g&&(S.tagsData=g),F&&F.length>0&&(S.utmMetadata=F);let Z=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions`,oe={"Content-Type":"application/json"};V&&(oe[T.IDEMPOTENCY_KEY_HEADER]=V);let U,W,ae={method:"POST",headers:oe,body:JSON.stringify(S),signal:e},z;try{t?.startAttempt(),z=await fetch(Z,ae)}catch(P){throw pr(P),P}try{t?.record(z.status)}catch{}U=z.status;try{W=await z.json()}catch{}if(U>=400)throw(0,T.withTelemetryHttpDiagnostics)(yr(U,W),z);if(U===201){let P=W?.data?.uuid,ee=W?.data?.nonce;if(!P)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!ee)throw new T.FloPayError("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(x.length>0||I)&&J(P,{currency:I,products:x.map(_=>({code:_.code??_.providerItemId??_.providerPlanId,type:_.type,name:_.name??_.itemName??_.providerItemName??_.subscriptionName??_.providerPlanName??null,totalAmount:_.totalAmount,overrideAmount:_.overrideAmount,currency:_.currency??I}))});let w=new URL(`${i.replace(/\/+$/,"")}/secure`);w.searchParams.set("id",P);for(let[_,j]of Object.entries(C))w.searchParams.set(_,j);if(f&&typeof window<"u"&&typeof document<"u"){let _=JSON.stringify({origin_url:u}),j=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(_)}; domain=.${j}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(ee)}; domain=.${j}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=w.toString()),{status:201,redirectUrl:w.toString(),nonce:ee}}return U===204?(typeof window<"u"&&(window.location.href=c),{status:204}):{status:U}}async function it(r){let e=ot(r),t=st(e),n=L(r.timeoutMs);try{let i=await nt(r,n.signal,t);return t.commit(),at(e,i),i}catch(i){throw t.commit(),Se(e,i),i}finally{n.clear(),re(e.reporter)}}function st(r){let e=!1,t=r.startedAt,n;return{startAttempt(){t=r.reporter.now()},record(i){n={status:i,durationMs:Math.max(0,r.reporter.now()-t),attempt:r.attempt}},commit(){if(e||!n)return;e=!0;let i=(0,T.telemetryStatusClass)(n.status);r.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:i,attempt:n.attempt}),r.reporter.performance({stage:"session_first_byte",durationMs:n.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:i,attempt:n.attempt})}}}function ot(r){let e=new A({billingApiUrl:r.billingApiUrl,sdkVersion:T.SDK_VERSION,enabled:r.telemetry!==!1}),t=e.now();return e.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:e,startedAt:t,attempt:0}}function at(r,e){let t=(0,T.telemetryStatusClass)(e.status);r.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:t}),r.reporter.performance({stage:"session_create",durationMs:r.reporter.now()-r.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:t,attempt:r.attempt})}function Se(r,e){let{reporter:t}=r,n=(0,T.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(t.performance({stage:"session_create",durationMs:t.now()-r.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:n.statusClass,attempt:r.attempt}),e instanceof T.FloPayError&&e.type==="validation_error"){t.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(n.statusClass==="4xx"){t.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}t.error({...n,stage:"session_create",requestCategory:"session_create"})}function re(r){r.flush().catch(()=>{}).finally(()=>r.destroy())}async function lt(r){let{maxRetries:e=2,...t}=r,n=ot(r),i=st(n);if(!Number.isFinite(e)||!Number.isInteger(e)||e<0||e>=3)throw n.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),re(n.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let s={...t,idempotencyKey:(0,T.resolveIdempotencyKey)(t.idempotencyKey)},o=L(t.timeoutMs),a;for(let l=0;l<=e;l++){n.attempt=l;try{let c=await nt(s,o.signal,i);return i.commit(),at(n,c),o.clear(),re(n.reporter),c}catch(c){a=c;let u=c instanceof Error&&c.name==="AbortError",h=hr(c),p=c instanceof T.FloPayError&&c.code===T.IDEMPOTENCY_IN_PROGRESS_CODE;if((u||h||p)&&!o.signal.aborted&&l<e){n.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:l+1});try{await te(l,o.signal)}catch(y){throw i.commit(),Se(n,y),o.clear(),re(n.reporter),y}continue}throw i.commit(),Se(n,c),o.clear(),re(n.reporter),c}}throw i.commit(),Se(n,a),o.clear(),re(n.reporter),a??new Error("Unknown error during checkout session creation")}var M=require("@flopay/shared");var d=require("@flopay/shared");function fr(r){return r==="on_session"||r==="off_session"}function vr(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function Cr(r){let e=r.vaultOutcome;if(!(!e||e.code!==d.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED))return typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0}var Tr="x-flopay-process-result-source",br="status",Ct=new WeakSet;function _r(r,e){let t=new d.FloPayError(r,"api_error",{code:e,statusCode:500});return Ct.add(t),t}function Rr(r){return typeof r=="object"&&r!==null&&Ct.has(r)}function ct(r){return r?.result==="DECLINE"||r?.result==="ERROR"}var wr=50,Q=new Map;function Sr(r,e){return Q.get(r)?.has(e)===!0}function Ar(r,e){let t=Q.get(r)??new Set;if(t.add(e),Q.delete(r),Q.set(r,t),Q.size>wr){let n=Q.keys().next().value;n!==void 0&&Q.delete(n)}}function kr(r){let e=r?.threeDSecureActionResultTokenId;if(typeof e=="string"&&e.length>0)return e;if(r?.gateway==="paypal"&&r.type!=="paypal_setup_token"&&typeof r.id=="string"&&r.id.length>0)return r.id}var dt=0,ut=500,Ae=15e3,mt=15e3,Er=3e3,Mr=1e4,Ir=1e4;function pe(r){return typeof r=="object"&&r!==null}function K(r,e){return le(r?.[e])}function pt(r,e){return ce(r?.[e])}function Pr(r,e){let t=r?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Ee(r,e){return e?new Promise((t,n)=>{let i=()=>{clearTimeout(s),n(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},s=setTimeout(()=>{e.removeEventListener("abort",i),t()},r);e.aborted?i():e.addEventListener("abort",i,{once:!0})}):new Promise(t=>setTimeout(t,r))}function Ve(r){return r instanceof Error&&r.name==="AbortError"}function D(){return new d.FloPayError(d.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}async function N(r,e){let t=await r.json().catch(()=>null),n=pe(t?.error)?t.error:null,i=pt(t,"message")??pt(n,"message")??e,s=K(t,"code")??K(t,"gatewayErrorCode")??K(n,"code")??`http_${r.status}`;return(0,d.withTelemetryHttpDiagnostics)(new d.FloPayError(i,"api_error",{code:s,statusCode:r.status}),r)}async function Dr(r){if(r.status!==403)return!1;let e=await r.clone().json().catch(()=>null),t=pe(e?.error)?e.error:null;return(K(e,"code")??K(t,"code"))==="verification_required"}function Fr(r){if(!(!pe(r)||typeof r.required!="boolean"))return{required:r.required,provider:"turnstile"}}async function xr(r){let e=r.status===400?await r.clone().json().catch(()=>null):null;return(0,d.classifyPaymentRejection)(r.status,e)}function ht(r){return r===400||r===422}var Me=2;async function ke(r,e,t=Me,n,i){let s;for(let o=0;;o++)try{return i?.(o),await fetch(r,e)}catch(a){if(e?.signal?.aborted||a instanceof Error&&a.name==="AbortError")throw a;if(s=a,o>=t)throw s;try{n?.(o+1)}catch{}await Ee(150*2**o,e?.signal??void 0)}}var Or=2e3,Ur=1e4,Lr=150;async function qr(r){try{let t=(await r.json())?.data?.status;return t==="closed"||t==="not_open"?t:"failed"}catch{return"failed"}}async function yt(r,e,t){let n=new AbortController,i=()=>n.abort();t?.addEventListener("abort",i,{once:!0});let s,o=new Promise(a=>{s=setTimeout(()=>{n.abort(),a("timeout")},Ur)});try{let a=await Promise.race([fetch(r,{...e,signal:n.signal}),o]);return a==="timeout"?"failed":a.status>=500?"retry":a.ok?await qr(a):"failed"}catch{return n.signal.aborted?"failed":"retry"}finally{clearTimeout(s),t?.removeEventListener("abort",i)}}function Nr(r,e){return new Promise(t=>{let n=setTimeout(t,e);r.then(()=>{clearTimeout(n),t()},()=>{clearTimeout(n),t()})})}var gt="stripe-account-switch-v1",ze=Symbol.for("@flopay/js.session-create.telemetry.v1");function Br(r){return r[ze]}function Vr(r){return"now"in r||"onFirstByte"in r||"onSessionCreateFailure"in r||"onRetry"in r}function Tt(r){let e=(0,d.isCardHolderNamePlaceholder)(r.firstName,r.lastName);return{userId:r.userId,firstName:e?null:r.firstName??null,lastName:e?null:r.lastName??null,email:r.email,country:r.country??null,gender:r.gender??null,city:r.city??null,state:r.state??null,zip:r.zip??null,addressLine1:r.addressLine1??null,addressLine2:r.addressLine2??null}}function bt(r,e){e.checkoutMetadata!==void 0&&(r.checkoutMetadata=e.checkoutMetadata),e.tagsData&&(r.tagsData=e.tagsData),e.utmMetadata&&e.utmMetadata.length>0&&(r.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(r.avsCheck=e.avsCheck),e.checkoutType&&(r.checkoutType=e.checkoutType),e.checkoutLayout&&(r.checkoutLayout=e.checkoutLayout),e.avsConfig&&(r.avsConfig=e.avsConfig)}function ft(r){if(typeof r!="string")return;let e=r.trim();return e.length>0?e:void 0}function zr(r){let e={};if(r.country&&(e.country=r.country),!(0,d.isCardHolderNamePlaceholder)(r.firstName,r.lastName)){let t=ft(r.firstName),n=ft(r.lastName);t&&(e.firstName=t),n&&(e.lastName=n)}return Object.keys(e).length>0?e:void 0}function jr(r,e,t){let n={clientId:r.clientId,checkoutVersion:d.SDK_VERSION,successUrl:r.successUrl,cancelUrl:r.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};r.captureMethod==="manual"&&(n.captureMethod=r.captureMethod);let i=zr(r.account);i&&(n.accountData=i),bt(n,r);let s=Hr(t);return s&&(n.routingProducts=s),n}function Hr(r){let e=new Set;for(let t of r){let n=[t.code,t.providerItemId,t.providerPlanId].map(i=>typeof i=="string"?i.trim():"").find(i=>i.length>0);n&&e.add(n)}return e.size>0?Array.from(e,t=>({code:t})):void 0}function vt(r,e,t){return{currency:e,products:t.map(n=>(0,d.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[],accountData:Tt(r.account)}}function Kr(r,e,t){return{currency:e,products:t.map(n=>(0,d.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[]}}function Gr(r){let e={},t=(0,d.isCardHolderNamePlaceholder)(r.firstName,r.lastName);for(let[n,i]of Object.entries(r)){if(t&&n.endsWith("Name")||typeof i!="string")continue;let s=i.trim();s&&(e[n]=s)}return{accountData:e}}function $r(r){return typeof r=="string"?{expiresAt:r}:r===null?{expiresAt:null}:{}}var O=class O{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let n=Vr(t);this.telemetryHooks=n?t:void 0,this.stripeAccountSwitch=!n&&t.stripeAccountSwitch===!0,this.directTelemetry=n||t.telemetry===!1?void 0:new A({billingApiUrl:this.baseUrl,sdkVersion:d.SDK_VERSION})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,n,i,s="unknown"){let o=(0,d.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...o,...Rr(e)?{reason:"capture_failed"}:{},stage:n,requestCategory:i,paymentMethodCategory:s})}reportAccountSnapshotFailure(e,t){let n=(0,d.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED");if(t==="best_effort"&&n.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...n,stage:"processing",requestCategory:"account_snapshot",paymentMethodCategory:"unknown"})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??E()}catch{return E()}}beginDirectTelemetryCheckout(e){!this.directTelemetry||this.directTelemetryCheckoutId===e||(this.directTelemetryCheckoutId=e,this.directTelemetry.beginCheckout())}beginDirectTelemetryOperation(){this.directTelemetry&&(this.directTelemetryCheckoutId=void 0,this.directTelemetry.beginCheckout())}adoptDirectTelemetryCheckout(e){e&&(this.directTelemetryCheckoutId=e)}async getCheckoutSession(e,t){return this.fetchCheckoutSession(e,t)}async fetchCheckoutSession(e,t,n=!0,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 l={[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION};t&&(l["x-checkout-session-token"]=t);let c=!1;try{let u=await ke(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:l,signal:i,cache:"no-store"},Me,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 h=Math.max(0,this.telemetryTimestamp()-o);try{this.telemetryHooks?.onFirstByte?.(h,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:h,durationMode:"machine",requestCategory:"session_read",statusClass:p,attempt:a}),!u.ok)throw await N(u,"Failed to get checkout session");let y=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}),{...y,data:this.mergeCachedDisplayData(y.data)}}catch(u){throw c&&(0,d.markSessionResponseReceived)(u),n&&this.directTelemetry?.error({...(0,d.classifyTelemetryFailure)(u,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),u}}cacheSessionDisplayData(e,t,n){J(e,t,n)}clearSessionDisplayData(e){Te(e)}async getVaultCapture(e,t){let n=`${this.baseUrl}\0${e}\0${t??""}`,i=O.activeVaultCaptureRequests.get(n);if(i!==void 0)return i;let s=O.pendingThreeDsAbandonReports.get(e),o=s===void 0?this.requestVaultCapture(e,t):Nr(s,Or).then(()=>this.requestVaultCapture(e,t));O.activeVaultCaptureRequests.set(n,o);try{return await o}finally{O.activeVaultCaptureRequests.get(n)===o&&O.activeVaultCaptureRequests.delete(n)}}async requestVaultCapture(e,t){let n=new AbortController,i=setTimeout(()=>n.abort(),Ir);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 ke(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:o,signal:n.signal,cache:"no-store"},Me,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 Dr(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 N(a,"Failed to load the secure card form");let l=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(l)}catch(a){let l=n.signal.aborted?new d.FloPayError("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(l,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),l}finally{clearTimeout(i)}}async getUnifiedCheckoutSession(e,t){let n=await this.getCheckoutSession(e,t);return this.normalizeCheckoutSessionResponse(n)}async getUnifiedCheckoutSessionForRecovery(e,t,n){let i=await this.fetchCheckoutSession(e,t,!1,n);return this.normalizeCheckoutSessionResponse(i)}normalizeCheckoutSessionResponse(e){try{let t=this.normalizeRawSession(e.data),n=e.vault;return n&&t.data.session&&(t.data.session.vault=this.toVaultBlock(n)),t}catch(t){throw(0,d.markSessionResponseReceived)(t)}}async processPayment(e,t,n){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 d.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,...l}=t,c=kr(t.tokenizedData),u,h;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(l)}),h=u}catch(p){if(Ve(p))throw this.reportDirectFailure(p,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),p;u=await this.reconcileProcessPayment(t.sessionId,{...n,nonce:o,paymentMethodCategory:i,submittedIntentId:c})}if(!u.ok&&u.status!==202){let p=await xr(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,d.telemetryStatusClass)(u.status),failureCategory:u.status>=500?"server_error":void 0,paymentMethodCategory:i,...(0,d.readTelemetryHttpDiagnostics)(h)}),u}try{let p=await this.resolveProcessResponse(u,t.sessionId,{...n,nonce:o,paymentMethodCategory:i,submittedIntentId:c});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,d.telemetryStatusClass)(p.status),paymentMethodCategory:i}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,d.telemetryStatusClass)(p.status),paymentMethodCategory:i}),p}catch(p){throw p instanceof d.FloPayError&&p.code==="checkout_processing_timeout"||this.reportDirectFailure(p,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),p}}async patchAccountSnapshot(e,t,n,i){this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let o=i?.timeoutMs??Mr,a=new AbortController,l=()=>a.abort();i?.signal&&(i.signal.aborted?a.abort():i.signal.addEventListener("abort",l,{once:!0}));let c=setTimeout(()=>a.abort(),o);try{let u;try{u=await ke(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(n),signal:a.signal},Me,h=>{this.telemetryHooks?.onRetry?.("account_snapshot",h),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:h})})}finally{clearTimeout(c),i?.signal?.removeEventListener("abort",l)}if(!u.ok)throw await N(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,n,i){if(!t)throw new d.FloPayError("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=n,o=s.paymentMethodType,a=typeof o=="string"&&o.trim().toLowerCase()==="card",l=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===d.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&(s.intentKind==="payment"||s.intentKind==="setup"));if(!l||!c&&!u)throw new d.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let h=s.authorizationAttemptId;if(h!==void 0&&!(0,d.isUuidV4)(h))throw new d.FloPayError("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let p=(0,d.isUuidV4)(h)?h:(0,d.randomUuidV4)();this.beginDirectTelemetryCheckout(e);let y=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,[d.IDEMPOTENCY_KEY_HEADER]:i?.idempotencyKey||p},g=!1;try{let C=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:m,body:JSON.stringify({...n,authorizationAttemptId:p}),signal:i?.signal});if(!C.ok){g=!0;let S=await N(C,"Failed to create checkout intent"),Z=(0,d.classifyTelemetryFailure)(S,"PAYMENT_PROCESSING_FAILED");throw ht(S.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...Z,stage:"processing",requestCategory:"intent_create"}),S}let f=await C.json();if(C.status===202&&pe(f)&&f.type==="checkout_processing")return g=!0,await this.settleProcessingSessionIntent(f,C,e,t,n);let R=f.data;if(!R||typeof R!="object")throw new d.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let v=R,F=v.paymentMethodType,Y=(v.paymentMethodCategory==="wallet"||v.paymentMethodCategory==="apm")&&typeof F=="string"&&F.trim().toLowerCase()!=="card"&&(typeof v.paymentMethodId=="string"||v.paymentMethodId===null)&&typeof v.providerObjectId=="string",V=v.provider==="stripe"&&(v.intentKind==="payment"||v.intentKind==="setup")&&typeof v.clientSecret=="string",x=v.provider==="paypal"&&v.paymentMethodCategory==="wallet"&&v.paymentMethodId===null&&(v.paymentMethodType==="paypal"&&v.intentKind==="payment"&&(v.providerObjectType==="order"||v.providerObjectType==="subscription")||v.paymentMethodType===d.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&v.intentKind==="payment"&&v.providerObjectType==="order"||v.paymentMethodType===d.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&v.intentKind==="setup"&&v.providerObjectType==="setup_token")&&v.clientSecret===null,I=v.provider===n.provider&&v.paymentMethodCategory===n.paymentMethodCategory&&v.paymentMethodType===n.paymentMethodType&&v.paymentMethodId===n.paymentMethodId&&v.intentKind===n.intentKind;if(!Y||!V&&!x||!I)throw new d.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:(0,d.telemetryStatusClass)(C.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-y),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,d.telemetryStatusClass)(C.status)}),v}catch(C){throw g||this.reportDirectFailure(C,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),C}}async settleProcessingSessionIntent(e,t,n,i,s){let o=this.toCheckoutProcessingPending(e,t,n);try{return{settled:!0,response:await this.resolveCheckoutProcessing(o,n,{nonce:i,paymentMethodCategory:s.provider==="paypal"?"paypal":s.paymentMethodCategory})}}catch(a){throw a instanceof d.FloPayError&&a.code==="checkout_processing_timeout"?new d.FloPayError(a.message,a.type,{code:a.code,statusCode:202,sessionId:o.sessionId,cause:a}):a}}closeThreeDsChallenge(e,t,n,i={}){if(!e||!t||!n||i.signal?.aborted)return Promise.resolve("failed");let s=this.requestThreeDsChallengeClose(e,t,n,i.signal),o=O.pendingThreeDsAbandonReports;return o.set(e,s),s.then(()=>{o.get(e)===s&&o.delete(e)}),s}async requestThreeDsChallengeClose(e,t,n,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:n})};try{let a=await yt(s,o,i);if(a!=="retry")return a;if(i?.aborted)return"failed";await Ee(Lr,i);let l=await yt(s,o,i);return l==="retry"?"failed":l}catch{return"failed"}}async reportSessionIntentDecline(e,t,n,i){if(!t)throw new d.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=n,o=s.providerDeclineReason,a=s.paymentMethodType,l=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,h=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(l===void 0||typeof l=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(l)),p=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodType==="paypal"&&l===void 0;if(!u||!h&&!p)throw new d.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let y=p?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:o}:{provider:"stripe",paymentMethodCategory:s.paymentMethodCategory,paymentMethodType:s.paymentMethodType,providerDeclineReason:o,...typeof l=="string"?{providerIntentId:l}:{}},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(y),signal:i?.signal});if(!m.ok)throw await N(m,"Failed to report checkout decline")}async resolvePaymentMethodLayout(e,t,n,i){if(!t)throw new d.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,[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION},body:JSON.stringify(n),signal:i?.signal});if(s.status===404||s.status===405)return null;if(!s.ok)throw await N(s,"Failed to resolve the payment method layout");let o=await s.json();return(0,d.normalizePaymentMethodLayout)(o?.data)}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let n=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let 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,d.withTelemetryHttpDiagnostics)(new d.FloPayError("Failed to fetch payments","api_error",{statusCode:a.status}),a);let l=await a.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-n),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),l}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if((0,d.isDetachedSessionEligible)(e)){let s=e.account.email?.trim();if(s&&!(0,d.isValidEmail)(s))throw new d.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(),n=L(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,n.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{n.clear()}}async createAndFetchSessionRequest(e,t,n){let i=e.products??(0,d.foldIntoProducts)(e.items,e.subscriptions);(0,d.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:i});let s=(0,d.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,i);if(!s)throw new d.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:d.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:s,checkoutMode:e.checkoutMode??"full",products:i.map(c=>(0,d.buildProductPayload)(c,s)),accountData:Tt(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(o.captureMethod=e.captureMethod),e.tokenizedData&&(o.tokenizedData=e.tokenizedData),bt(o,e);let a=await this.postCheckoutSessionCreate(o,e,t,n),l=!1;try{let c=await a.json();if(c.data&&"gateways"in c.data){this.autoCacheDisplayData(c.data.uuid,e);let p=this.mergeCachedDisplayData(c.data),y=this.normalizeRawSession(p);return c.vault&&y.data.session&&(y.data.session.vault=this.toVaultBlock(c.vault)),{...y,autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}let u=c.data?.uuid;if(!u)throw new d.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(u,e),this.adoptDirectTelemetryCheckout(u),l=!0,{...await this.getUnifiedCheckoutSession(u),autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}catch(c){throw l?c:(0,d.markSessionResponseReceived)(c)}}async postCheckoutSessionCreate(e,t,n,i){let s={"Content-Type":"application/json",[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION},o=(0,d.resolveIdempotencyKey)(t.idempotencyKey);o&&(s[d.IDEMPOTENCY_KEY_HEADER]=o);let a=[];t.checkoutMode==="auto"&&a.push(d.ASYNC_AUTO_CHECKOUT_CAPABILITY),this.stripeAccountSwitch&&e.deferDataAttachment===!0&&a.push(gt),a.length>0&&(s[d.FLO_SDK_CAPABILITIES_HEADER]=a.join(", "));let l,c=!1,u=Br(t),h=(y,m,g)=>{c||(c=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:g,attempt:y}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-m),durationMode:"machine",requestCategory:"session_create",statusClass:g,attempt:y}))},p=y=>{try{this.telemetryHooks?.onRetry?.("session_create",y),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:y})}catch{}};for(let y=0;y<3;y++){i.attempt=y;let m=this.telemetryTimestamp();try{u?.onAttempt?.(y)}catch{}try{l=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:s,body:JSON.stringify(e),signal:n})}catch(f){if(i.statusClass=n.aborted||f instanceof Error&&f.name==="AbortError"?"timeout":"network_error",n.aborted||f instanceof Error&&f.name==="AbortError"||y>=2)throw f;let R=y+1;p(R),await te(y,n);continue}let g=(0,d.telemetryStatusClass)(l.status);if(i.statusClass=g,l.status===204)throw h(y,m,g),new d.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(l.ok){h(y,m,g);break}let C=await N(l,"Failed to create checkout session");if(C.code===d.IDEMPOTENCY_IN_PROGRESS_CODE&&y<2){p(y+1),await te(y,n);continue}throw h(y,m,g),C}if(!l)throw new TypeError("Checkout-session creation exhausted its retry budget.");return l}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),n=L(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,d.foldIntoProducts)(e.items,e.subscriptions);try{(0,d.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:s})}catch(f){throw n.clear(),this.reportSessionCreateFailure(f,t,i),f}let o=(0,d.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,s);if(!o)throw n.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new d.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{vt(e,o,s)}catch(f){throw n.clear(),this.reportSessionCreateFailure(f,t,i),f}let a,l,c=!1;try{let f=await this.postCheckoutSessionCreate(jr(e,o,s),e,n.signal,i);if(c=!0,l=await f.json(),!l.data||!("gateways"in l.data))throw new d.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(l.data)),l.vault&&a.data.session&&(a.data.session.vault=this.toVaultBlock(l.vault))}catch(f){throw n.clear(),c&&(0,d.markSessionResponseReceived)(f),this.reportSessionCreateFailure(f,t,i),f}let u=a.data.session?.id??l.data.uuid??"",h=a.data.session?.clientSecret??l.data.nonce??"";if(!u||!h){n.clear();let f=new d.FloPayError("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(f,t,i),f}n.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(),y=L(e.timeoutMs??12e3),m=this.claimCheckoutSession(u,h,p?Kr(e,o,s):vt(e,o,s),{params:e,startedAt:t,deadline:y,createAttempt:i.attempt}),g=p?void 0:m,C=(f={})=>{if(g!==void 0)return g;let R={...e,account:{...e.account,...f,email:f.email?.trim()||e.account.email?.trim()}};return(0,d.isValidEmail)(R.account.email)?(g=m.then(()=>{let v=this.telemetryTimestamp();return this.claimCheckoutSession(u,h,Gr(R.account),{params:R,startedAt:v,deadline:L(e.timeoutMs??12e3),createAttempt:0})}),g.catch(()=>{}),g):Promise.reject(new d.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:h,claimed:m,claim:C}}async claimCheckoutSession(e,t,n,i){let s=i?.startedAt??this.telemetryTimestamp(),o=this.telemetryTimestamp(),a=i?.deadline??L(12e3),l=JSON.stringify(n),c="unknown",u=0,h=!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,[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION,...this.stripeAccountSwitch?{[d.FLO_SDK_CAPABILITIES_HEADER]:gt}:{}},body:l,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 te(u,a.signal);continue}if(c=(0,d.telemetryStatusClass)(p.status),p.ok)break;throw await N(p,"Failed to attach checkout session data")}if(!p)throw new TypeError("Checkout-session claim exhausted its retry budget.");h=!0;let y=await p.json();if(!y.data?.gateways)throw new d.FloPayError("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});i?.params&&this.autoCacheDisplayData(y.data.uuid??e,i.params);let m=this.normalizeRawSession(this.mergeCachedDisplayData(y.data));return y.vault&&m.data.session&&(m.data.session.vault=this.toVaultBlock(y.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}),m}catch(p){throw h&&(0,d.markSessionResponseReceived)(p),this.reportSessionCreateFailure(p,o,{attempt:u,statusClass:c},"session_claim"),p}finally{a.clear()}}reportSessionCreateFailure(e,t,n,i="session_create"){if(!(e instanceof d.FloPayError&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let s=(0,d.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:n.attempt}),e instanceof d.FloPayError&&e.type==="validation_error"||e instanceof d.FloPayError&&ht(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 d.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 n=this.telemetryTimestamp(),i=t?.paymentMethodCategory??"saved";this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:i});let s=t?.timeoutMs??Ae,o=Date.now()+s,a=new AbortController,l=!1,c,u=setTimeout(()=>{c=setTimeout(()=>{l=!0,a.abort()},mt)},s),h=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?h():t?.signal?.addEventListener("abort",h,{once:!0});let p=this.clampRetryAfterMs(t?.initialDelayMs??dt),y=0;try{if(t?.statusUrl){let m=await this.waitForCheckoutStatus(e,{initialDelayMs:p,timeoutMs:s,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,()=>l);return this.reportRecoveryCompleted(n,i,t.challengeAttemptId),g}}for(;;){let m=o-Date.now();if(m<=0)throw D();if(p>0){try{y+=1,this.telemetryHooks?.onRetry?.("session_read",y),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:i,attempt:y})}catch{}if(await Ee(Math.min(p,m),a.signal),Date.now()>=o)throw D()}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(n,i,t?.challengeAttemptId),g;if(Date.now()>=o)throw D();p=this.clampRetryAfterMs(Math.max(p*2,ut))}}catch(m){let g=l&&Ve(m)?D():m;throw this.reportDirectFailure(g,"RECOVERY_FAILED","recovery","session_read",i),g}finally{clearTimeout(u),clearTimeout(c),t?.signal?.removeEventListener("abort",h)}}reportRecoveryCompleted(e,t,n){let i={stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t};if(this.directTelemetry?.log({name:"operation.recovery.completed",...i}),n)try{this.directTelemetry?.beginThreeDsChallenge({attemptId:n}).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,n,i,s){let o=t.latestTransactionAttempt;if(this.rememberReportedFailure(e,t),o?.result==="DECLINE"){let c=o.code===d.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE;throw new d.FloPayError(c?d.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 _r("Payment could not be completed. Please try again.",o?.code??"payment_processing_error");let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,n,i)}catch(c){if(!s?.()||!Ve(c))throw c;a={providers:[],mode:"tokenize",data:{},raw:t}}let l=a.data.session;return l&&o?.result==="SUCCESS"?{...a,data:{...a.data,session:{...l,status:"complete"}}}:l&&o?.result==="AUTHORIZED"?{...a,data:{...a.data,session:{...l,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:l&&t.status==="completed"?{...a,data:{...a.data,session:{...l,status:"complete"}}}:l&&t.status==="authorized"?{...a,data:{...a.data,session:{...l,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:l&&t.status==="expired"?{...a,data:{...a.data,session:{...l,status:"expired"}}}:o?.result!=="ACTION_REQUIRED"?a:o.gateway==="paypal"&&o.providerIntentId?{...a,autoProcessingError:{type:"paypal_direct_required",message:"PayPal authorization required",orderId:o.providerIntentId,checkoutMethod:"paypal"}}:o.nextActionRedirectUrl?{...a,autoProcessingError:{type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:o.nextActionRedirectUrl}}:a}async waitForCheckoutStatus(e,t){let n=t.timeoutMs??Ae,i=Date.now()+n,s=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let o=i-Date.now();if(o<=0||s>0&&(await Ee(Math.min(s,o),t.signal),Date.now()>=i))throw D();let a=i-Date.now();if(a<=0)throw D();let l=new AbortController,c,u=t.signal?new Promise((R,v)=>{c=v}):null,h=()=>{l.abort(t.signal?.reason),c?.(t.signal?.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))};t.signal?.aborted?h():t.signal?.addEventListener("abort",h,{once:!0});let p,y=t.signal?null:new Promise((R,v)=>{p=setTimeout(()=>{v(D()),l.abort()},a+mt)}),m;try{let R=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,l.signal);m=await Promise.race([R,y,u].filter(v=>v!==null))}finally{p!==void 0&&clearTimeout(p),t.signal?.removeEventListener("abort",h)}if(!m)return null;let g=ct(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 C=m.latestTransactionAttempt?.result,f=t.pollAfterAction===!0&&C==="ACTION_REQUIRED";if(!g&&C!==void 0&&C!=="PENDING"&&!f)return m;s=this.clampRetryAfterMs(Math.max(s*2,ut))}}isOwnFailedAttempt(e,t,n){let i=t.latestTransactionAttempt?.providerIntentId??null;return n!==void 0?i===n:i===null?!0:!Sr(t.uuid||e,i)}rememberReportedFailure(e,t){let n=t.latestTransactionAttempt;!ct(n)||!n.providerIntentId||Ar(t.uuid||e,n.providerIntentId)}async fetchCheckoutStatus(e,t,n,i){let s=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,o=s;if(n)try{let u=new URL(n,`${this.baseUrl}/`),h=new URL(s);u.origin===h.origin&&(o=u.toString())}catch{}let a={[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION};t&&(a["x-checkout-session-token"]=t);let l=await ke(o,{headers:a,signal:i});if(l.status===404||l.status===405)return null;if(!l.ok)throw await N(l,"Failed to get checkout session status");let c=await l.json();return pe(c.data)&&"latestTransactionAttempt"in c.data?c.data:null}normalizeRawSession(e){let t=e.gateways??{},n=[],i={session:this.toCheckoutSession(e)},s=t.stripe;if(s?.publishableKey){n.push("stripe");let l=[e.stripeClientSecret,s.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);i.stripe={clientSecret:l??"",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&&(n.push("paypal"),i.paypal={publishableKey:o.publishableKey,environment:o.environment,providerObjectType:o.providerObjectType,approvalPresentation:o.approvalPresentation}),{providers:n,mode:"tokenize",...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},data:i,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],n=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),i=t.reduce((c,u)=>c+(u.overrideAmount??u.totalAmount??0),0),s=n?e.totalAmount:i,o=Math.round(s*100),a=e.currency??t[0]?.currency??"USD",l="payment";return e.checkoutMode==="setup"?l="setup":t.some(c=>c.type==="subscription")&&(l="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:l,status:this.toCheckoutSessionStatus(e.status),amount:o,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:(0,d.normalizeCheckoutFailureOutcome)(e.outcome)??(0,d.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}:{},...fr(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(vr)}:{},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=Fr(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,...$r(e.expiresAt),...t?{verification:t}:{}}}toCheckoutSessionStatus(e){return e==="completed"?"complete":e==="authorized"?"authorized":e==="expired"?"expired":"open"}async resolveProcessResponse(e,t,n){if(e.status!==202)return e;let i=await e.json().catch(()=>null),s=this.toCheckoutProcessingPending(i,e,t);return this.resolveCheckoutProcessing(s,t,n)}async resolveCheckoutProcessing(e,t,n){let i=n?.pollTimeoutMs??Ae,s=Date.now()+i;if(e.statusUrl){let a=await this.waitForCheckoutStatus(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:i,nonce:n?.nonce,statusUrl:e.statusUrl,submittedIntentId:n?.submittedIntentId});if(a)return this.toProcessResponseFromStatus(a,t,n?.nonce)}let o=await this.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:s-Date.now(),nonce:n?.nonce,paymentMethodCategory:n?.paymentMethodCategory});return this.toProcessResponseFromSession(o,t)}async toProcessResponseFromStatus(e,t,n){let i=e.latestTransactionAttempt?.result,s={[Tr]:br},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,n);return this.toProcessResponseFromSession(a,t)}if(this.rememberReportedFailure(t,e),i==="DECLINE"){let a=e.latestTransactionAttempt,l=a?.code===d.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE,c=a?.declineReason??void 0;return new Response(JSON.stringify({type:c??"authorization_declined",message:l?d.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:Cr(e)??"Payment could not be completed. Please try again."}),{status:500,headers:o});throw D()}async reconcileProcessPayment(e,t){let n=t?.pollTimeoutMs??Ae,i=Date.now()+n,s=null;try{s=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:n,nonce:t?.nonce,submittedIntentId:t?.submittedIntentId})}catch(l){if(this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),l instanceof d.FloPayError&&l.code==="checkout_processing_timeout")throw l}if(s)return this.toProcessResponseFromStatus(s,e,t?.nonce);let o=i-Date.now();if(o<=0)throw D();let a=await this.waitForCheckoutSessionCompletion(e,{initialDelayMs:0,timeoutMs:o,nonce:t?.nonce,paymentMethodCategory:t?.paymentMethodCategory});return this.toProcessResponseFromSession(a,e)}toProcessResponseFromSession(e,t){if(e.data.session?.status==="complete")return new Response(null,{status:204,statusText:"No Content"});if(e.data.session?.status==="authorized"){let n=e.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:n.paymentId,sessionId:n.id||t,authorizationExpiresAt:n.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(e.data.session?.status==="expired"){let n=e.data.session.failureOutcome==="authorization_expired"||e.data.session.captureMethod==="manual";throw new d.FloPayError(n?"Authorization has expired.":"Checkout session has expired.","api_error",{code:n?"authorization_expired":"checkout_session_expired"})}throw D()}toCheckoutProcessingPending(e,t,n){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:K(e,"sessionId")??n,retryAfterMs:this.clampRetryAfterMs(Pr(e,"retryAfterMs")??o??dt),statusUrl:K(e,"statusUrl"),sessionUrl:K(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,Er))}autoCacheDisplayData(e,t){if(!e)return;let n=t.products??(0,d.foldIntoProducts)(t.items,t.subscriptions);if(n.length===0&&!t.currency)return;let i=t.products!==void 0,s=(0,d.resolveSessionCurrency)(t.currency,i?void 0:t.items,i?void 0:t.subscriptions,n);J(e,{currency:s??void 0,products:n.map(o=>({code:o.code??o.providerItemId??o.providerPlanId,type:o.type,name:o.name??o.itemName??o.providerItemName??o.subscriptionName??o.providerPlanName??null,totalAmount:o.totalAmount,overrideAmount:o.overrideAmount,currency:o.currency??s??void 0}))})}mergeCachedDisplayData(e){let t=Ce(e.uuid),n=new Map,i=o=>o?`code:${o}`:void 0;for(let o of t?.products??[]){let a=i(o.code);a&&n.set(a,o)}let s=(e.products??[]).map(o=>{let a=i(o.code),l=a?n.get(a):void 0;return{...o,name:o.name??l?.name??null,totalAmount:o.totalAmount??l?.totalAmount,overrideAmount:o.overrideAmount??l?.overrideAmount,currency:o.currency??l?.currency}});return{...e,currency:e.currency??t?.currency,products:s}}};O.activeVaultCaptureRequests=new Map,O.pendingThreeDsAbandonReports=new Map;var G=O;function _t(r,e){let t=G;return new t(r,e)}var b=require("@flopay/shared");var Pe=require("@flopay/shared");function Rt(r){if(!r)return null;try{let e=new URL(r,window.location.href);return e.origin==="null"?null:e.origin}catch{return null}}var Ie=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,Pe.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,n=[];for(let s of Array.from(e.querySelectorAll("script[src], iframe[src]"))){let o=Rt(s.getAttribute("src"));if(o&&t.add(o),s.tagName==="SCRIPT"){let a=()=>this.fail("load_error");s.addEventListener("error",a),n.push(()=>s.removeEventListener("error",a))}}let i=s=>{let o=Rt(s.blockedURI);o&&t.has(o)&&this.fail("blocked")};document.addEventListener("securitypolicyviolation",i),n.push(()=>document.removeEventListener("securitypolicyviolation",i)),this.detach=()=>{for(let s of n)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,Pe.invokeMerchantCallback)(()=>t(e))}};var Yr=4,De="flopay-vault",Wr=3e4,Jr=b.THREE_DS_CHALLENGE_WINDOW_MS+Wr,Qr="Card authentication timed out.",je=2,Xr=6e4;function Zr(r){if(!r)return!1;let e=Date.parse(r);return Number.isNaN(e)?!1:e-Date.now()<Xr}function en(r){if(!r)return!1;let e=Date.parse(r);return Number.isFinite(e)&&e>Date.now()}var wt={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 tn(r){return r.class==="lifecycle"?r.name:r.class==="technical_error"?r.code:r.class==="expected_outcome"?r.outcome:"sdk.performance"}function ne(r){let e={class:r.class,stage:r.stage};"code"in r&&(e.code=r.code),"provider"in r&&r.provider&&(e.provider=r.provider),"paymentMethodCategory"in r&&r.paymentMethodCategory&&(e.paymentMethodCategory=r.paymentMethodCategory),"outcome"in r&&(e.outcome=r.outcome),"durationMs"in r&&r.durationMs!==void 0&&(e.durationMs=r.durationMs),"durationMode"in r&&r.durationMode&&(e.durationMode=r.durationMode);try{globalThis.Sentry?.addBreadcrumb?.({category:"flopay.telemetry",level:r.class==="technical_error"?"error":"info",message:tn(r),data:e})}catch{}}function he(r,e){return(0,b.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:r,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var rn=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function nn(r){return typeof r=="string"&&rn.has(r)?r:"unknown"}var sn=new Set(["verification_failed","verification_expired"]);function on(r){return r==null?!0:typeof r=="string"&&sn.has(r)}var an="vault_mount";function ln(r){return r.failureStage===an}function He(r,e){return r&&!ln(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:nn(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function St(r,e,t="checkout"){return t==="card_setup"?r.type==="decline"?"card_setup_declined":"card_setup_succeeded":r.type==="decline"?"payment_declined":r.outcome==="authorized"||e==="manual"?"payment_authorized":"payment_succeeded"}function cn(r,e,t,n="checkout"){let{type:i}=r;if(i==="complete"||i==="decline")return(0,b.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:St(r,t,n),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(i==="error"){let a=He(e,r);return(0,b.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[s,o]=wt[i];return he(s,o)}function dn(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===De&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function un(r){if(typeof r!="object"||r===null)return;let e=r;if(typeof e.code!="string"||e.code.trim()==="")return;let t=typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0;return t?{code:e.code,message:t}:{code:e.code}}function mn(r){if(typeof r!="object"||r===null)return;let e=r,t=e.status;if(!(typeof e.id!="string"||e.id.trim()===""||typeof e.brand!="string"||e.brand.trim()===""||typeof e.lastFour!="string"||!/^\d{4}$/.test(e.lastFour)||typeof e.expiryMonth!="number"||!Number.isInteger(e.expiryMonth)||e.expiryMonth<1||e.expiryMonth>12||typeof e.expiryYear!="number"||!Number.isInteger(e.expiryYear)||e.expiryYear<1970||e.expiryYear>9999||t!=="pending"&&t!=="active"&&t!=="deleted"))return{id:e.id,brand:e.brand,lastFour:e.lastFour,expiryMonth:e.expiryMonth,expiryYear:e.expiryYear,status:t}}function pn(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===De&&e.type==="validation"&&Array.isArray(e.messages)}function hn(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===De&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}function yn(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===De&&e.type==="fields_interactive"}function gn(r){let e=r.capabilities;return Array.isArray(e)&&e.includes("fields_interactive")}var fn=["number","expiry","cvv","name"];function vn(r){if(r===null||typeof r!="object")return;let e=r,t={};for(let n of fn){let i=e[n];typeof i=="string"&&(t[n]=i)}return t}var X=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.chargeInFlight=!1;this.captureExpiresAt=null;this.remintPosts=0;this.remintGeneration=0;this.remintTask=null;this.remintFormRefused=!1;this.restoreListenersAttached=!1;this.onPageShow=()=>{this.considerRemint("page_restore")};this.onVisibilityChange=()=>{document.visibilityState==="visible"&&this.considerRemint("page_restore")};this.listeners=new Map;this.config=e,this.cardFields=new Ie({timeoutMs:e.cardFieldsTimeoutMs,now:()=>this.telemetryReporter?.now?.()??E(),report:n=>this.reportCardFields(n)}),this.ownsTelemetryReporter=!t&&e.telemetry!==!1,this.telemetryReporter=t?.reporter??(this.ownsTelemetryReporter?new A({billingApiUrl:(0,b.resolveBillingApiUrl)(e.billingApiUrl),sdkVersion:b.SDK_VERSION}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new A({billingApiUrl:(0,b.resolveBillingApiUrl)(this.config.billingApiUrl),sdkVersion:b.SDK_VERSION}));let n=this.telemetryReporter;if(this.config.operation==="card_setup"&&n&&this.setupTelemetryReporter!==n){this.setupTelemetryReporter=n;try{n.beginCheckout({checkoutMode:"setup"})}catch{}}if(this.mountStartedAt=this.telemetryReporter?.now?.()??E(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,this.cardFields.begin(),typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),new b.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 b.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.captureExpiresAt=t.expiresAt??null,this.remintPosts=0,this.chargeInFlight=!1,this.remintGeneration+=1,this.remintTask=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(),ne(he("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?.()??E())-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),this.emit("ready",{sessionId:this.config.sessionId}),this.attachRestoreListeners(),this.considerRemint("expiring")}reportVaultLoadFailure(){this.telemetryReporter?.error({errorCode:"VAULT_LOAD_FAILED",failureCategory:"provider_runtime",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})}on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>{this.listeners.get(e)?.delete(t)}}onCardFields(e){return this.cardFields.subscribe(e)}failCardFieldsMount(){this.cardFields.fail("other"),this.cardFields.end()}reportCardFields(e){let t=e.type==="card_fields_ready",n=this.config.sessionId;this.telemetryReporter?.log({name:t?"vault.fields.ready":"vault.fields.failed",stage:t?"vault_ready":"vault_mount",provider:"pcivault",paymentMethodCategory:"card",elapsedMs:e.elapsedMs,...e.type==="card_fields_failed"?{loadFailureReason:e.reason}:{},...n?{checkoutSessionId:n}:{}})}unmount(){if(this.detachRestoreListeners(),this.remintGeneration+=1,this.remintTask=null,this.chargeInFlight=!1,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)}remintBlocked(){return this.chargeInFlight||this.actionOverlay!==null}canRemint(){return!!(this.config.sessionId&&this.config.sessionToken)}recoverUnavailableForm(){return this.remintBlocked()||!this.canRemint()?!1:this.remintTask!==null?(this.remintFormRefused=!0,!0):this.remintPosts>=je?(this.emitRemint("form_unavailable","capped"),!1):(this.beginRemint("form_unavailable"),!0)}considerRemint(e){if(!(this.remintBlocked()||!this.canRemint()||this.remintTask!==null)&&Zr(this.captureExpiresAt)){if(this.remintPosts>=je){this.emitRemint(e,"capped");return}this.beginRemint(e)}}beginRemint(e){let t=this.remintGeneration;this.remintFormRefused=e==="form_unavailable";let n=this.performRemint(e,t).finally(()=>{this.remintTask===n&&(this.remintTask=null)});return this.remintTask=n,n}async performRemint(e,t){let n=this.config.sessionId,i=this.config.sessionToken;if(!n||!i)return;let s=new G((0,b.resolveBillingApiUrl)(this.config.billingApiUrl),{telemetry:!1}),o=!1;for(;this.remintPosts<je&&t===this.remintGeneration;){this.remintPosts+=1,this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});try{let a=await s.getVaultCapture(n,i);if(t!==this.remintGeneration||!this.container)return;this.adoptFreshBlock(a,n,i),o=!0,this.emitRemint(e,"succeeded");return}catch{if(t!==this.remintGeneration)return;this.emitRemint(e,"failed")}}!o&&t===this.remintGeneration&&this.container&&(this.remintFormRefused||!en(this.captureExpiresAt))&&this.showRemintLoadError()}adoptFreshBlock(e,t,n){if(!this.container)return;let i=(0,b.resolveVaultMountOptions)(e,{billingApiUrl:(0,b.resolveBillingApiUrl)(this.config.billingApiUrl),sessionId:t,nonce:n});if(!i?.html)throw new Error("The re-minted card form had no widget HTML.");this.messageToken=i.messageToken??null,i.expectedOrigin&&(this.expectedOrigin=i.expectedOrigin),this.captureExpiresAt=i.expiresAt??null,this.verificationRequired=i.verificationRequired===!0,this.injectWidget(this.container,i.html),this.cardFields.begin(),this.cardFields.watch(this.container)}showRemintLoadError(){this.reportVaultLoadFailure(),this.cardFields.fail("load_error"),this.emit("error",{...this.config.sessionId?{sessionId:this.config.sessionId}:{}})}emitRemint(e,t){this.telemetryReporter?.log({name:"card_form.remint",stage:"vault_request",trigger:e,outcome:t,provider:"pcivault",paymentMethodCategory:"card"})}attachRestoreListeners(){this.restoreListenersAttached||typeof window>"u"||(window.addEventListener("pageshow",this.onPageShow),document.addEventListener("visibilitychange",this.onVisibilityChange),this.restoreListenersAttached=!0)}detachRestoreListeners(){this.restoreListenersAttached&&(window.removeEventListener("pageshow",this.onPageShow),document.removeEventListener("visibilitychange",this.onVisibilityChange),this.restoreListenersAttached=!1)}injectWidget(e,t){e.innerHTML=t;let n=Array.from(e.querySelectorAll("script"));for(let i of n){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 n=t.data;if(hn(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;this.applyHeight(n.height);return}if(pn(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let c=n.messages.filter(u=>typeof u=="string"&&u.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:c||void 0});return}if(yn(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let c=typeof n.sessionId=="string"?n.sessionId:void 0;if(this.config.sessionId&&c&&c!==this.config.sessionId)return;this.cardFields.ready(),this.remintPosts=0;return}if(!dn(n)||this.messageToken&&n.messageToken!==this.messageToken)return;let i=this.config.sessionId,s=typeof n.sessionId=="string"?n.sessionId:void 0;if(i&&s&&s!==i||(n.type==="complete"||n.type==="decline")&&i&&s!==i||n.type==="error"&&n.code==="form_unavailable"&&this.recoverUnavailableForm())return;let o=mn(n.paymentMethod),a=un(n.vaultOutcome),l={...n.sessionId??this.config.sessionId?{sessionId:n.sessionId??this.config.sessionId}:{},...n.outcome?{outcome:n.outcome}:{},...n.paymentId?{paymentId:n.paymentId}:{},...n.authorizationExpiresAt?{authorizationExpiresAt:n.authorizationExpiresAt}:{},...n.failureOutcome?{failureOutcome:n.failureOutcome}:{},...n.intentId?{intentId:n.intentId}:{},...n.declineReason?{declineReason:n.declineReason}:{},...n.message?{message:n.message}:{},...a?{vaultOutcome:a}:{},...o?{paymentMethod:o}:{}};n.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??E(),this.chargeInFlight=!0,this.remintGeneration+=1,this.remintTask=null),(n.type==="complete"||n.type==="decline"||n.type==="error")&&(this.chargeInFlight=!1),this.isVerificationStateError(n)?(ne(he("operation.state_transition","vault_mount")),this.telemetryReporter?.log({name:"operation.state_transition",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})):(ne(cn(n,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(n),n.type==="error"&&He(this.submissionStarted,n).errorCode==="VAULT_LOAD_FAILED"&&this.cardFields.fail("load_error")),n.type==="ready"&&(this.remintPosts=0,this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postCardBrandIcons(),this.postCardFieldLabels(),this.postCardFieldPlaceholders(),this.postSubmitLabel(),gn(n)||this.cardFields.ready()),n.type==="action_required"&&n.nextActionRedirectUrl&&(this.showActionRequiredOverlay(n.nextActionRedirectUrl),this.actionOverlay&&typeof n.intentId=="string"&&n.intentId&&(this.actionChallengeIntentId=n.intentId)),(n.type==="complete"||n.type==="decline"||n.type==="error"||n.type==="submitting")&&(this.endActionChallengeFromWidget(n.type),this.hideActionRequiredOverlay()),n.type!=="action_required"&&this.emit(n.type,l)};this.messageHandler=e,window.addEventListener("message",e)}isVerificationStateError(e){return e.type==="error"&&this.verificationRequired&&!this.submissionStarted&&on(e.failureOutcome)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;let{type:n}=e;if(n==="ready"&&!this.vaultReadyReported&&(this.vaultReadyReported=!0,t.performance({stage:"vault_ready",durationMs:Math.max(0,t.now()-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card",requestCategory:"provider_sdk"})),n==="complete"||n==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:St(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="error"){let o=He(this.submissionStarted,e);t.log({name:"vault.terminal",stage:o.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...o,provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="action_required"){t.log({name:"vault.action.required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),t.log({name:"vault.three_ds.handoff",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});let o=this.submissionStartedAt;this.submissionStartedAt=null,o!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-o),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[i,s]=wt[n];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,b.buildCardFieldLabelsPayload)(e),this.postCardFieldLabels()}postCardFieldLabels(){let e=this.showCardFieldLabels,t=this.cardFieldLabels;if(e===void 0&&t===void 0)return;let n=this.config.sessionId,{messageToken:i,expectedOrigin:s}=this;!n||!i||!s||this.postToHostedWindow({source:"flopay-vault-host",type:"cardFieldLabels",sessionId:n,messageToken:i,...e===void 0?{}:{show:e},...t===void 0?{}:{labels:{...t}}},s)}setCardFieldPlaceholders(e){let t=vn(e),n=t===void 0&&this.cardFieldPlaceholders!==void 0;this.cardFieldPlaceholders=t,this.postCardFieldPlaceholders(n?{}:t)}postCardFieldPlaceholders(e=this.cardFieldPlaceholders){let t=this.config.sessionId,{messageToken:n,expectedOrigin:i}=this;e===void 0||!t||!n||!i||this.postToHostedWindow({source:"flopay-vault-host",type:"cardFieldPlaceholders",sessionId:t,messageToken:n,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:n,expectedOrigin:i}=this;e===void 0||!t||!n||!i||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:t,messageToken:n,label:e},i)}hostedWindow(){return this.container?.querySelector("iframe")?.contentWindow??null}postToHostedWindow(e,t){let n=this.hostedWindow();if(n)try{n.postMessage(e,t)}catch{}}directiveTargetOrigin(){return this.expectedOrigin??"*"}emit(e,t){for(let n of this.listeners.get(e)??[])n(t)}showActionRequiredOverlay(e){if(typeof document>"u")return;if(this.actionOverlay){let 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=de(this.beginActionChallengeAttempt()),n=Re(e),i=!1,s=m=>{if(i)return;let g=_e(m,n);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"),ue(e)==="invalid"&&t.record("action_invalid",{reason:"invalid_url"}),document.addEventListener("securitypolicyviolation",s),window.addEventListener("pagehide",o);let l=document.createElement("div");l.setAttribute("data-flopay-action-required","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let c=document.createElement("iframe");c.setAttribute("title","Card authentication"),c.setAttribute("allow","payment"),c.tabIndex=0,c.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),c.addEventListener("load",()=>{a.loaded||(a.loaded=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"}))}),c.src=e,l.appendChild(c);let 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()),l.appendChild(u),l.addEventListener("click",m=>{m.target===l&&this.abandonActionRequiredOverlay()});let h=0,p=m=>{let g=m.data,C=!!g&&typeof g=="object"&&g.source==="flopay-vault-3ds-return";if(m.source!==c.contentWindow){C&&h<Yr&&(h+=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"}),ne(he("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(l)}catch(m){throw t.record("render_failed"),this.hideActionRequiredOverlay(),this.actionOverlayPreviousFocus=null,m}t.record("container_attached"),t.record("navigation_assigned");let y=be(l);y&&t.record("container_visibility",{reason:y,evidenceBasis:"parent_computed_style"}),this.actionOverlay=l,c.focus(),this.armActionRequiredTimeout(),ne(he("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},Jr)}reportChallengeAbandoned(){ne((0,b.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:Qr})}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:n}=this.config;if(!(!e||!t||!n))try{new G((0,b.resolveBillingApiUrl)(this.config.billingApiUrl),{telemetry:!1}).closeThreeDsChallenge(t,n,e).catch(()=>{})}catch{}}beginActionChallengeAttempt(){try{return this.telemetryReporter?.beginThreeDsChallenge?.()}catch{return}}endActionChallengeFromWidget(e){let t=this.actionChallenge,n=t?.telemetry??this.lastChallengeTelemetry;if(this.lastChallengeTelemetry=null,!!n){if(e==="submitting"){if(!t)return;n.record("abort_observed",{reason:"unspecified",evidenceBasis:"signal_reason"}),n.terminal("abort",{reason:"unspecified",evidenceBasis:"signal_reason"});return}t&&n.terminal("status_poll",{evidenceBasis:"server_status"}),e==="complete"&&n.reconcile("succeeded"),e==="decline"&&n.reconcile("declined")}}hideActionRequiredOverlay(){if(this.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 n=Math.max(0,Math.min(Math.ceil(e),2e3));t.style.height=`${n}px`}};function At(r,e){let t=X;return new t(r,{reporter:e})}var kt=Symbol.for("@flopay/js.telemetry.bridge.v1");function Et(r,e,t){let n=()=>e?.now()??t();Object.defineProperty(r,kt,{configurable:!1,enumerable:!1,writable:!1,value:{error:s=>e?.error(s),log:s=>e?.log(s),performance:s=>e?.performance(s),terminal:s=>e?.terminal(s),now:n,elapsed:s=>Math.max(0,n()-s),setCheckoutContext:s=>e?.setCheckoutContext(s),beginCheckout:(s={})=>e?.beginCheckout(s)??n(),disable:()=>e?.disable(),subscribe:s=>e?.subscribe(s)??(()=>{}),flush:()=>e?.flush()??Promise.resolve()}})}function Mt(r){return r[kt]}var ye=class{now(){return this.telemetryReporter?.now?.()??E()}constructor(e,t,n){this.provider=e,this.config=t,this.telemetryReporter=n??new A({billingApiUrl:(0,M.resolveBillingApiUrl)(t.billingApiUrl),sdkVersion:M.SDK_VERSION,enabled:t.telemetry!==!1}),Et(this,this.telemetryReporter,E)}cardCapture(e){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?At({sessionId:e?.sessionId,captureMethod:e?.captureMethod,sessionToken:e?.sessionToken,billingApiUrl:this.config.billingApiUrl,cardFieldsTimeoutMs:e?.cardFieldsTimeoutMs},this.telemetryReporter):new X({sessionId:e?.sessionId,captureMethod:e?.captureMethod,sessionToken:e?.sessionToken,billingApiUrl:this.config.billingApiUrl,cardFieldsTimeoutMs:e?.cardFieldsTimeoutMs,telemetry:!1})}async retrieveSession(e,t){if(!e)throw new M.FloPayError("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let n=await this.retrieveUnifiedSession(e,t);if(!n.data.session)throw new M.FloPayError("Session not found","api_error");return n.data.session}async retrieveUnifiedSession(e,t){if(!e)throw new M.FloPayError("sessionId is required.","validation_error",{param:"sessionId"});let n=(0,M.resolveBillingApiUrl)(t??this.config.billingApiUrl),i=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let s,o,a=c=>{if(s===void 0)return;let u=s,h=o;s=void 0,o=void 0,this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:c,attempt:h}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:u,durationMode:"machine",requestCategory:"session_read",statusClass:c,attempt:h})},l=_t(n,{now:()=>this.telemetryReporter?.now()??E(),onFirstByte:(c,u)=>{s=c,o=u},onRetry:(c,u)=>{this.telemetryReporter?.log({name:"operation.retry",stage:c==="session_read"?"session_read":"processing",requestCategory:c,attempt:u})}});try{let c=await l.getUnifiedCheckoutSession(e);return a("2xx"),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-i,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),c}catch(c){let u=(0,M.classifyTelemetryFailure)(c,c instanceof M.FloPayError&&c.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw a(u.statusClass),this.telemetryReporter?.error({...u,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-i,durationMode:"machine",requestCategory:"session_read",statusClass:u.statusClass}),c}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.provider.destroy()}};function It(r,e,t){let n=ye;return new n(r,e,t)}var B=require("@flopay/shared");var Ke=require("@flopay/shared"),Pt=require("@stripe/stripe-js"),se=require("@flopay/shared"),Dt=new WeakSet;function Ft(r){return r instanceof Ke.FloPayError&&Dt.has(r)}var ie=class{constructor(){this.name="stripe";this.stripe=null}async initialize(e){if(typeof window>"u")return;let t=await(0,Pt.loadStripe)(e.publishableKey,{locale:e.locale??"auto"});if(!t){let n=new Ke.FloPayError("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw Dt.add(n),n}this.stripe=t}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var xt=new Map;function Ge(r){return Array.isArray(r)?r.map(Ge):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Ge(t)])):r}function Cn(r,e){return JSON.stringify([r,(0,B.resolveBillingApiUrl)(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,Ge(e?.appearance??null)])}var Fe=new Map;async function Ot(r,e){if(!r){let a=new A({billingApiUrl:(0,B.resolveBillingApiUrl)(e?.billingApiUrl),sdkVersion:B.SDK_VERSION,enabled:e?.telemetry!==!1});throw a.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),a.flush().catch(()=>{}).finally(()=>a.destroy()),new B.FloPayError("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let t=Cn(r,e),n=xt.get(t);if(n)return e?.telemetry!==!1&&Mt(n)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),n;let i=Fe.get(t);if(i)return i;let s={...e,publishableKey:r},o=(async()=>{let a=new A({billingApiUrl:(0,B.resolveBillingApiUrl)(s.billingApiUrl),sdkVersion:B.SDK_VERSION,enabled:s.telemetry!==!1}),l=a.now();a.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),a.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),a.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let c=new ie,u=a.now();try{await c.initialize(s)}catch(y){throw a.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:Ft(y)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),a.destroy(),y}let h=a.now();a.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),a.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),a.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),a.performance({stage:"sdk_initialize",durationMs:h-l,durationMode:"machine",provider:"stripe"}),a.performance({stage:"provider_ready",durationMs:h-u,durationMode:"machine",provider:"stripe"});let p=It(c,s,a);return xt.set(t,p),p})();Fe.set(t,o);try{return await o}finally{Fe.get(t)===o&&Fe.delete(t)}}var $=require("@flopay/shared");var Tn=4,bn=1e3,_n=1e3,Rn=15e3;function wn(r){let e=!!r?.gateways?.stripe,t=!!r?.gateways?.worldpayCorporateGateway;return e===t?"unknown":e?"stripe":"worldpay"}function Lt(r,e,t){try{return typeof r?.beginThreeDsChallenge!="function"?void 0:r.beginThreeDsChallenge(e,{provider:wn(t)})}catch{return}}function ge(r){return new $.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:r})}function qt(){return new $.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Nt(r){return r.replace(/\/+$/,"")}function Sn(r){return r.status==="succeeded"||r.status==="authorized"||r.status==="declined"}function An(r){if(!r||typeof r!="object")return{status:"unknown"};let e=typeof r.status=="string"?r.status:"unknown",t=typeof r.providerIntentId=="string"?r.providerIntentId:null;switch(e){case"succeeded":case"authorized":case"pending":case"timeout":return{status:e,providerIntentId:t};case"declined":return{status:"declined",providerIntentId:t,declineReason:typeof r.declineReason=="string"?r.declineReason:null,gatewayDeclineReason:typeof r.gatewayDeclineReason=="string"?r.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:t,nextActionRedirectUrl:typeof r.nextActionRedirectUrl=="string"?r.nextActionRedirectUrl:null};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}async function $e(r){if(typeof document>"u"||typeof window>"u")throw new $.FloPayError("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});let e=de(r.telemetry);e.record("handoff_planned");let t=ue(r.nextActionRedirectUrl);t==="missing"?e.record("action_missing",{reason:"missing_url"}):t==="invalid"&&e.record("action_invalid",{reason:"invalid_url"});let n=m=>{let g=Qe(m);if(g==="buyer_cancel"){e.record("cancel_requested",{reason:g,evidenceBasis:"signal_reason"}),e.terminal("cancel",{reason:g,evidenceBasis:"signal_reason"});return}e.record("abort_observed",{reason:g,evidenceBasis:"signal_reason"}),e.terminal("abort",{reason:g,evidenceBasis:"signal_reason"})},i=m=>{(m.status==="succeeded"||m.status==="authorized"||m.status==="declined"||m.status==="timeout")&&e.reconcile(m.status)};if(r.signal?.aborted)throw n(r.signal.reason),ge();let s=`${Nt(r.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(r.sessionId)}/3ds/complete`,o=async()=>{let m=new AbortController,g=()=>m.abort();r.signal?.aborted?m.abort():r.signal?.addEventListener("abort",g);let C=window.setTimeout(()=>m.abort(),Rn);try{let f=await fetch(s,{method:"POST",headers:{"x-checkout-session-token":r.nonce,"content-type":"application/json",...e.attemptId?{"x-flopay-challenge-attempt":e.attemptId}:{}},body:"{}",signal:m.signal});if(!f.ok)return{status:"unknown"};let R=await f.json().catch(()=>null),v=An(R);return i(v),v}catch{return{status:"unknown"}}finally{window.clearTimeout(C),r.signal?.removeEventListener("abort",g)}},a,l=()=>r.pollCompletionEndpoint!==!1?o():(a??(a=o()),a),c=document.activeElement instanceof HTMLElement?document.activeElement:null,u=document.createElement("div");u.setAttribute("data-flopay-auto-3ds-overlay","1"),u.setAttribute("role","dialog"),u.setAttribute("aria-modal","true"),u.setAttribute("aria-label","Card authentication"),u.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 h=document.createElement("iframe");h.setAttribute("title","Card authentication"),h.setAttribute("allow","payment"),h.tabIndex=0,h.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let p=null;try{p=new URL(r.billingApiUrl,window.location.href).origin}catch{p=null}let y=Re(r.nextActionRedirectUrl);try{let m=await new Promise((g,C)=>{let f=!1,R=0,v=0,F=0,Y=!1,V=!1,x=!1,I=0,S=()=>{window.clearTimeout(R),window.clearInterval(v),window.clearTimeout(F),window.removeEventListener("message",P),window.removeEventListener("pagehide",oe),document.removeEventListener("securitypolicyviolation",U),h.removeEventListener("load",W),r.signal?.removeEventListener("abort",ae)},Z=async()=>{if(!(f||Y)){Y=!0;try{let w=await l();if(f||!Sn(w))return;f=!0,S(),e.terminal("status_poll",{evidenceBasis:"server_status"}),g(w)}finally{Y=!1}}},oe=()=>{e.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},U=w=>{if(x)return;let _=_e(w,y);_&&(x=!0,e.record("policy_violation",{reason:_,evidenceBasis:"parent_csp_event"}))},W=()=>{V||(V=!0,e.record("iframe_load",{evidenceBasis:"iframe_load_event"})),r.pollCompletionEndpoint!==!1&&(window.clearTimeout(F),F=window.setTimeout(()=>{Z()},250))},ae=()=>{f||(f=!0,S(),n(r.signal?.reason),C(ge()))},z=w=>{f||I>=Tn||(I+=1,e.record("return_rejected",{reason:w,evidenceBasis:"message_origin_check"}))},P=w=>{let _=w.data,j=!!_&&typeof _=="object"&&_.source==="flopay-vault-3ds-return";if(w.source!==h.contentWindow){j&&z("untrusted_source");return}if(p&&w.origin!==p){j&&z("untrusted_origin");return}j&&(f||(f=!0,S(),e.record("trusted_return",{evidenceBasis:"message_origin_check"}),e.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),g(null)))};R=window.setTimeout(()=>{f||(f=!0,S(),V||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"}),C(qt()))},$.THREE_DS_CHALLENGE_WINDOW_MS),r.pollCompletionEndpoint!==!1&&(v=window.setInterval(()=>{Z()},_n)),h.addEventListener("load",W),window.addEventListener("message",P),window.addEventListener("pagehide",oe),document.addEventListener("securitypolicyviolation",U),r.signal?.addEventListener("abort",ae),h.src=r.nextActionRedirectUrl,e.record("render_attempted");try{u.appendChild(h),document.body.appendChild(u)}catch(w){throw f=!0,S(),e.record("render_failed"),w}e.record("container_attached"),e.record("navigation_assigned");let ee=be(u);ee&&e.record("container_visibility",{reason:ee,evidenceBasis:"parent_computed_style"}),h.focus(),r.signal?.aborted&&ae()});return m||await l()}finally{u.parentNode?.removeChild(u),e.record("teardown"),c?.isConnected&&c.focus()}}function Ut(r,e){try{let t=e.data.session?.status;t==="complete"?r.reconcile("succeeded"):t==="authorized"&&r.reconcile("authorized")}catch{}}function kn(r){return new $.FloPayError("Card was declined.","api_error",{code:r.declineReason??"authorization_declined",...r.gatewayDeclineReason?{declineCode:r.gatewayDeclineReason}:{}})}async function Bt(r,e){let t=`${Nt(r.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(r.sessionId)}/status`,n=new AbortController,i=new AbortController,s=()=>{n.abort(r.signal?.reason),i.abort(r.signal?.reason)};r.signal?.aborted?s():r.signal?.addEventListener("abort",s,{once:!0});let o=de(r.telemetry),a=$e({billingApiUrl:r.billingApiUrl,sessionId:r.sessionId,nonce:r.nonce,nextActionRedirectUrl:r.nextActionRedirectUrl,signal:n.signal,pollCompletionEndpoint:!1,...r.telemetry?{telemetry:r.telemetry}:{}}),l=e.waitForCheckoutSessionCompletion(r.sessionId,{initialDelayMs:bn,nonce:r.nonce,statusUrl:t,continueAfterActionRequired:!0,timeoutMs:$.THREE_DS_CHALLENGE_WINDOW_MS+15e3,signal:i.signal,...o.attemptId?{challengeAttemptId:o.attemptId}:{}});l.catch(()=>{}),a.catch(()=>{});try{let c=await Promise.race([a,l]);if("data"in c)return o.terminal("status_poll",{evidenceBasis:"server_status"}),Ut(o,c),c;if(c.status==="declined")throw(r.createDeclineError??kn)(c);if(c.status==="timeout")throw qt();let u=await l;return Ut(o,u),u}catch(c){throw r.signal?.aborted||c instanceof Error&&c.name==="AbortError"?ge(c):c}finally{r.signal?.removeEventListener("abort",s),n.abort(),i.abort()}}0&&(module.exports={FloPay,PaymentAPI,PciVaultCardCapture,SESSION_CREATE_TELEMETRY,StripeAdapter,beginSavedCardChallengeTelemetry,cacheSessionDisplayData,clearSessionDisplayData,completeSavedCardNextAction,createCheckoutSession,createCheckoutSessionWithRetries,createSavedCardActionAbortedError,dropThirdPartyOnlyError,getSessionDisplayData,loadCheckoutRuntime,loadFloPay,runSavedCardChallenge,toStripeAppearance,toStripeAppearanceTheme});
|
|
1
|
+
"use strict";var q=Object.defineProperty;var Ee=Object.getOwnPropertyDescriptor;var ke=Object.getOwnPropertyNames;var _e=Object.prototype.hasOwnProperty;var we=(e,t)=>{for(var r in t)q(e,r,{get:t[r],enumerable:!0})},De=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ke(t))!_e.call(e,o)&&o!==r&&q(e,o,{get:()=>t[o],enumerable:!(n=Ee(t,o))||n.enumerable});return e};var Re=e=>De(q({},"__esModule",{value:!0}),e);var We={};we(We,{cacheSessionDisplayData:()=>I,clearSessionDisplayData:()=>Z,createCheckoutSession:()=>ue,createCheckoutSessionWithRetries:()=>pe,dropThirdPartyOnlyError:()=>fe.dropThirdPartyOnlyError,getSessionDisplayData:()=>W,loadCheckoutRuntime:()=>Q});module.exports=Re(We);var fe=require("@flopay/shared");var B=require("@flopay/shared"),Ae="FloPayCheckoutRuntime",Ie=1e4,U=new Map;function Pe(e){return typeof e=="object"&&e!==null&&typeof e.mount=="function"}function L(e){return new B.FloPayError(e==="runtime_load_timeout"?"The checkout runtime did not load in time.":"The checkout runtime failed to load.","network_error",{code:e})}function xe(e,t){return new Promise((r,n)=>{let o=document.createElement("script"),u=!1,c=m=>{u||(u=!0,clearTimeout(l),o.removeEventListener("load",a),o.removeEventListener("error",i),m instanceof B.FloPayError?(U.delete(e),o.remove(),n(m)):r(m))},a=()=>{let m=Reflect.get(globalThis,Ae);c(Pe(m)?m:L("runtime_load_failed"))},i=()=>c(L("runtime_load_failed")),l=setTimeout(()=>c(L("runtime_load_timeout")),t);o.addEventListener("load",a),o.addEventListener("error",i),o.async=!0,o.src=e,document.head.appendChild(o)})}function Q(e){let{runtimeUrl:t,timeoutMs:r=Ie}=e,n=U.get(t);if(n!==void 0)return n;let o=xe(t,r);return U.set(t,o),o}var s=require("@flopay/shared");function N(e){return typeof e=="string"&&e.trim()?e:void 0}function j(e){if(typeof e=="string")return e.trim()?e:void 0;if(Array.isArray(e))return e.filter(r=>typeof r=="string"&&r.trim().length>0).join("; ")||void 0}function $(e=12e3){let t=Number.isFinite(e)&&e>=0?e:12e3,r=new AbortController,n=setTimeout(()=>r.abort(),t);return{signal:r.signal,clear:()=>clearTimeout(n)}}function Me(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function J(e,t){let r=150*2**e,n=Math.round(r*(.75+Math.random()*.5));return new Promise((o,u)=>{let c,a=()=>t.removeEventListener("abort",i),i=()=>{c!==void 0&&clearTimeout(c),a(),u(Me())};if(t.aborted){i();return}c=setTimeout(()=>{a(),o()},n),t.addEventListener("abort",i,{once:!0})})}var Fe="flopay_session_display:";var R=new Map;function A(e){return`${Fe}${e}`}function H(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function I(e,t,r){if(!e)return;let n=r?.ttlMs??36e5,o={data:t,expiresAt:Date.now()+n},u=H();if(u)try{u.setItem(A(e),JSON.stringify(o));return}catch{}R.set(e,o)}function W(e){if(!e)return null;let t=H();if(t)try{let n=t.getItem(A(e));if(n){let o=JSON.parse(n);if(o&&typeof o.expiresAt=="number"&&o.expiresAt>Date.now())return o.data;t.removeItem(A(e))}}catch{}let r=R.get(e);if(r){if(r.expiresAt>Date.now())return r.data;R.delete(e)}return null}function Z(e){if(!e)return;R.delete(e);let t=H();if(t)try{t.removeItem(A(e))}catch{}}var h=require("@flopay/shared");var te=require("@flopay/shared"),Oe=32,ee=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function qe(){let e=globalThis,t=e[ee];if(t instanceof Map)return t;let r=new Map;try{Object.defineProperty(e,ee,{configurable:!0,enumerable:!1,writable:!1,value:r})}catch{}return r}function Le(e,t){let r=qe(),n=r.get(e);if(n)return n;for(;r.size>=Oe;){let u=r.keys().next();if(u.done)break;r.delete(u.value)}let o={nextSequence:0,startedAt:t,terminated:!1,reconciled:new Set,provider:"unknown"};return r.set(e,o),o}var Ue=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),Be=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function re(e,t={}){let r=(0,te.isThreeDsChallengeAttemptId)(t.attemptId)?t.attemptId.toLowerCase():e.newAttemptId(),n=()=>{try{let a=e.now();return Number.isFinite(a)?a:0}catch{return 0}},o=Le(r,n());(t.provider==="stripe"||t.provider==="worldpay")&&(o.provider=t.provider);let u=o.provider,c=(a,i)=>{if(o.terminated&&!Be.has(a))return;let l={attemptId:r,phase:a,attemptSequence:o.nextSequence,elapsedMs:Math.max(0,n()-o.startedAt),provider:u};o.nextSequence+=1,i.reason!==void 0&&(l.reason=i.reason),i.evidenceBasis!==void 0&&(l.evidenceBasis=i.evidenceBasis),i.terminalSource!==void 0&&(l.terminalSource=i.terminalSource),i.providerOutcome!==void 0&&(l.providerOutcome=i.providerOutcome);try{e.emit(l,Ue.has(a))}catch{}};return{attemptId:r,record(a,i={}){a==="browser_terminal"||a==="provider_reconciled"||c(a,{reason:i.reason,evidenceBasis:i.evidenceBasis})},terminal(a,i={}){o.terminated||(c("browser_terminal",{terminalSource:a,reason:i.reason,evidenceBasis:i.evidenceBasis}),o.terminated=!0)},reconcile(a){o.reconciled.has(a)||(o.reconciled.add(a),c("provider_reconciled",{providerOutcome:a,evidenceBasis:"provider_fact"}))}}}var Ne="/v1/sdk-telemetry/events",P=16,ne=64,je=1500,oe=1e3,$e=64,He="00000000-0000-4000-8000-000000000000",Ke={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},Ve=48;function f(){try{return globalThis.crypto.randomUUID()}catch{let e=new Uint8Array(16);try{globalThis.crypto.getRandomValues(e)}catch{for(let r=0;r<e.length;r+=1)e[r]=Math.floor(Math.random()*256)}e[6]=(e[6]??0)&15|64,e[8]=(e[8]??0)&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}}function Ye(e){try{return new TextEncoder().encode(e).byteLength}catch{return e.length}}function Ge(e){return JSON.stringify([e.code,e.failureCategory,e.reason,e.stage,e.provider,e.attempt,e.statusClass,e.requestCategory,e.paymentMethodCategory,e.walletType,e.operationOutcome,e.checkoutMode,e.layout,e.inAppBrowser,e.appFamily,e.popupCapability,e.presentationMode,e.terminalReason])}function ie(){return globalThis.performance?.now()??0}var k=class{constructor(t){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=()=>{typeof document<"u"&&document.visibilityState==="hidden"&&this.flush()};this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0};this.endpoint=`${t.billingApiUrl.replace(/\/+$/,"")}${Ne}`,this.sdkPackage=t.sdkPackage??"@flopay/js",this.sdkVersion=t.sdkVersion,this.correlationId=f(),this.merchantEnabled=t.enabled!==!1,this.clock=t.clock??ie,this.browserTransportAvailable=typeof window<"u"&&typeof document<"u",this.browserTransportAvailable&&(window.addEventListener("pagehide",this.pageExitHandler),document.addEventListener("visibilitychange",this.visibilityHandler))}log(t){this.notify({...t,class:"lifecycle"}),this.canCollect()&&this.enqueue((0,h.buildTelemetryLogEvent)({...this.checkoutContext,...t,eventId:f(),sequence:this.sequence++}))}error(t){if(this.notify({...t,class:"technical_error"}),!this.canCollect())return;let r=(0,h.buildTelemetryErrorEvent)({...this.checkoutContext,...t,eventId:He,sequence:0}),n=Ge(r),o=this.now();this.pruneReportedFailures(o);let u=this.reportedFailures.get(n);if(u!==void 0&&o>=u&&o-u<oe){this.log({name:"operation.deduplicated",stage:t.stage,provider:t.provider,paymentMethodCategory:t.paymentMethodCategory,attempt:t.attempt,inAppBrowser:t.inAppBrowser,appFamily:t.appFamily,popupCapability:t.popupCapability,presentationMode:t.presentationMode,terminalReason:t.terminalReason});return}this.rememberReportedFailure(n,o),this.enqueue((0,h.buildTelemetryErrorEvent)({...this.checkoutContext,...t,eventId:f(),sequence:this.sequence++}))}performance(t){this.canCollect()&&this.enqueue((0,h.buildTelemetryPerformanceEvent)({...this.checkoutContext,...t,eventId:f(),sequence:this.sequence++}))}terminal(t){if(this.canCollect()&&(this.enqueue((0,h.buildTelemetryTerminalEvent)({...this.checkoutContext,...t,eventId:f(),sequence:this.sequence++})),t.outcome!=="action_required"&&this.checkoutStartedAt!==null)){let r=this.checkoutStartedAt;this.checkoutStartedAt=null,this.performance({...t,stage:"total_journey",durationMs:Math.max(0,this.now()-r),durationMode:"total"})}}beginThreeDsChallenge(t={}){return re({now:()=>this.now(),newAttemptId:f,emit:(r,n)=>this.recordThreeDsChallenge(r,n)},t)}recordThreeDsChallenge(t,r){if(!this.canCollect()||this.threeDsChallengeCount>=Ve)return;let n=(0,h.buildTelemetryLogEvent)({...this.checkoutContext,...t,name:"three_ds.challenge",stage:"three_ds_handoff",eventId:f(),sequence:this.sequence++});if(!(this.queue.length>=ne)){if(this.threeDsChallengeCount+=1,this.queue.push(n),r){this.drainQueue();return}if(this.queue.length>=P){this.flush();return}this.scheduleFlush()}}now(){try{return this.clock()}catch{return ie()}}subscribe(t){return this.destroyed?()=>{}:(this.observers.add(t),()=>this.observers.delete(t))}notify(t){if(!this.destroyed)for(let r of this.observers)try{r(t)}catch{}}pruneReportedFailures(t){for(let[r,n]of this.reportedFailures)(t<n||t-n>=oe)&&this.reportedFailures.delete(r)}rememberReportedFailure(t,r){for(;this.reportedFailures.size>=$e;){let n=this.reportedFailures.keys().next();if(n.done)break;this.reportedFailures.delete(n.value)}this.reportedFailures.set(t,r)}setCheckoutContext(t){this.checkoutContext={checkoutMode:t.checkoutMode,layout:t.layout}}beginCheckout(t={}){return this.canCollect()?(this.drainQueue(),this.setCheckoutContext(t),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(t){if(this.canCollect()&&!(this.queue.length>=ne||this.eventCounts[t.class]>=Ke[t.class])){if(this.eventCounts[t.class]+=1,this.queue.push(t),this.queue.length>=P){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 t=this.queue.splice(0,P);return this.flushInFlight=this.sendBatch(t).finally(()=>{this.flushInFlight=null,this.queue.length>0&&this.scheduleFlush()}),this.flushInFlight}destroy(){this.destroyed||(this.drainQueue(),this.destroyed=!0,this.clearFlushTimer(),this.browserTransportAvailable&&(typeof window<"u"&&window.removeEventListener("pagehide",this.pageExitHandler),typeof document<"u"&&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 t=this.queue.splice(0,P);this.sendBatch(t)}}async sendBatch(t){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let r=(0,h.serializeTelemetryBatch)(t,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:f()});if(Ye(r)>h.TELEMETRY_MAX_BATCH_BYTES)return;let n=typeof AbortController>"u"?null:new AbortController,o=null;try{let u=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:r,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:n?.signal}).then(async i=>{if(i.status!==202)return null;let l=null;try{l=await i.json()}catch{}return l?.status==="disabled"?"disabled":null}).catch(()=>null),c=new Promise(i=>{o=setTimeout(()=>{n?.abort(),i(null)},je)});await Promise.race([u,c])==="disabled"&&this.disableFromIngestion()}catch{}finally{o&&clearTimeout(o)}}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)}},se=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),ae=globalThis;ae[se]===void 0&&Object.defineProperty(ae,se,{configurable:!0,enumerable:!1,writable:!1,value:e=>new k(e)});var V=5,le=new WeakSet;function Xe(e){(typeof e=="object"&&e!==null||typeof e=="function")&&le.add(e)}function ze(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&le.has(e)}function Qe(e,t){let r=t?.error,n=N(t?.code)??N(r?.code)??`http_${e}`,o=j(t?.message)??j(r?.message)??Je(n,e);return new s.FloPayError(o,"api_error",{code:n,statusCode:e})}function Je(e,t){switch(e){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${V}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${t}).`}}async function ce(e,t,r){let{billingApiUrl:n,checkoutBaseUrl:o,items:u=[],subscriptions:c=[],products:a,account:i,successUrl:l,cancelUrl:m,checkoutMode:M="full",captureMethod:v,couponCodes:C=[],checkoutMetadata:Y,tagsData:G,redirectParams:ye={},setCookie:ge=!0,clientId:Te,currency:ve,utmMetadata:F,idempotencyKey:Ce}=e,X=(0,s.resolveIdempotencyKey)(Ce);if(C.length>V)throw new s.FloPayError(`Too many coupon codes \u2014 a checkout session accepts at most ${V}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let b=a??(0,s.foldIntoProducts)(u,c);(0,s.assertCaptureMethodEligible)({captureMethod:v,products:b});let y=(0,s.resolveSessionCurrency)(ve,u,c,b);if(!y)throw new s.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 S={clientId:Te,checkoutVersion:s.SDK_VERSION,successUrl:l,cancelUrl:m,currency:y,checkoutMode:M,products:b.map(p=>(0,s.buildProductPayload)(p,y)),accountData:{userId:i.userId,firstName:i.firstName??null,lastName:i.lastName??null,email:i.email,country:i.country??null,gender:i.gender??null,city:i.city??null,state:i.state??null,zip:i.zip??null,addressLine1:i.addressLine1??null,addressLine2:i.addressLine2??null},couponCodes:C};v==="manual"&&(S.captureMethod=v),Y!==void 0&&(S.checkoutMetadata=Y),G&&(S.tagsData=G),F&&F.length>0&&(S.utmMetadata=F);let be=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions`,z={"Content-Type":"application/json"};X&&(z[s.IDEMPOTENCY_KEY_HEADER]=X);let g,_,Se={method:"POST",headers:z,body:JSON.stringify(S),signal:t},E;try{r?.startAttempt(),E=await fetch(be,Se)}catch(p){throw Xe(p),p}try{r?.record(E.status)}catch{}g=E.status;try{_=await E.json()}catch{}if(g>=400)throw(0,s.withTelemetryHttpDiagnostics)(Qe(g,_),E);if(g===201){let p=_?.data?.uuid,O=_?.data?.nonce;if(!p)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!O)throw new s.FloPayError("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(b.length>0||y)&&I(p,{currency:y,products:b.map(d=>({code:d.code??d.providerItemId??d.providerPlanId,type:d.type,name:d.name??d.itemName??d.providerItemName??d.subscriptionName??d.providerPlanName??null,totalAmount:d.totalAmount,overrideAmount:d.overrideAmount,currency:d.currency??y}))});let w=new URL(`${o.replace(/\/+$/,"")}/secure`);w.searchParams.set("id",p);for(let[d,D]of Object.entries(ye))w.searchParams.set(d,D);if(ge&&typeof window<"u"&&typeof document<"u"){let d=JSON.stringify({origin_url:m}),D=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(d)}; domain=.${D}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(O)}; domain=.${D}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=w.toString()),{status:201,redirectUrl:w.toString(),nonce:O}}return g===204?(typeof window<"u"&&(window.location.href=l),{status:204}):{status:g}}async function ue(e){let t=he(e),r=de(t),n=$(e.timeoutMs);try{let o=await ce(e,n.signal,r);return r.commit(),me(t,o),o}catch(o){throw r.commit(),x(t,o),o}finally{n.clear(),T(t.reporter)}}function de(e){let t=!1,r=e.startedAt,n;return{startAttempt(){r=e.reporter.now()},record(o){n={status:o,durationMs:Math.max(0,e.reporter.now()-r),attempt:e.attempt}},commit(){if(t||!n)return;t=!0;let o=(0,s.telemetryStatusClass)(n.status);e.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:o,attempt:n.attempt}),e.reporter.performance({stage:"session_first_byte",durationMs:n.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:o,attempt:n.attempt})}}}function he(e){let t=new k({billingApiUrl:e.billingApiUrl,sdkVersion:s.SDK_VERSION,enabled:e.telemetry!==!1}),r=t.now();return t.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:t,startedAt:r,attempt:0}}function me(e,t){let r=(0,s.telemetryStatusClass)(t.status);e.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:r}),e.reporter.performance({stage:"session_create",durationMs:e.reporter.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:e.attempt})}function x(e,t){let{reporter:r}=e,n=(0,s.classifyTelemetryFailure)(t,"CHECKOUT_SESSION_CREATE_FAILED");if(r.performance({stage:"session_create",durationMs:r.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:n.statusClass,attempt:e.attempt}),t instanceof s.FloPayError&&t.type==="validation_error"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(n.statusClass==="4xx"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}r.error({...n,stage:"session_create",requestCategory:"session_create"})}function T(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}async function pe(e){let{maxRetries:t=2,...r}=e,n=he(e),o=de(n);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0||t>=3)throw n.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),T(n.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let u={...r,idempotencyKey:(0,s.resolveIdempotencyKey)(r.idempotencyKey)},c=$(r.timeoutMs),a;for(let i=0;i<=t;i++){n.attempt=i;try{let l=await ce(u,c.signal,o);return o.commit(),me(n,l),c.clear(),T(n.reporter),l}catch(l){a=l;let m=l instanceof Error&&l.name==="AbortError",M=ze(l),v=l instanceof s.FloPayError&&l.code===s.IDEMPOTENCY_IN_PROGRESS_CODE;if((m||M||v)&&!c.signal.aborted&&i<t){n.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:i+1});try{await J(i,c.signal)}catch(C){throw o.commit(),x(n,C),c.clear(),T(n.reporter),C}continue}throw o.commit(),x(n,l),c.clear(),T(n.reporter),l}}throw o.commit(),x(n,a),c.clear(),T(n.reporter),a??new Error("Unknown error during checkout session creation")}0&&(module.exports={cacheSessionDisplayData,clearSessionDisplayData,createCheckoutSession,createCheckoutSessionWithRetries,dropThirdPartyOnlyError,getSessionDisplayData,loadCheckoutRuntime});
|
package/dist/index.d.ts
CHANGED
|
@@ -4,15 +4,6 @@ export type { CheckoutRuntime, CheckoutRuntimeAutomaticPayment, CheckoutRuntimeE
|
|
|
4
4
|
export type { LoadCheckoutRuntimeOptions } from './checkout-runtime-loader.js';
|
|
5
5
|
export { loadCheckoutRuntime } from './checkout-runtime-loader.js';
|
|
6
6
|
export { createCheckoutSession, createCheckoutSessionWithRetries, } from './create-checkout-session.js';
|
|
7
|
-
export { FloPay } from './flopay.js';
|
|
8
|
-
export { loadFloPay } from './load.js';
|
|
9
|
-
export { PaymentAPI, SESSION_CREATE_TELEMETRY } from './payment-api.js';
|
|
10
|
-
export type { CardCaptureOperation, PciVaultCardCaptureConfig, } from './pci-vault-card-capture.js';
|
|
11
|
-
export { PciVaultCardCapture } from './pci-vault-card-capture.js';
|
|
12
|
-
export type { SavedCardChallengeDecline, SavedCardChallengeInput, SavedCardChallengeOutcome, SavedCardNextActionInput, } from './saved-card-action.js';
|
|
13
|
-
export { beginSavedCardChallengeTelemetry, completeSavedCardNextAction, createSavedCardActionAbortedError, runSavedCardChallenge, } from './saved-card-action.js';
|
|
14
7
|
export type { SessionDisplayCacheData, SessionDisplayProduct, } from './session-display-cache.js';
|
|
15
8
|
export { cacheSessionDisplayData, clearSessionDisplayData, getSessionDisplayData, } from './session-display-cache.js';
|
|
16
|
-
export type { StripeSafeAppearance } from './stripe-adapter.js';
|
|
17
|
-
export { StripeAdapter, toStripeAppearance, toStripeAppearanceTheme } from './stripe-adapter.js';
|
|
18
9
|
export type { ThreeDsChallengeAttempt } from './three-ds-challenge.js';
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as W,b as G,c as J,d as se,e as Q,f as Ne,g as Be,h as X,i as ae,j as le,k as ce,l as de,m as ue,n as z,o as A,p as qe,q as ze,r as me,s as Z,t as pe}from"./chunk-YGLB52ZW.mjs";import{dropThirdPartyOnlyError as tr}from"@flopay/shared";import{FloPayError as ye}from"@flopay/shared";var je="FloPayCheckoutRuntime",Ve=1e4,te=new Map;function Ke(e){return typeof e=="object"&&e!==null&&typeof e.mount=="function"}function ee(e){return new ye(e==="runtime_load_timeout"?"The checkout runtime did not load in time.":"The checkout runtime failed to load.","network_error",{code:e})}function $e(e,t){return new Promise((r,o)=>{let i=document.createElement("script"),s=!1,d=l=>{s||(s=!0,clearTimeout(n),i.removeEventListener("load",a),i.removeEventListener("error",c),l instanceof ye?(te.delete(e),i.remove(),o(l)):r(l))},a=()=>{let l=Reflect.get(globalThis,je);d(Ke(l)?l:ee("runtime_load_failed"))},c=()=>d(ee("runtime_load_failed")),n=setTimeout(()=>d(ee("runtime_load_timeout")),t);i.addEventListener("load",a),i.addEventListener("error",c),i.async=!0,i.src=e,document.head.appendChild(i)})}function He(e){let{runtimeUrl:t,timeoutMs:r=Ve}=e,o=te.get(t);if(o!==void 0)return o;let i=$e(t,r);return te.set(t,i),i}import{assertCaptureMethodEligible as Ye,buildProductPayload as We,classifyTelemetryFailure as Ge,FloPayError as U,foldIntoProducts as Je,IDEMPOTENCY_IN_PROGRESS_CODE as Qe,IDEMPOTENCY_KEY_HEADER as Xe,resolveIdempotencyKey as fe,resolveSessionCurrency as Ze,SDK_VERSION as ge,telemetryStatusClass as he,withTelemetryHttpDiagnostics as et}from"@flopay/shared";var oe=5,Ce=new WeakSet;function tt(e){(typeof e=="object"&&e!==null||typeof e=="function")&&Ce.add(e)}function rt(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&Ce.has(e)}function ot(e,t){let r=t?.error,o=W(t?.code)??W(r?.code)??`http_${e}`,i=G(t?.message)??G(r?.message)??nt(o,e);return new U(i,"api_error",{code:o,statusCode:e})}function nt(e,t){switch(e){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${oe}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${t}).`}}async function ve(e,t,r){let{billingApiUrl:o,checkoutBaseUrl:i,items:s=[],subscriptions:d=[],products:a,account:c,successUrl:n,cancelUrl:l,checkoutMode:m="confirm",captureMethod:h,couponCodes:w=[],checkoutMetadata:p,tagsData:g,redirectParams:I={},setCookie:f=!0,clientId:x,currency:P,utmMetadata:E,idempotencyKey:O}=e,F=fe(O);if(w.length>oe)throw new U(`Too many coupon codes \u2014 a checkout session accepts at most ${oe}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let k=a??Je(s,d);Ye({captureMethod:h,products:k});let _=Ze(P,s,d,k);if(!_)throw new U("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let C={clientId:x,checkoutVersion:ge,successUrl:n,cancelUrl:l,currency:_,checkoutMode:m,products:k.map(v=>We(v,_)),accountData:{userId:c.userId,firstName:c.firstName??null,lastName:c.lastName??null,email:c.email,country:c.country??null,gender:c.gender??null,city:c.city??null,state:c.state??null,zip:c.zip??null,addressLine1:c.addressLine1??null,addressLine2:c.addressLine2??null},couponCodes:w};h==="manual"&&(C.captureMethod=h),p!==void 0&&(C.checkoutMetadata=p),g&&(C.tagsData=g),E&&E.length>0&&(C.utmMetadata=E);let q=`${o.replace(/\/+$/,"")}/v1/checkouts/sessions`,L={"Content-Type":"application/json"};F&&(L[Xe]=F);let b,T,N={method:"POST",headers:L,body:JSON.stringify(C),signal:t},S;try{r?.startAttempt(),S=await fetch(q,N)}catch(v){throw tt(v),v}try{r?.record(S.status)}catch{}b=S.status;try{T=await S.json()}catch{}if(b>=400)throw et(ot(b,T),S);if(b===201){let v=T?.data?.uuid,M=T?.data?.nonce;if(!v)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!M)throw new U("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(k.length>0||_)&&Q(v,{currency:_,products:k.map(u=>({code:u.code??u.providerItemId??u.providerPlanId,type:u.type,name:u.name??u.itemName??u.providerItemName??u.subscriptionName??u.providerPlanName??null,totalAmount:u.totalAmount,overrideAmount:u.overrideAmount,currency:u.currency??_}))});let y=new URL(`${i.replace(/\/+$/,"")}/secure`);y.searchParams.set("id",v);for(let[u,R]of Object.entries(I))y.searchParams.set(u,R);if(f&&typeof window<"u"&&typeof document<"u"){let u=JSON.stringify({origin_url:l}),R=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(u)}; domain=.${R}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(M)}; domain=.${R}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=y.toString()),{status:201,redirectUrl:y.toString(),nonce:M}}return b===204?(typeof window<"u"&&(window.location.href=n),{status:204}):{status:b}}async function it(e){let t=_e(e),r=we(t),o=J(e.timeoutMs);try{let i=await ve(e,o.signal,r);return r.commit(),be(t,i),i}catch(i){throw r.commit(),j(t,i),i}finally{o.clear(),D(t.reporter)}}function we(e){let t=!1,r=e.startedAt,o;return{startAttempt(){r=e.reporter.now()},record(i){o={status:i,durationMs:Math.max(0,e.reporter.now()-r),attempt:e.attempt}},commit(){if(t||!o)return;t=!0;let i=he(o.status);e.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:i,attempt:o.attempt}),e.reporter.performance({stage:"session_first_byte",durationMs:o.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:i,attempt:o.attempt})}}}function _e(e){let t=new A({billingApiUrl:e.billingApiUrl,sdkVersion:ge,enabled:e.telemetry!==!1}),r=t.now();return t.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:t,startedAt:r,attempt:0}}function be(e,t){let r=he(t.status);e.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:r}),e.reporter.performance({stage:"session_create",durationMs:e.reporter.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:e.attempt})}function j(e,t){let{reporter:r}=e,o=Ge(t,"CHECKOUT_SESSION_CREATE_FAILED");if(r.performance({stage:"session_create",durationMs:r.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:e.attempt}),t instanceof U&&t.type==="validation_error"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(o.statusClass==="4xx"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}r.error({...o,stage:"session_create",requestCategory:"session_create"})}function D(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}async function st(e){let{maxRetries:t=2,...r}=e,o=_e(e),i=we(o);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0||t>=3)throw o.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),D(o.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let s={...r,idempotencyKey:fe(r.idempotencyKey)},d=J(r.timeoutMs),a;for(let c=0;c<=t;c++){o.attempt=c;try{let n=await ve(s,d.signal,i);return i.commit(),be(o,n),d.clear(),D(o.reporter),n}catch(n){a=n;let l=n instanceof Error&&n.name==="AbortError",m=rt(n),h=n instanceof U&&n.code===Qe;if((l||m||h)&&!d.signal.aborted&&c<t){o.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:c+1});try{await se(c,d.signal)}catch(w){throw i.commit(),j(o,w),d.clear(),D(o.reporter),w}continue}throw i.commit(),j(o,n),d.clear(),D(o.reporter),n}}throw i.commit(),j(o,a),d.clear(),D(o.reporter),a??new Error("Unknown error during checkout session creation")}import{classifyTelemetryFailure as at,FloPayError as V,resolveBillingApiUrl as Pe,SDK_VERSION as lt}from"@flopay/shared";var ke=Symbol.for("@flopay/js.telemetry.bridge.v1");function Se(e,t,r){let o=()=>t?.now()??r();Object.defineProperty(e,ke,{configurable:!1,enumerable:!1,writable:!1,value:{error:s=>t?.error(s),log:s=>t?.log(s),performance:s=>t?.performance(s),terminal:s=>t?.terminal(s),now:o,elapsed:s=>Math.max(0,o()-s),setCheckoutContext:s=>t?.setCheckoutContext(s),beginCheckout:(s={})=>t?.beginCheckout(s)??o(),disable:()=>t?.disable(),subscribe:s=>t?.subscribe(s)??(()=>{}),flush:()=>t?.flush()??Promise.resolve()}})}function Re(e){return e[ke]}var K=class{now(){return this.telemetryReporter?.now?.()??z()}constructor(t,r,o){this.provider=t,this.config=r,this.telemetryReporter=o??new A({billingApiUrl:Pe(r.billingApiUrl),sdkVersion:lt,enabled:r.telemetry!==!1}),Se(this,this.telemetryReporter,z)}cardCapture(t){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?pe({sessionId:t?.sessionId,captureMethod:t?.captureMethod,sessionToken:t?.sessionToken,billingApiUrl:this.config.billingApiUrl,cardFieldsTimeoutMs:t?.cardFieldsTimeoutMs},this.telemetryReporter):new Z({sessionId:t?.sessionId,captureMethod:t?.captureMethod,sessionToken:t?.sessionToken,billingApiUrl:this.config.billingApiUrl,cardFieldsTimeoutMs:t?.cardFieldsTimeoutMs,telemetry:!1})}async retrieveSession(t,r){if(!t)throw new V("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let o=await this.retrieveUnifiedSession(t,r);if(!o.data.session)throw new V("Session not found","api_error");return o.data.session}async retrieveUnifiedSession(t,r){if(!t)throw new V("sessionId is required.","validation_error",{param:"sessionId"});let o=Pe(r??this.config.billingApiUrl),i=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let s,d,a=n=>{if(s===void 0)return;let l=s,m=d;s=void 0,d=void 0,this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:n,attempt:m}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:l,durationMode:"machine",requestCategory:"session_read",statusClass:n,attempt:m})},c=me(o,{now:()=>this.telemetryReporter?.now()??z(),onFirstByte:(n,l)=>{s=n,d=l},onRetry:(n,l)=>{this.telemetryReporter?.log({name:"operation.retry",stage:n==="session_read"?"session_read":"processing",requestCategory:n,attempt:l})}});try{let n=await c.getUnifiedCheckoutSession(t);return a("2xx"),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-i,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),n}catch(n){let l=at(n,n instanceof V&&n.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw a(l.statusClass),this.telemetryReporter?.error({...l,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-i,durationMode:"machine",requestCategory:"session_read",statusClass:l.statusClass}),n}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.provider.destroy()}};function Ee(e,t,r){let o=K;return new o(e,t,r)}import{FloPayError as mt,resolveBillingApiUrl as ne,SDK_VERSION as xe}from"@flopay/shared";import{FloPayError as Te}from"@flopay/shared";import{loadStripe as ct}from"@stripe/stripe-js";import{toStripeAppearance as dt,toStripeAppearanceTheme as ut}from"@flopay/shared";var Ae=new WeakSet;function Ie(e){return e instanceof Te&&Ae.has(e)}var B=class{constructor(){this.name="stripe";this.stripe=null}async initialize(t){if(typeof window>"u")return;let r=await ct(t.publishableKey,{locale:t.locale??"auto"});if(!r){let o=new Te("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw Ae.add(o),o}this.stripe=r}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var Fe=new Map;function ie(e){return Array.isArray(e)?e.map(ie):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,ie(r)])):e}function pt(e,t){return JSON.stringify([e,ne(t?.billingApiUrl),t?.telemetry!==!1,t?.locale??"auto",t?.apiVersion??null,ie(t?.appearance??null)])}var $=new Map;async function yt(e,t){if(!e){let a=new A({billingApiUrl:ne(t?.billingApiUrl),sdkVersion:xe,enabled:t?.telemetry!==!1});throw a.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),a.flush().catch(()=>{}).finally(()=>a.destroy()),new mt("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let r=pt(e,t),o=Fe.get(r);if(o)return t?.telemetry!==!1&&Re(o)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),o;let i=$.get(r);if(i)return i;let s={...t,publishableKey:e},d=(async()=>{let a=new A({billingApiUrl:ne(s.billingApiUrl),sdkVersion:xe,enabled:s.telemetry!==!1}),c=a.now();a.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),a.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),a.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let n=new B,l=a.now();try{await n.initialize(s)}catch(w){throw a.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:Ie(w)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),a.destroy(),w}let m=a.now();a.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),a.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),a.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),a.performance({stage:"sdk_initialize",durationMs:m-c,durationMode:"machine",provider:"stripe"}),a.performance({stage:"provider_ready",durationMs:m-l,durationMode:"machine",provider:"stripe"});let h=Ee(n,s,a);return Fe.set(r,h),h})();$.set(r,d);try{return await d}finally{$.get(r)===d&&$.delete(r)}}import{FloPayError as Y,THREE_DS_CHALLENGE_WINDOW_MS as De}from"@flopay/shared";var ft=4,gt=1e3,ht=1e3,Ct=15e3;function vt(e){let t=!!e?.gateways?.stripe,r=!!e?.gateways?.worldpayCorporateGateway;return t===r?"unknown":t?"stripe":"worldpay"}function wt(e,t,r){try{return typeof e?.beginThreeDsChallenge!="function"?void 0:e.beginThreeDsChallenge(t,{provider:vt(r)})}catch{return}}function H(e){return new Y("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Ue(){return new Y("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function Oe(e){return e.replace(/\/+$/,"")}function _t(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}function bt(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",r=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":case"authorized":case"pending":case"timeout":return{status:t,providerIntentId:r};case"declined":return{status:"declined",providerIntentId:r,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:r,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}async function Le(e){if(typeof document>"u"||typeof window>"u")throw new Y("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});let t=X(e.telemetry);t.record("handoff_planned");let r=ae(e.nextActionRedirectUrl);r==="missing"?t.record("action_missing",{reason:"missing_url"}):r==="invalid"&&t.record("action_invalid",{reason:"invalid_url"});let o=p=>{let g=le(p);if(g==="buyer_cancel"){t.record("cancel_requested",{reason:g,evidenceBasis:"signal_reason"}),t.terminal("cancel",{reason:g,evidenceBasis:"signal_reason"});return}t.record("abort_observed",{reason:g,evidenceBasis:"signal_reason"}),t.terminal("abort",{reason:g,evidenceBasis:"signal_reason"})},i=p=>{(p.status==="succeeded"||p.status==="authorized"||p.status==="declined"||p.status==="timeout")&&t.reconcile(p.status)};if(e.signal?.aborted)throw o(e.signal.reason),H();let s=`${Oe(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,d=async()=>{let p=new AbortController,g=()=>p.abort();e.signal?.aborted?p.abort():e.signal?.addEventListener("abort",g);let I=window.setTimeout(()=>p.abort(),Ct);try{let f=await fetch(s,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json",...t.attemptId?{"x-flopay-challenge-attempt":t.attemptId}:{}},body:"{}",signal:p.signal});if(!f.ok)return{status:"unknown"};let x=await f.json().catch(()=>null),P=bt(x);return i(P),P}catch{return{status:"unknown"}}finally{window.clearTimeout(I),e.signal?.removeEventListener("abort",g)}},a,c=()=>e.pollCompletionEndpoint!==!1?d():(a??(a=d()),a),n=document.activeElement instanceof HTMLElement?document.activeElement:null,l=document.createElement("div");l.setAttribute("data-flopay-auto-3ds-overlay","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let m=document.createElement("iframe");m.setAttribute("title","Card authentication"),m.setAttribute("allow","payment"),m.tabIndex=0,m.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let h=null;try{h=new URL(e.billingApiUrl,window.location.href).origin}catch{h=null}let w=ue(e.nextActionRedirectUrl);try{let p=await new Promise((g,I)=>{let f=!1,x=0,P=0,E=0,O=!1,F=!1,k=!1,_=0,C=()=>{window.clearTimeout(x),window.clearInterval(P),window.clearTimeout(E),window.removeEventListener("message",v),window.removeEventListener("pagehide",L),document.removeEventListener("securitypolicyviolation",b),m.removeEventListener("load",T),e.signal?.removeEventListener("abort",N)},q=async()=>{if(!(f||O)){O=!0;try{let y=await c();if(f||!_t(y))return;f=!0,C(),t.terminal("status_poll",{evidenceBasis:"server_status"}),g(y)}finally{O=!1}}},L=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},b=y=>{if(k)return;let u=de(y,w);u&&(k=!0,t.record("policy_violation",{reason:u,evidenceBasis:"parent_csp_event"}))},T=()=>{F||(F=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"})),e.pollCompletionEndpoint!==!1&&(window.clearTimeout(E),E=window.setTimeout(()=>{q()},250))},N=()=>{f||(f=!0,C(),o(e.signal?.reason),I(H()))},S=y=>{f||_>=ft||(_+=1,t.record("return_rejected",{reason:y,evidenceBasis:"message_origin_check"}))},v=y=>{let u=y.data,R=!!u&&typeof u=="object"&&u.source==="flopay-vault-3ds-return";if(y.source!==m.contentWindow){R&&S("untrusted_source");return}if(h&&y.origin!==h){R&&S("untrusted_origin");return}R&&(f||(f=!0,C(),t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),g(null)))};x=window.setTimeout(()=>{f||(f=!0,C(),F||t.record("load_unconfirmed",{evidenceBasis:"no_load_signal"}),t.record("timer_expired",{reason:"window_elapsed",evidenceBasis:"timer"}),t.terminal("timer",{reason:"window_elapsed",evidenceBasis:"timer"}),I(Ue()))},De),e.pollCompletionEndpoint!==!1&&(P=window.setInterval(()=>{q()},ht)),m.addEventListener("load",T),window.addEventListener("message",v),window.addEventListener("pagehide",L),document.addEventListener("securitypolicyviolation",b),e.signal?.addEventListener("abort",N),m.src=e.nextActionRedirectUrl,t.record("render_attempted");try{l.appendChild(m),document.body.appendChild(l)}catch(y){throw f=!0,C(),t.record("render_failed"),y}t.record("container_attached"),t.record("navigation_assigned");let M=ce(l);M&&t.record("container_visibility",{reason:M,evidenceBasis:"parent_computed_style"}),m.focus(),e.signal?.aborted&&N()});return p||await c()}finally{l.parentNode?.removeChild(l),t.record("teardown"),n?.isConnected&&n.focus()}}function Me(e,t){try{let r=t.data.session?.status;r==="complete"?e.reconcile("succeeded"):r==="authorized"&&e.reconcile("authorized")}catch{}}function kt(e){return new Y("Card was declined.","api_error",{code:e.declineReason??"authorization_declined",...e.gatewayDeclineReason?{declineCode:e.gatewayDeclineReason}:{}})}async function St(e,t){let r=`${Oe(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/status`,o=new AbortController,i=new AbortController,s=()=>{o.abort(e.signal?.reason),i.abort(e.signal?.reason)};e.signal?.aborted?s():e.signal?.addEventListener("abort",s,{once:!0});let d=X(e.telemetry),a=Le({billingApiUrl:e.billingApiUrl,sessionId:e.sessionId,nonce:e.nonce,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o.signal,pollCompletionEndpoint:!1,...e.telemetry?{telemetry:e.telemetry}:{}}),c=t.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:gt,nonce:e.nonce,statusUrl:r,continueAfterActionRequired:!0,timeoutMs:De+15e3,signal:i.signal,...d.attemptId?{challengeAttemptId:d.attemptId}:{}});c.catch(()=>{}),a.catch(()=>{});try{let n=await Promise.race([a,c]);if("data"in n)return d.terminal("status_poll",{evidenceBasis:"server_status"}),Me(d,n),n;if(n.status==="declined")throw(e.createDeclineError??kt)(n);if(n.status==="timeout")throw Ue();let l=await c;return Me(d,l),l}catch(n){throw e.signal?.aborted||n instanceof Error&&n.name==="AbortError"?H(n):n}finally{e.signal?.removeEventListener("abort",s),o.abort(),i.abort()}}export{K as FloPay,ze as PaymentAPI,Z as PciVaultCardCapture,qe as SESSION_CREATE_TELEMETRY,B as StripeAdapter,wt as beginSavedCardChallengeTelemetry,Q as cacheSessionDisplayData,Be as clearSessionDisplayData,St as completeSavedCardNextAction,it as createCheckoutSession,st as createCheckoutSessionWithRetries,H as createSavedCardActionAbortedError,tr as dropThirdPartyOnlyError,Ne as getSessionDisplayData,He as loadCheckoutRuntime,yt as loadFloPay,Le as runSavedCardChallenge,dt as toStripeAppearance,ut as toStripeAppearanceTheme};
|
|
1
|
+
import{dropThirdPartyOnlyError as kt}from"@flopay/shared";import{FloPayError as G}from"@flopay/shared";var ve="FloPayCheckoutRuntime",Ce=1e4,O=new Map;function be(e){return typeof e=="object"&&e!==null&&typeof e.mount=="function"}function F(e){return new G(e==="runtime_load_timeout"?"The checkout runtime did not load in time.":"The checkout runtime failed to load.","network_error",{code:e})}function Se(e,t){return new Promise((r,n)=>{let o=document.createElement("script"),c=!1,l=d=>{c||(c=!0,clearTimeout(a),o.removeEventListener("load",s),o.removeEventListener("error",i),d instanceof G?(O.delete(e),o.remove(),n(d)):r(d))},s=()=>{let d=Reflect.get(globalThis,ve);l(be(d)?d:F("runtime_load_failed"))},i=()=>l(F("runtime_load_failed")),a=setTimeout(()=>l(F("runtime_load_timeout")),t);o.addEventListener("load",s),o.addEventListener("error",i),o.async=!0,o.src=e,document.head.appendChild(o)})}function Ee(e){let{runtimeUrl:t,timeoutMs:r=Ce}=e,n=O.get(t);if(n!==void 0)return n;let o=Se(t,r);return O.set(t,o),o}import{assertCaptureMethodEligible as Ye,buildProductPayload as Ge,classifyTelemetryFailure as Xe,FloPayError as g,foldIntoProducts as ze,IDEMPOTENCY_IN_PROGRESS_CODE as Qe,IDEMPOTENCY_KEY_HEADER as Je,resolveIdempotencyKey as oe,resolveSessionCurrency as We,SDK_VERSION as ie,telemetryStatusClass as se,withTelemetryHttpDiagnostics as Ze}from"@flopay/shared";function q(e){return typeof e=="string"&&e.trim()?e:void 0}function L(e){if(typeof e=="string")return e.trim()?e:void 0;if(Array.isArray(e))return e.filter(r=>typeof r=="string"&&r.trim().length>0).join("; ")||void 0}function U(e=12e3){let t=Number.isFinite(e)&&e>=0?e:12e3,r=new AbortController,n=setTimeout(()=>r.abort(),t);return{signal:r.signal,clear:()=>clearTimeout(n)}}function ke(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function X(e,t){let r=150*2**e,n=Math.round(r*(.75+Math.random()*.5));return new Promise((o,c)=>{let l,s=()=>t.removeEventListener("abort",i),i=()=>{l!==void 0&&clearTimeout(l),s(),c(ke())};if(t.aborted){i();return}l=setTimeout(()=>{s(),o()},n),t.addEventListener("abort",i,{once:!0})})}var _e="flopay_session_display:";var D=new Map;function R(e){return`${_e}${e}`}function B(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function N(e,t,r){if(!e)return;let n=r?.ttlMs??36e5,o={data:t,expiresAt:Date.now()+n},c=B();if(c)try{c.setItem(R(e),JSON.stringify(o));return}catch{}D.set(e,o)}function we(e){if(!e)return null;let t=B();if(t)try{let n=t.getItem(R(e));if(n){let o=JSON.parse(n);if(o&&typeof o.expiresAt=="number"&&o.expiresAt>Date.now())return o.data;t.removeItem(R(e))}}catch{}let r=D.get(e);if(r){if(r.expiresAt>Date.now())return r.data;D.delete(e)}return null}function De(e){if(!e)return;D.delete(e);let t=B();if(t)try{t.removeItem(R(e))}catch{}}import{buildTelemetryErrorEvent as J,buildTelemetryLogEvent as W,buildTelemetryPerformanceEvent as Fe,buildTelemetryTerminalEvent as Oe,serializeTelemetryBatch as qe,TELEMETRY_MAX_BATCH_BYTES as Le}from"@flopay/shared";import{isThreeDsChallengeAttemptId as Re}from"@flopay/shared";var Ae=32,z=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function Ie(){let e=globalThis,t=e[z];if(t instanceof Map)return t;let r=new Map;try{Object.defineProperty(e,z,{configurable:!0,enumerable:!1,writable:!1,value:r})}catch{}return r}function Pe(e,t){let r=Ie(),n=r.get(e);if(n)return n;for(;r.size>=Ae;){let c=r.keys().next();if(c.done)break;r.delete(c.value)}let o={nextSequence:0,startedAt:t,terminated:!1,reconciled:new Set,provider:"unknown"};return r.set(e,o),o}var xe=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),Me=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function Q(e,t={}){let r=Re(t.attemptId)?t.attemptId.toLowerCase():e.newAttemptId(),n=()=>{try{let s=e.now();return Number.isFinite(s)?s:0}catch{return 0}},o=Pe(r,n());(t.provider==="stripe"||t.provider==="worldpay")&&(o.provider=t.provider);let c=o.provider,l=(s,i)=>{if(o.terminated&&!Me.has(s))return;let a={attemptId:r,phase:s,attemptSequence:o.nextSequence,elapsedMs:Math.max(0,n()-o.startedAt),provider:c};o.nextSequence+=1,i.reason!==void 0&&(a.reason=i.reason),i.evidenceBasis!==void 0&&(a.evidenceBasis=i.evidenceBasis),i.terminalSource!==void 0&&(a.terminalSource=i.terminalSource),i.providerOutcome!==void 0&&(a.providerOutcome=i.providerOutcome);try{e.emit(a,xe.has(s))}catch{}};return{attemptId:r,record(s,i={}){s==="browser_terminal"||s==="provider_reconciled"||l(s,{reason:i.reason,evidenceBasis:i.evidenceBasis})},terminal(s,i={}){o.terminated||(l("browser_terminal",{terminalSource:s,reason:i.reason,evidenceBasis:i.evidenceBasis}),o.terminated=!0)},reconcile(s){o.reconciled.has(s)||(o.reconciled.add(s),l("provider_reconciled",{providerOutcome:s,evidenceBasis:"provider_fact"}))}}}var Ue="/v1/sdk-telemetry/events",A=16,Z=64,Be=1500,ee=1e3,Ne=64,je="00000000-0000-4000-8000-000000000000",$e={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},He=48;function m(){try{return globalThis.crypto.randomUUID()}catch{let e=new Uint8Array(16);try{globalThis.crypto.getRandomValues(e)}catch{for(let r=0;r<e.length;r+=1)e[r]=Math.floor(Math.random()*256)}e[6]=(e[6]??0)&15|64,e[8]=(e[8]??0)&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}}function Ke(e){try{return new TextEncoder().encode(e).byteLength}catch{return e.length}}function Ve(e){return JSON.stringify([e.code,e.failureCategory,e.reason,e.stage,e.provider,e.attempt,e.statusClass,e.requestCategory,e.paymentMethodCategory,e.walletType,e.operationOutcome,e.checkoutMode,e.layout,e.inAppBrowser,e.appFamily,e.popupCapability,e.presentationMode,e.terminalReason])}function te(){return globalThis.performance?.now()??0}var E=class{constructor(t){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=()=>{typeof document<"u"&&document.visibilityState==="hidden"&&this.flush()};this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0};this.endpoint=`${t.billingApiUrl.replace(/\/+$/,"")}${Ue}`,this.sdkPackage=t.sdkPackage??"@flopay/js",this.sdkVersion=t.sdkVersion,this.correlationId=m(),this.merchantEnabled=t.enabled!==!1,this.clock=t.clock??te,this.browserTransportAvailable=typeof window<"u"&&typeof document<"u",this.browserTransportAvailable&&(window.addEventListener("pagehide",this.pageExitHandler),document.addEventListener("visibilitychange",this.visibilityHandler))}log(t){this.notify({...t,class:"lifecycle"}),this.canCollect()&&this.enqueue(W({...this.checkoutContext,...t,eventId:m(),sequence:this.sequence++}))}error(t){if(this.notify({...t,class:"technical_error"}),!this.canCollect())return;let r=J({...this.checkoutContext,...t,eventId:je,sequence:0}),n=Ve(r),o=this.now();this.pruneReportedFailures(o);let c=this.reportedFailures.get(n);if(c!==void 0&&o>=c&&o-c<ee){this.log({name:"operation.deduplicated",stage:t.stage,provider:t.provider,paymentMethodCategory:t.paymentMethodCategory,attempt:t.attempt,inAppBrowser:t.inAppBrowser,appFamily:t.appFamily,popupCapability:t.popupCapability,presentationMode:t.presentationMode,terminalReason:t.terminalReason});return}this.rememberReportedFailure(n,o),this.enqueue(J({...this.checkoutContext,...t,eventId:m(),sequence:this.sequence++}))}performance(t){this.canCollect()&&this.enqueue(Fe({...this.checkoutContext,...t,eventId:m(),sequence:this.sequence++}))}terminal(t){if(this.canCollect()&&(this.enqueue(Oe({...this.checkoutContext,...t,eventId:m(),sequence:this.sequence++})),t.outcome!=="action_required"&&this.checkoutStartedAt!==null)){let r=this.checkoutStartedAt;this.checkoutStartedAt=null,this.performance({...t,stage:"total_journey",durationMs:Math.max(0,this.now()-r),durationMode:"total"})}}beginThreeDsChallenge(t={}){return Q({now:()=>this.now(),newAttemptId:m,emit:(r,n)=>this.recordThreeDsChallenge(r,n)},t)}recordThreeDsChallenge(t,r){if(!this.canCollect()||this.threeDsChallengeCount>=He)return;let n=W({...this.checkoutContext,...t,name:"three_ds.challenge",stage:"three_ds_handoff",eventId:m(),sequence:this.sequence++});if(!(this.queue.length>=Z)){if(this.threeDsChallengeCount+=1,this.queue.push(n),r){this.drainQueue();return}if(this.queue.length>=A){this.flush();return}this.scheduleFlush()}}now(){try{return this.clock()}catch{return te()}}subscribe(t){return this.destroyed?()=>{}:(this.observers.add(t),()=>this.observers.delete(t))}notify(t){if(!this.destroyed)for(let r of this.observers)try{r(t)}catch{}}pruneReportedFailures(t){for(let[r,n]of this.reportedFailures)(t<n||t-n>=ee)&&this.reportedFailures.delete(r)}rememberReportedFailure(t,r){for(;this.reportedFailures.size>=Ne;){let n=this.reportedFailures.keys().next();if(n.done)break;this.reportedFailures.delete(n.value)}this.reportedFailures.set(t,r)}setCheckoutContext(t){this.checkoutContext={checkoutMode:t.checkoutMode,layout:t.layout}}beginCheckout(t={}){return this.canCollect()?(this.drainQueue(),this.setCheckoutContext(t),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(t){if(this.canCollect()&&!(this.queue.length>=Z||this.eventCounts[t.class]>=$e[t.class])){if(this.eventCounts[t.class]+=1,this.queue.push(t),this.queue.length>=A){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 t=this.queue.splice(0,A);return this.flushInFlight=this.sendBatch(t).finally(()=>{this.flushInFlight=null,this.queue.length>0&&this.scheduleFlush()}),this.flushInFlight}destroy(){this.destroyed||(this.drainQueue(),this.destroyed=!0,this.clearFlushTimer(),this.browserTransportAvailable&&(typeof window<"u"&&window.removeEventListener("pagehide",this.pageExitHandler),typeof document<"u"&&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 t=this.queue.splice(0,A);this.sendBatch(t)}}async sendBatch(t){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let r=qe(t,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:m()});if(Ke(r)>Le)return;let n=typeof AbortController>"u"?null:new AbortController,o=null;try{let c=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:r,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:n?.signal}).then(async i=>{if(i.status!==202)return null;let a=null;try{a=await i.json()}catch{}return a?.status==="disabled"?"disabled":null}).catch(()=>null),l=new Promise(i=>{o=setTimeout(()=>{n?.abort(),i(null)},Be)});await Promise.race([c,l])==="disabled"&&this.disableFromIngestion()}catch{}finally{o&&clearTimeout(o)}}disableFromIngestion(){this.ingestionDisabled=!0,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}scheduleFlush(){this.flushTimer||this.destroyed||this.ingestionDisabled||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush()},0))}clearFlushTimer(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}},re=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),ne=globalThis;ne[re]===void 0&&Object.defineProperty(ne,re,{configurable:!0,enumerable:!1,writable:!1,value:e=>new E(e)});var $=5,ae=new WeakSet;function et(e){(typeof e=="object"&&e!==null||typeof e=="function")&&ae.add(e)}function tt(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&ae.has(e)}function rt(e,t){let r=t?.error,n=q(t?.code)??q(r?.code)??`http_${e}`,o=L(t?.message)??L(r?.message)??nt(n,e);return new g(o,"api_error",{code:n,statusCode:e})}function nt(e,t){switch(e){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${$}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${t}).`}}async function le(e,t,r){let{billingApiUrl:n,checkoutBaseUrl:o,items:c=[],subscriptions:l=[],products:s,account:i,successUrl:a,cancelUrl:d,checkoutMode:P="full",captureMethod:T,couponCodes:v=[],checkoutMetadata:H,tagsData:K,redirectParams:he={},setCookie:me=!0,clientId:pe,currency:fe,utmMetadata:x,idempotencyKey:ye}=e,V=oe(ye);if(v.length>$)throw new g(`Too many coupon codes \u2014 a checkout session accepts at most ${$}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let C=s??ze(c,l);Ye({captureMethod:T,products:C});let p=We(fe,c,l,C);if(!p)throw new g("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 b={clientId:pe,checkoutVersion:ie,successUrl:a,cancelUrl:d,currency:p,checkoutMode:P,products:C.map(h=>Ge(h,p)),accountData:{userId:i.userId,firstName:i.firstName??null,lastName:i.lastName??null,email:i.email,country:i.country??null,gender:i.gender??null,city:i.city??null,state:i.state??null,zip:i.zip??null,addressLine1:i.addressLine1??null,addressLine2:i.addressLine2??null},couponCodes:v};T==="manual"&&(b.captureMethod=T),H!==void 0&&(b.checkoutMetadata=H),K&&(b.tagsData=K),x&&x.length>0&&(b.utmMetadata=x);let ge=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions`,Y={"Content-Type":"application/json"};V&&(Y[Je]=V);let f,k,Te={method:"POST",headers:Y,body:JSON.stringify(b),signal:t},S;try{r?.startAttempt(),S=await fetch(ge,Te)}catch(h){throw et(h),h}try{r?.record(S.status)}catch{}f=S.status;try{k=await S.json()}catch{}if(f>=400)throw Ze(rt(f,k),S);if(f===201){let h=k?.data?.uuid,M=k?.data?.nonce;if(!h)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!M)throw new g("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(C.length>0||p)&&N(h,{currency:p,products:C.map(u=>({code:u.code??u.providerItemId??u.providerPlanId,type:u.type,name:u.name??u.itemName??u.providerItemName??u.subscriptionName??u.providerPlanName??null,totalAmount:u.totalAmount,overrideAmount:u.overrideAmount,currency:u.currency??p}))});let _=new URL(`${o.replace(/\/+$/,"")}/secure`);_.searchParams.set("id",h);for(let[u,w]of Object.entries(he))_.searchParams.set(u,w);if(me&&typeof window<"u"&&typeof document<"u"){let u=JSON.stringify({origin_url:d}),w=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(u)}; domain=.${w}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(M)}; domain=.${w}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=_.toString()),{status:201,redirectUrl:_.toString(),nonce:M}}return f===204?(typeof window<"u"&&(window.location.href=a),{status:204}):{status:f}}async function ot(e){let t=ue(e),r=ce(t),n=U(e.timeoutMs);try{let o=await le(e,n.signal,r);return r.commit(),de(t,o),o}catch(o){throw r.commit(),I(t,o),o}finally{n.clear(),y(t.reporter)}}function ce(e){let t=!1,r=e.startedAt,n;return{startAttempt(){r=e.reporter.now()},record(o){n={status:o,durationMs:Math.max(0,e.reporter.now()-r),attempt:e.attempt}},commit(){if(t||!n)return;t=!0;let o=se(n.status);e.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:o,attempt:n.attempt}),e.reporter.performance({stage:"session_first_byte",durationMs:n.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:o,attempt:n.attempt})}}}function ue(e){let t=new E({billingApiUrl:e.billingApiUrl,sdkVersion:ie,enabled:e.telemetry!==!1}),r=t.now();return t.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:t,startedAt:r,attempt:0}}function de(e,t){let r=se(t.status);e.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:r}),e.reporter.performance({stage:"session_create",durationMs:e.reporter.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:e.attempt})}function I(e,t){let{reporter:r}=e,n=Xe(t,"CHECKOUT_SESSION_CREATE_FAILED");if(r.performance({stage:"session_create",durationMs:r.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:n.statusClass,attempt:e.attempt}),t instanceof g&&t.type==="validation_error"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(n.statusClass==="4xx"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}r.error({...n,stage:"session_create",requestCategory:"session_create"})}function y(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}async function it(e){let{maxRetries:t=2,...r}=e,n=ue(e),o=ce(n);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0||t>=3)throw n.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),y(n.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let c={...r,idempotencyKey:oe(r.idempotencyKey)},l=U(r.timeoutMs),s;for(let i=0;i<=t;i++){n.attempt=i;try{let a=await le(c,l.signal,o);return o.commit(),de(n,a),l.clear(),y(n.reporter),a}catch(a){s=a;let d=a instanceof Error&&a.name==="AbortError",P=tt(a),T=a instanceof g&&a.code===Qe;if((d||P||T)&&!l.signal.aborted&&i<t){n.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:i+1});try{await X(i,l.signal)}catch(v){throw o.commit(),I(n,v),l.clear(),y(n.reporter),v}continue}throw o.commit(),I(n,a),l.clear(),y(n.reporter),a}}throw o.commit(),I(n,s),l.clear(),y(n.reporter),s??new Error("Unknown error during checkout session creation")}export{N as cacheSessionDisplayData,De as clearSessionDisplayData,ot as createCheckoutSession,it as createCheckoutSessionWithRetries,kt as dropThirdPartyOnlyError,we as getSessionDisplayData,Ee as loadCheckoutRuntime};
|
package/dist/payment-api.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type { AdvertisedPaymentMethod,
|
|
1
|
+
import type { AdvertisedPaymentMethod, CheckoutSessionMode, CreateSessionIntentRequest, InlineSessionDraft, PaymentMethodLayout, PaymentMethodLayoutRules, ProcessPaymentParams, SessionIntentDeclineRequest, SessionIntentResult, TelemetryPaymentMethodCategory, TelemetryRequestCategory, VaultCaptureBlock } from '@flopay/shared';
|
|
2
|
+
import type { CheckoutGateways, DetachedCheckoutSession, NormalizedCheckoutSession } from './checkout-runtime/providers/session-gateways.js';
|
|
2
3
|
import type { SessionDisplayCacheData } from './session-display-cache.js';
|
|
3
4
|
import type { BeginThreeDsChallengeInput, ThreeDsChallengeAttempt } from './three-ds-challenge.js';
|
|
4
5
|
/** Raw billing API response wrapper. */
|
|
@@ -134,7 +135,6 @@ interface PaymentApiTelemetryHooks {
|
|
|
134
135
|
onSessionCreateFailure?: (error: unknown) => void;
|
|
135
136
|
onRetry?: (requestCategory: TelemetryRequestCategory, attempt: number) => void;
|
|
136
137
|
}
|
|
137
|
-
export declare const SESSION_CREATE_TELEMETRY: unique symbol;
|
|
138
138
|
/**
|
|
139
139
|
* Client-side payment API service.
|
|
140
140
|
*
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { CaptureMethod, CardCaptureAdapter, CardCaptureEventType, CardCaptureMountOptions, CardCaptureOutcomeEvent, CardCaptureProviderId, CardFieldLabels, CardFieldPlaceholders, CardFieldsEvent, VaultCardFieldKey, VaultCardThemeColors } from '@flopay/shared';
|
|
2
2
|
import { TelemetryReporter } from './telemetry-reporter.js';
|
|
3
3
|
/** Browser operation hosted by the PCIVault card-capture adapter. */
|
|
4
|
-
|
|
4
|
+
type CardCaptureOperation = 'checkout' | 'card_setup';
|
|
5
5
|
/** Configuration for a {@link PciVaultCardCapture} instance. */
|
|
6
6
|
export interface PciVaultCardCaptureConfig {
|
|
7
7
|
/** Checkout session id bound to the capture (for outcome correlation + trust). */
|
|
@@ -387,3 +387,4 @@ export declare class PciVaultCardCapture implements CardCaptureAdapter {
|
|
|
387
387
|
}
|
|
388
388
|
/** Build the adapter with the existing SDK reporter without publishing injection. */
|
|
389
389
|
export declare function createInstrumentedPciVaultCardCapture(config: PciVaultCardCaptureConfig, reporter: TelemetryReporter): PciVaultCardCapture;
|
|
390
|
+
export {};
|