@flopay/js 1.20.12 → 1.20.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/card-setup.cjs +1 -1
- package/dist/card-setup.mjs +1 -1
- package/dist/checkout-runtime/hosted.d.ts +3 -2
- package/dist/chunk-YGLB52ZW.mjs +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/pci-vault-card-capture.d.ts +40 -0
- package/package.json +3 -3
- package/dist/chunk-5FTMB7TO.mjs +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var xe=Object.defineProperty;var Vt=Object.getOwnPropertyDescriptor;var zt=Object.getOwnPropertyNames;var jt=Object.prototype.hasOwnProperty;var Ht=(r,e)=>{for(var t in e)xe(r,t,{get:e[t],enumerable:!0})},Kt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of zt(e))!jt.call(r,i)&&i!==t&&xe(r,i,{get:()=>e[i],enumerable:!(n=Vt(e,i))||n.enumerable});return r};var $t=r=>Kt(xe({},"__esModule",{value:!0}),r);var Sn={};Ht(Sn,{FloPay:()=>ye,PaymentAPI:()=>Q,PciVaultCardCapture:()=>X,SESSION_CREATE_TELEMETRY:()=>ze,StripeAdapter:()=>ie,beginSavedCardChallengeTelemetry:()=>Ut,cacheSessionDisplayData:()=>W,clearSessionDisplayData:()=>Te,completeSavedCardNextAction:()=>Nt,createCheckoutSession:()=>nt,createCheckoutSessionWithRetries:()=>at,createSavedCardActionAbortedError:()=>ge,dropThirdPartyOnlyError:()=>Bt.dropThirdPartyOnlyError,getSessionDisplayData:()=>ve,loadCheckoutRuntime:()=>Ge,loadFloPay:()=>xt,runSavedCardChallenge:()=>$e,toStripeAppearance:()=>oe.toStripeAppearance,toStripeAppearanceTheme:()=>oe.toStripeAppearanceTheme});module.exports=$t(Sn);var Bt=require("@flopay/shared");var Le=require("@flopay/shared"),Gt="FloPayCheckoutRuntime",Yt=1e4,Ue=new Map;function Wt(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 Jt(r,e){return new Promise((t,n)=>{let i=document.createElement("script"),o=!1,s=u=>{o||(o=!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,Gt);s(Wt(u)?u:Oe("runtime_load_failed"))},l=()=>s(Oe("runtime_load_failed")),c=setTimeout(()=>s(Oe("runtime_load_timeout")),e);i.addEventListener("load",a),i.addEventListener("error",l),i.async=!0,i.src=r,document.head.appendChild(i)})}function Ge(r){let{runtimeUrl:e,timeoutMs:t=Yt}=r,n=Ue.get(e);if(n!==void 0)return n;let i=Jt(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 Qt(){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,o)=>{let s,a=()=>e.removeEventListener("abort",l),l=()=>{s!==void 0&&clearTimeout(s),a(),o(Qt())};if(e.aborted){l();return}s=setTimeout(()=>{a(),i()},n),e.addEventListener("abort",l,{once:!0})})}var Xt="flopay_session_display:";var fe=new Map;function Ce(r){return`${Xt}${r}`}function qe(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function W(r,e,t){if(!r)return;let n=t?.ttlMs??36e5,i={data:e,expiresAt:Date.now()+n},o=qe();if(o)try{o.setItem(Ce(r),JSON.stringify(i));return}catch{}fe.set(r,i)}function ve(r){if(!r)return null;let e=qe();if(e)try{let n=e.getItem(Ce(r));if(n){let i=JSON.parse(n);if(i&&typeof i.expiresAt=="number"&&i.expiresAt>Date.now())return i.data;e.removeItem(Ce(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(Ce(r))}catch{}}var k=require("@flopay/shared");var Ne=require("@flopay/shared"),Zt=32,Ye=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function er(){let r=globalThis,e=r[Ye];if(e instanceof Map)return e;let t=new Map;try{Object.defineProperty(r,Ye,{configurable:!0,enumerable:!1,writable:!1,value:t})}catch{}return t}function tr(r,e){let t=er(),n=t.get(r);if(n)return n;for(;t.size>=Zt;){let o=t.keys().next();if(o.done)break;t.delete(o.value)}let i={nextSequence:0,startedAt:e,terminated:!1,reconciled:new Set,provider:"unknown"};return t.set(r,i),i}var rr=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),nr=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function We(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=tr(t,n());(e.provider==="stripe"||e.provider==="worldpay")&&(i.provider=e.provider);let o=i.provider,s=(a,l)=>{if(i.terminated&&!nr.has(a))return;let c={attemptId:t,phase:a,attemptSequence:i.nextSequence,elapsedMs:Math.max(0,n()-i.startedAt),provider:o};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,rr.has(a))}catch{}};return{attemptId:t,record(a,l={}){a==="browser_terminal"||a==="provider_reconciled"||s(a,{reason:l.reason,evidenceBasis:l.evidenceBasis})},terminal(a,l={}){i.terminated||(s("browser_terminal",{terminalSource:a,reason:l.reason,evidenceBasis:l.evidenceBasis}),i.terminated=!0)},reconcile(a){i.reconciled.has(a)||(i.reconciled.add(a),s("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 Je(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 Se(r){try{return ue(r)==="valid"?new URL(r).origin:null}catch{return null}}var ir="/v1/sdk-telemetry/events",Re=16,Qe=64,or=1500,Xe=1e3,sr=64,ar="00000000-0000-4000-8000-000000000000",lr={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},cr=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 dr(r){try{return new TextEncoder().encode(r).byteLength}catch{return r.length}}function ur(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(/\/+$/,"")}${ir}`,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:ar,sequence:0}),n=ur(t),i=this.now();this.pruneReportedFailures(i);let o=this.reportedFailures.get(n);if(o!==void 0&&i>=o&&i-o<Xe){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 We({now:()=>this.now(),newAttemptId:H,emit:(t,n)=>this.recordThreeDsChallenge(t,n)},e)}recordThreeDsChallenge(e,t){if(!this.canCollect()||this.threeDsChallengeCount>=cr)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>=Qe)){if(this.threeDsChallengeCount+=1,this.queue.push(n),t){this.drainQueue();return}if(this.queue.length>=Re){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>=Xe)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=sr;){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>=Qe||this.eventCounts[e.class]>=lr[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=Re){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,Re);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,Re);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(dr(t)>k.TELEMETRY_MAX_BATCH_BYTES)return;let n=typeof AbortController>"u"?null:new AbortController,i=null;try{let o=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),s=new Promise(l=>{i=setTimeout(()=>{n?.abort(),l(null)},or)});await Promise.race([o,s])==="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)}},Ze=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),et=globalThis;et[Ze]===void 0&&Object.defineProperty(et,Ze,{configurable:!0,enumerable:!1,writable:!1,value:r=>new A(r)});var Be=5,tt=new WeakSet;function mr(r){(typeof r=="object"&&r!==null||typeof r=="function")&&tt.add(r)}function pr(r){return(typeof r=="object"&&r!==null||typeof r=="function")&&tt.has(r)}function hr(r,e){let t=e?.error,n=le(e?.code)??le(t?.code)??`http_${r}`,i=ce(e?.message)??ce(t?.message)??yr(n,r);return new T.FloPayError(i,"api_error",{code:n,statusCode:r})}function yr(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 rt(r,e,t){let{billingApiUrl:n,checkoutBaseUrl:i,items:o=[],subscriptions:s=[],products:a,account:l,successUrl:c,cancelUrl:u,checkoutMode:h="confirm",captureMethod:p,couponCodes:y=[],checkoutMetadata:m,tagsData:g,redirectParams:v={},setCookie:f=!0,clientId:S,currency:C,utmMetadata:F,idempotencyKey:G}=r,V=(0,T.resolveIdempotencyKey)(G);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)(o,s);(0,T.assertCaptureMethodEligible)({captureMethod:p,products:x});let I=(0,T.resolveSessionCurrency)(C,o,s,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 w={clientId:S,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"&&(w.captureMethod=p),m!==void 0&&(w.checkoutMetadata=m),g&&(w.tagsData=g),F&&F.length>0&&(w.utmMetadata=F);let Z=`${n.replace(/\/+$/,"")}/v1/checkouts/sessions`,se={"Content-Type":"application/json"};V&&(se[T.IDEMPOTENCY_KEY_HEADER]=V);let U,Y,ae={method:"POST",headers:se,body:JSON.stringify(w),signal:e},z;try{t?.startAttempt(),z=await fetch(Z,ae)}catch(P){throw mr(P),P}try{t?.record(z.status)}catch{}U=z.status;try{Y=await z.json()}catch{}if(U>=400)throw(0,T.withTelemetryHttpDiagnostics)(hr(U,Y),z);if(U===201){let P=Y?.data?.uuid,ee=Y?.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)&&W(P,{currency:I,products:x.map(b=>({code:b.code??b.providerItemId??b.providerPlanId,type:b.type,name:b.name??b.itemName??b.providerItemName??b.subscriptionName??b.providerPlanName??null,totalAmount:b.totalAmount,overrideAmount:b.overrideAmount,currency:b.currency??I}))});let R=new URL(`${i.replace(/\/+$/,"")}/secure`);R.searchParams.set("id",P);for(let[b,j]of Object.entries(v))R.searchParams.set(b,j);if(f&&typeof window<"u"&&typeof document<"u"){let b=JSON.stringify({origin_url:u}),j=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(b)}; 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=R.toString()),{status:201,redirectUrl:R.toString(),nonce:ee}}return U===204?(typeof window<"u"&&(window.location.href=c),{status:204}):{status:U}}async function nt(r){let e=ot(r),t=it(e),n=L(r.timeoutMs);try{let i=await rt(r,n.signal,t);return t.commit(),st(e,i),i}catch(i){throw t.commit(),we(e,i),i}finally{n.clear(),re(e.reporter)}}function it(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 st(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 we(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 at(r){let{maxRetries:e=2,...t}=r,n=ot(r),i=it(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 o={...t,idempotencyKey:(0,T.resolveIdempotencyKey)(t.idempotencyKey)},s=L(t.timeoutMs),a;for(let l=0;l<=e;l++){n.attempt=l;try{let c=await rt(o,s.signal,i);return i.commit(),st(n,c),s.clear(),re(n.reporter),c}catch(c){a=c;let u=c instanceof Error&&c.name==="AbortError",h=pr(c),p=c instanceof T.FloPayError&&c.code===T.IDEMPOTENCY_IN_PROGRESS_CODE;if((u||h||p)&&!s.signal.aborted&&l<e){n.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:l+1});try{await te(l,s.signal)}catch(y){throw i.commit(),we(n,y),s.clear(),re(n.reporter),y}continue}throw i.commit(),we(n,c),s.clear(),re(n.reporter),c}}throw i.commit(),we(n,a),s.clear(),re(n.reporter),a??new Error("Unknown error during checkout session creation")}var M=require("@flopay/shared");var d=require("@flopay/shared");function gr(r){return r==="on_session"||r==="off_session"}function fr(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 vr="x-flopay-process-result-source",Tr="status",Ct=new WeakSet;function br(r,e){let t=new d.FloPayError(r,"api_error",{code:e,statusCode:500});return Ct.add(t),t}function _r(r){return typeof r=="object"&&r!==null&&Ct.has(r)}function lt(r){return r?.result==="DECLINE"||r?.result==="ERROR"}var Sr=50,J=new Map;function Rr(r,e){return J.get(r)?.has(e)===!0}function wr(r,e){let t=J.get(r)??new Set;if(t.add(e),J.delete(r),J.set(r,t),J.size>Sr){let n=J.keys().next().value;n!==void 0&&J.delete(n)}}function Ar(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 ct=0,dt=500,Ae=15e3,ut=15e3,kr=3e3,Er=1e4,Mr=1e4;function pe(r){return typeof r=="object"&&r!==null}function K(r,e){return le(r?.[e])}function mt(r,e){return ce(r?.[e])}function Ir(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(o),n(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},o=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=mt(t,"message")??mt(n,"message")??e,o=K(t,"code")??K(t,"gatewayErrorCode")??K(n,"code")??`http_${r.status}`;return(0,d.withTelemetryHttpDiagnostics)(new d.FloPayError(i,"api_error",{code:o,statusCode:r.status}),r)}async function Pr(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 Dr(r){if(!(!pe(r)||typeof r.required!="boolean"))return{required:r.required,provider:"turnstile"}}async function Fr(r){let e=r.status===400?await r.clone().json().catch(()=>null):null;return(0,d.classifyPaymentRejection)(r.status,e)}function pt(r){return r===400||r===422}var Me=2;async function ke(r,e,t=Me,n,i){let o;for(let s=0;;s++)try{return i?.(s),await fetch(r,e)}catch(a){if(e?.signal?.aborted||a instanceof Error&&a.name==="AbortError")throw a;if(o=a,s>=t)throw o;try{n?.(s+1)}catch{}await Ee(150*2**s,e?.signal??void 0)}}var xr=2e3,Or=1e4,Ur=150;async function Lr(r){try{let t=(await r.json())?.data?.status;return t==="closed"||t==="not_open"?t:"failed"}catch{return"failed"}}async function ht(r,e,t){let n=new AbortController,i=()=>n.abort();t?.addEventListener("abort",i,{once:!0});let o,s=new Promise(a=>{o=setTimeout(()=>{n.abort(),a("timeout")},Or)});try{let a=await Promise.race([fetch(r,{...e,signal:n.signal}),s]);return a==="timeout"?"failed":a.status>=500?"retry":a.ok?await Lr(a):"failed"}catch{return n.signal.aborted?"failed":"retry"}finally{clearTimeout(o),t?.removeEventListener("abort",i)}}function qr(r,e){return new Promise(t=>{let n=setTimeout(t,e);r.then(()=>{clearTimeout(n),t()},()=>{clearTimeout(n),t()})})}var yt="stripe-account-switch-v1",ze=Symbol.for("@flopay/js.session-create.telemetry.v1");function Nr(r){return r[ze]}function Br(r){return"now"in r||"onFirstByte"in r||"onSessionCreateFailure"in r||"onRetry"in r}function vt(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 Tt(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 gt(r){if(typeof r!="string")return;let e=r.trim();return e.length>0?e:void 0}function Vr(r){let e={};if(r.country&&(e.country=r.country),!(0,d.isCardHolderNamePlaceholder)(r.firstName,r.lastName)){let t=gt(r.firstName),n=gt(r.lastName);t&&(e.firstName=t),n&&(e.lastName=n)}return Object.keys(e).length>0?e:void 0}function zr(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=Vr(r.account);i&&(n.accountData=i),Tt(n,r);let o=jr(t);return o&&(n.routingProducts=o),n}function jr(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 ft(r,e,t){return{currency:e,products:t.map(n=>(0,d.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[],accountData:vt(r.account)}}function Hr(r,e,t){return{currency:e,products:t.map(n=>(0,d.buildProductPayload)(n,e)),couponCodes:r.couponCodes??[]}}function Kr(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 o=i.trim();o&&(e[n]=o)}return{accountData:e}}var O=class O{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let n=Br(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,o="unknown"){let s=(0,d.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...s,..._r(e)?{reason:"capture_failed"}:{},stage:n,requestCategory:i,paymentMethodCategory:o})}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 o=this.telemetryTimestamp(),s=o,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},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,s=this.telemetryTimestamp()});c=!0;let h=Math.max(0,this.telemetryTimestamp()-s);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()-o),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){W(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 o=O.pendingThreeDsAbandonReports.get(e),s=o===void 0?this.requestVaultCapture(e,t):qr(o,xr).then(()=>this.requestVaultCapture(e,t));O.activeVaultCaptureRequests.set(n,s);try{return await s}finally{O.activeVaultCaptureRequests.get(n)===s&&O.activeVaultCaptureRequests.delete(n)}}async requestVaultCapture(e,t){let n=new AbortController,i=setTimeout(()=>n.abort(),Mr);this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let s={"Content-Type":"application/json"};t&&(s["x-checkout-session-token"]=t);try{let a=await ke(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:s,signal:n.signal},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 Pr(a))return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-o),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()-o),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 o=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:i});let{nonce:s,paymentMethodCategory:a,...l}=t,c=Ar(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":s},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:s,paymentMethodCategory:i,submittedIntentId:c})}if(!u.ok&&u.status!==202){let p=await Fr(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:s,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()-o),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 o=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let s=i?.timeoutMs??Er,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(),s);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()-o),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 o=n,s=o.paymentMethodType,a=typeof s=="string"&&s.trim().toLowerCase()==="card",l=typeof s=="string"&&s.length>0&&!a&&(typeof o.paymentMethodId=="string"||o.paymentMethodId===null),c=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(o.intentKind==="payment"||o.intentKind==="setup"),u=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodId===null&&(o.paymentMethodType==="paypal"&&o.intentKind==="payment"||o.paymentMethodType===d.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&(o.intentKind==="payment"||o.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=o.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 v=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:m,body:JSON.stringify({...n,authorizationAttemptId:p}),signal:i?.signal});if(!v.ok){g=!0;let w=await N(v,"Failed to create checkout intent"),Z=(0,d.classifyTelemetryFailure)(w,"PAYMENT_PROCESSING_FAILED");throw pt(w.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...Z,stage:"processing",requestCategory:"intent_create"}),w}let f=await v.json();if(v.status===202&&pe(f)&&f.type==="checkout_processing")return g=!0,await this.settleProcessingSessionIntent(f,v,e,t,n);let S=f.data;if(!S||typeof S!="object")throw new d.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let C=S,F=C.paymentMethodType,G=(C.paymentMethodCategory==="wallet"||C.paymentMethodCategory==="apm")&&typeof F=="string"&&F.trim().toLowerCase()!=="card"&&(typeof C.paymentMethodId=="string"||C.paymentMethodId===null)&&typeof C.providerObjectId=="string",V=C.provider==="stripe"&&(C.intentKind==="payment"||C.intentKind==="setup")&&typeof C.clientSecret=="string",x=C.provider==="paypal"&&C.paymentMethodCategory==="wallet"&&C.paymentMethodId===null&&(C.paymentMethodType==="paypal"&&C.intentKind==="payment"&&(C.providerObjectType==="order"||C.providerObjectType==="subscription")||C.paymentMethodType===d.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&C.intentKind==="payment"&&C.providerObjectType==="order"||C.paymentMethodType===d.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&C.intentKind==="setup"&&C.providerObjectType==="setup_token")&&C.clientSecret===null,I=C.provider===n.provider&&C.paymentMethodCategory===n.paymentMethodCategory&&C.paymentMethodType===n.paymentMethodType&&C.paymentMethodId===n.paymentMethodId&&C.intentKind===n.intentKind;if(!G||!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)(v.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-y),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,d.telemetryStatusClass)(v.status)}),C}catch(v){throw g||this.reportDirectFailure(v,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),v}}async settleProcessingSessionIntent(e,t,n,i,o){let s=this.toCheckoutProcessingPending(e,t,n);try{return{settled:!0,response:await this.resolveCheckoutProcessing(s,n,{nonce:i,paymentMethodCategory:o.provider==="paypal"?"paypal":o.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:s.sessionId,cause:a}):a}}closeThreeDsChallenge(e,t,n,i={}){if(!e||!t||!n||i.signal?.aborted)return Promise.resolve("failed");let o=this.requestThreeDsChallengeClose(e,t,n,i.signal),s=O.pendingThreeDsAbandonReports;return s.set(e,o),o.then(()=>{s.get(e)===o&&s.delete(e)}),o}async requestThreeDsChallengeClose(e,t,n,i){let o=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/3ds/abandoned`,s={method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify({providerIntentId:n})};try{let a=await ht(o,s,i);if(a!=="retry")return a;if(i?.aborted)return"failed";await Ee(Ur,i);let l=await ht(o,s,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 o=n,s=o.providerDeclineReason,a=o.paymentMethodType,l=o.providerIntentId,c=typeof s=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(s)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(s),u=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&c,h=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(l===void 0||typeof l=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(l)),p=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.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:s}:{provider:"stripe",paymentMethodCategory:o.paymentMethodCategory,paymentMethodType:o.paymentMethodType,providerDeclineReason:s,...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 o=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(o.status===404||o.status===405)return null;if(!o.ok)throw await N(o,"Failed to resolve the payment method layout");let s=await o.json();return(0,d.normalizePaymentMethodLayout)(s?.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,o=t?.limit??1,s=new URLSearchParams({email:e,page:String(i),limit:String(o),sortField:"createdAt",sortDirection:"DESC"});try{let a=await fetch(`${this.baseUrl}/v1/payments?${s.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 o=e.account.email?.trim();if(o&&!(0,d.isValidEmail)(o))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 o=await this.createAndFetchSessionRequest(e,n.signal,i);return this.adoptDirectTelemetryCheckout(o.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}),o}catch(o){throw this.reportSessionCreateFailure(o,t,i),o}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 o=(0,d.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,i);if(!o)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 s={clientId:e.clientId,checkoutVersion:d.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:o,checkoutMode:e.checkoutMode??"full",products:i.map(c=>(0,d.buildProductPayload)(c,o)),accountData:vt(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(s.captureMethod=e.captureMethod),e.tokenizedData&&(s.tokenizedData=e.tokenizedData),Tt(s,e);let a=await this.postCheckoutSessionCreate(s,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 o={"Content-Type":"application/json",[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION},s=(0,d.resolveIdempotencyKey)(t.idempotencyKey);s&&(o[d.IDEMPOTENCY_KEY_HEADER]=s);let a=[];t.checkoutMode==="auto"&&a.push(d.ASYNC_AUTO_CHECKOUT_CAPABILITY),this.stripeAccountSwitch&&e.deferDataAttachment===!0&&a.push(yt),a.length>0&&(o[d.FLO_SDK_CAPABILITIES_HEADER]=a.join(", "));let l,c=!1,u=Nr(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:o,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 S=y+1;p(S),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 v=await N(l,"Failed to create checkout session");if(v.code===d.IDEMPOTENCY_IN_PROGRESS_CODE&&y<2){p(y+1),await te(y,n);continue}throw h(y,m,g),v}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 o=e.products??(0,d.foldIntoProducts)(e.items,e.subscriptions);try{(0,d.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:o})}catch(f){throw n.clear(),this.reportSessionCreateFailure(f,t,i),f}let s=(0,d.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,o);if(!s)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{ft(e,s,o)}catch(f){throw n.clear(),this.reportSessionCreateFailure(f,t,i),f}let a,l,c=!1;try{let f=await this.postCheckoutSessionCreate(zr(e,s,o),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?Hr(e,s,o):ft(e,s,o),{params:e,startedAt:t,deadline:y,createAttempt:i.attempt}),g=p?void 0:m,v=(f={})=>{if(g!==void 0)return g;let S={...e,account:{...e.account,...f,email:f.email?.trim()||e.account.email?.trim()}};return(0,d.isValidEmail)(S.account.email)?(g=m.then(()=>{let C=this.telemetryTimestamp();return this.claimCheckoutSession(u,h,Kr(S.account),{params:S,startedAt:C,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:v}}async claimCheckoutSession(e,t,n,i){let o=i?.startedAt??this.telemetryTimestamp(),s=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]:yt}:{}},body:l,signal:a.signal})}catch(g){let v=a.signal.aborted||g instanceof Error&&g.name==="AbortError";if(c=v?"timeout":"network_error",v||u>=2)throw g;try{this.telemetryHooks?.onRetry?.("session_claim",u+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:u+1})}catch{}await 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()-s),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()-o),durationMode:"machine",requestCategory:"session_create",statusClass:c,attempt:i?.createAttempt??u}),m}catch(p){throw h&&(0,d.markSessionResponseReceived)(p),this.reportSessionCreateFailure(p,s,{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 o=(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:o.statusClass,attempt:n.attempt}),e instanceof d.FloPayError&&e.type==="validation_error"||e instanceof d.FloPayError&&pt(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({...o,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 o=t?.timeoutMs??Ae,s=Date.now()+o,a=new AbortController,l=!1,c,u=setTimeout(()=>{c=setTimeout(()=>{l=!0,a.abort()},ut)},o),h=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?h():t?.signal?.addEventListener("abort",h,{once:!0});let p=this.clampRetryAfterMs(t?.initialDelayMs??ct),y=0;try{if(t?.statusUrl){let m=await this.waitForCheckoutStatus(e,{initialDelayMs:p,timeoutMs:o,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=s-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()>=s)throw D()}let g=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,a.signal),v=g.data.session?.status;if(v==="authorized"||v==="complete"||v==="expired")return this.reportRecoveryCompleted(n,i,t?.challengeAttemptId),g;if(Date.now()>=s)throw D();p=this.clampRetryAfterMs(Math.max(p*2,dt))}}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,o){let s=t.latestTransactionAttempt;if(this.rememberReportedFailure(e,t),s?.result==="DECLINE"){let c=s.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:s.code??s.declineReason??"authorization_declined",statusCode:400})}if(s?.result==="ERROR"||t.status==="voided")throw br("Payment could not be completed. Please try again.",s?.code??"payment_processing_error");let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,n,i)}catch(c){if(!o?.()||!Ve(c))throw c;a={providers:[],mode:"tokenize",data:{},raw:t}}let l=a.data.session;return l&&s?.result==="SUCCESS"?{...a,data:{...a.data,session:{...l,status:"complete"}}}:l&&s?.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"}}}:s?.result!=="ACTION_REQUIRED"?a:s.gateway==="paypal"&&s.providerIntentId?{...a,autoProcessingError:{type:"paypal_direct_required",message:"PayPal authorization required",orderId:s.providerIntentId,checkoutMethod:"paypal"}}:s.nextActionRedirectUrl?{...a,autoProcessingError:{type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:s.nextActionRedirectUrl}}:a}async waitForCheckoutStatus(e,t){let n=t.timeoutMs??Ae,i=Date.now()+n,o=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let s=i-Date.now();if(s<=0||o>0&&(await Ee(Math.min(o,s),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((S,C)=>{c=C}):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((S,C)=>{p=setTimeout(()=>{C(D()),l.abort()},a+ut)}),m;try{let S=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,l.signal);m=await Promise.race([S,y,u].filter(C=>C!==null))}finally{p!==void 0&&clearTimeout(p),t.signal?.removeEventListener("abort",h)}if(!m)return null;let g=lt(m.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,m,t.submittedIntentId);if(m.status==="completed"||m.status==="authorized"||m.status==="expired"||m.status==="voided")return g?{...m,latestTransactionAttempt:null}:m;let v=m.latestTransactionAttempt?.result,f=t.pollAfterAction===!0&&v==="ACTION_REQUIRED";if(!g&&v!==void 0&&v!=="PENDING"&&!f)return m;o=this.clampRetryAfterMs(Math.max(o*2,dt))}}isOwnFailedAttempt(e,t,n){let i=t.latestTransactionAttempt?.providerIntentId??null;return n!==void 0?i===n:i===null?!0:!Rr(t.uuid||e,i)}rememberReportedFailure(e,t){let n=t.latestTransactionAttempt;!lt(n)||!n.providerIntentId||wr(t.uuid||e,n.providerIntentId)}async fetchCheckoutStatus(e,t,n,i){let o=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,s=o;if(n)try{let u=new URL(n,`${this.baseUrl}/`),h=new URL(o);u.origin===h.origin&&(s=u.toString())}catch{}let a={[d.FLO_SDK_VERSION_HEADER]:d.SDK_VERSION};t&&(a["x-checkout-session-token"]=t);let l=await ke(s,{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)},o=t.stripe;if(o?.publishableKey){n.push("stripe");let l=[e.stripeClientSecret,o.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);i.stripe={clientSecret:l??"",publishableKey:o.publishableKey??void 0,paypalPublishableKey:o.paypalPublishableKey??void 0,environment:o.environment,enabledPaymentMethods:Array.isArray(o.enabledPaymentMethods)?o.enabledPaymentMethods.filter(c=>typeof c=="string"):void 0}}let s=t.paypal;return s?.publishableKey&&(n.push("paypal"),i.paypal={publishableKey:s.publishableKey,environment:s.environment,providerObjectType:s.providerObjectType,approvalPresentation:s.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),o=n?e.totalAmount:i,s=Math.round(o*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:s,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}:{},...gr(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(fr)}:{},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=Dr(e.verification);return{html:typeof e.html=="string"?e.html:void 0,url:typeof e.url=="string"?e.url:void 0,messageToken:typeof e.messageToken=="string"?e.messageToken:void 0,expectedOrigin:typeof e.expectedOrigin=="string"?e.expectedOrigin:void 0,...t?{verification:t}:{}}}toCheckoutSessionStatus(e){return e==="completed"?"complete":e==="authorized"?"authorized":e==="expired"?"expired":"open"}async resolveProcessResponse(e,t,n){if(e.status!==202)return e;let i=await e.json().catch(()=>null),o=this.toCheckoutProcessingPending(i,e,t);return this.resolveCheckoutProcessing(o,t,n)}async resolveCheckoutProcessing(e,t,n){let i=n?.pollTimeoutMs??Ae,o=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 s=await this.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:o-Date.now(),nonce:n?.nonce,paymentMethodCategory:n?.paymentMethodCategory});return this.toProcessResponseFromSession(s,t)}async toProcessResponseFromStatus(e,t,n){let i=e.latestTransactionAttempt?.result,o={[vr]:Tr},s={"Content-Type":"application/json",...o};if(e.status==="completed"||i==="SUCCESS")return new Response(null,{status:204,statusText:"No Content",headers:o});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:s});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:s})}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:s});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:s});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:s});throw D()}async reconcileProcessPayment(e,t){let n=t?.pollTimeoutMs??Ae,i=Date.now()+n,o=null;try{o=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(o)return this.toProcessResponseFromStatus(o,e,t?.nonce);let s=i-Date.now();if(s<=0)throw D();let a=await this.waitForCheckoutSessionCompletion(e,{initialDelayMs:0,timeoutMs:s,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"),o=i===null||i.trim()===""?void 0:Number(i),s=o!==void 0&&Number.isFinite(o)?o*1e3:void 0;return{type:"checkout_processing",sessionId:K(e,"sessionId")??n,retryAfterMs:this.clampRetryAfterMs(Ir(e,"retryAfterMs")??s??ct),statusUrl:K(e,"statusUrl"),sessionUrl:K(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,kr))}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,o=(0,d.resolveSessionCurrency)(t.currency,i?void 0:t.items,i?void 0:t.subscriptions,n);W(e,{currency:o??void 0,products:n.map(s=>({code:s.code??s.providerItemId??s.providerPlanId,type:s.type,name:s.name??s.itemName??s.providerItemName??s.subscriptionName??s.providerPlanName??null,totalAmount:s.totalAmount,overrideAmount:s.overrideAmount,currency:s.currency??o??void 0}))})}mergeCachedDisplayData(e){let t=ve(e.uuid),n=new Map,i=s=>s?`code:${s}`:void 0;for(let s of t?.products??[]){let a=i(s.code);a&&n.set(a,s)}let o=(e.products??[]).map(s=>{let a=i(s.code),l=a?n.get(a):void 0;return{...s,name:s.name??l?.name??null,totalAmount:s.totalAmount??l?.totalAmount,overrideAmount:s.overrideAmount??l?.overrideAmount,currency:s.currency??l?.currency}});return{...e,currency:e.currency??t?.currency,products:o}}};O.activeVaultCaptureRequests=new Map,O.pendingThreeDsAbandonReports=new Map;var Q=O;function bt(r,e){let t=Q;return new t(r,e)}var _=require("@flopay/shared");var Pe=require("@flopay/shared");function _t(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 o of Array.from(e.querySelectorAll("script[src], iframe[src]"))){let s=_t(o.getAttribute("src"));if(s&&t.add(s),o.tagName==="SCRIPT"){let a=()=>this.fail("load_error");o.addEventListener("error",a),n.push(()=>o.removeEventListener("error",a))}}let i=o=>{let s=_t(o.blockedURI);s&&t.has(s)&&this.fail("blocked")};document.addEventListener("securitypolicyviolation",i),n.push(()=>document.removeEventListener("securitypolicyviolation",i)),this.detach=()=>{for(let o of n)o()}}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 $r=4,De="flopay-vault",Gr=3e4,Yr=_.THREE_DS_CHALLENGE_WINDOW_MS+Gr,Wr="Card authentication timed out.",St={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 Jr(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:Jr(r),data:e})}catch{}}function he(r,e){return(0,_.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:r,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var Qr=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function Xr(r){return typeof r=="string"&&Qr.has(r)?r:"unknown"}var Zr=new Set(["verification_failed","verification_expired"]);function en(r){return r==null?!0:typeof r=="string"&&Zr.has(r)}var tn="vault_mount";function rn(r){return r.failureStage===tn}function je(r,e){return r&&!rn(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:Xr(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function Rt(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 nn(r,e,t,n="checkout"){let{type:i}=r;if(i==="complete"||i==="decline")return(0,_.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:Rt(r,t,n),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(i==="error"){let a=je(e,r);return(0,_.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[o,s]=St[i];return he(o,s)}function on(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 sn(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 an(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 ln(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===De&&e.type==="validation"&&Array.isArray(e.messages)}function cn(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 dn(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===De&&e.type==="fields_interactive"}function un(r){let e=r.capabilities;return Array.isArray(e)&&e.includes("fields_interactive")}var mn=["number","expiry","cvv","name"];function pn(r){if(r===null||typeof r!="object")return;let e=r,t={};for(let n of mn){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.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,_.resolveBillingApiUrl)(e.billingApiUrl),sdkVersion:_.SDK_VERSION}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new A({billingApiUrl:(0,_.resolveBillingApiUrl)(this.config.billingApiUrl),sdkVersion:_.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 _.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 _.FloPayError("No vault capture widget HTML was provided to mount the secure card form.","api_error",{code:"card_capture_no_widget_html"});this.container=e,this.verificationRequired=t.verificationRequired===!0,this.messageToken=t.messageToken??null,this.expectedOrigin=t.expectedOrigin??this.config.expectedOrigin??null,this.theme=t.theme,t.submitLabel!==void 0&&(this.submitLabel=t.submitLabel);try{this.attachMessageListener(),this.injectWidget(e,t.html),this.cardFields.watch(e)}catch(i){throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),i}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postCardBrandIcons(),this.postCardFieldLabels(),this.postCardFieldPlaceholders(),this.postSubmitLabel(),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})}reportVaultLoadFailure(){this.telemetryReporter?.error({errorCode:"VAULT_LOAD_FAILED",failureCategory:"provider_runtime",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})}on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>{this.listeners.get(e)?.delete(t)}}onCardFields(e){return this.cardFields.subscribe(e)}failCardFieldsMount(){this.cardFields.fail("other"),this.cardFields.end()}reportCardFields(e){let t=e.type==="card_fields_ready",n=this.config.sessionId;this.telemetryReporter?.log({name:t?"vault.fields.ready":"vault.fields.failed",stage:t?"vault_ready":"vault_mount",provider:"pcivault",paymentMethodCategory:"card",elapsedMs:e.elapsedMs,...e.type==="card_fields_failed"?{loadFailureReason:e.reason}:{},...n?{checkoutSessionId:n}:{}})}unmount(){if(this.cardFields.end(),this.actionChallenge){let{telemetry:e}=this.actionChallenge;e.record("abort_observed",{reason:"component_unmount",evidenceBasis:"signal_reason"}),e.terminal("abort",{reason:"component_unmount",evidenceBasis:"signal_reason"})}this.lastChallengeTelemetry=null,this.hideActionRequiredOverlay(),this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.container&&(this.container.replaceChildren(),this.container=null),this.messageToken=null,this.expectedOrigin=null,this.ownsTelemetryReporter&&(this.telemetryReporter?.destroy(),this.telemetryReporter=void 0)}injectWidget(e,t){e.innerHTML=t;let n=Array.from(e.querySelectorAll("script"));for(let i of n){let o=document.createElement("script");for(let s of Array.from(i.attributes))o.setAttribute(s.name,s.value);o.text=i.text,i.replaceWith(o)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let n=t.data;if(cn(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;this.applyHeight(n.height);return}if(ln(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(dn(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let c=typeof n.sessionId=="string"?n.sessionId:void 0;if(this.config.sessionId&&c&&c!==this.config.sessionId)return;this.cardFields.ready();return}if(!on(n)||this.messageToken&&n.messageToken!==this.messageToken)return;let i=this.config.sessionId,o=typeof n.sessionId=="string"?n.sessionId:void 0;if(i&&o&&o!==i||(n.type==="complete"||n.type==="decline")&&i&&o!==i)return;let s=an(n.paymentMethod),a=sn(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}:{},...s?{paymentMethod:s}:{}};n.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??E()),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(nn(n,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(n),n.type==="error"&&je(this.submissionStarted,n).errorCode==="VAULT_LOAD_FAILED"&&this.cardFields.fail("load_error")),n.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postCardBrandIcons(),this.postCardFieldLabels(),this.postCardFieldPlaceholders(),this.postSubmitLabel(),un(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&&en(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:Rt(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="error"){let s=je(this.submissionStarted,e);t.log({name:"vault.terminal",stage:s.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...s,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 s=this.submissionStartedAt;this.submissionStartedAt=null,s!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-s),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[i,o]=St[n];t.log({name:i,stage:o,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,_.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:o}=this;!n||!i||!o||this.postToHostedWindow({source:"flopay-vault-host",type:"cardFieldLabels",sessionId:n,messageToken:i,...e===void 0?{}:{show:e},...t===void 0?{}:{labels:{...t}}},o)}setCardFieldPlaceholders(e){let t=pn(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=Se(e),i=!1,o=m=>{if(i)return;let g=_e(m,n);g&&(i=!0,t.record("policy_violation",{reason:g,evidenceBasis:"parent_csp_event"}))},s=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},a={telemetry:t,loaded:!1,detach:()=>{document.removeEventListener("securitypolicyviolation",o),window.removeEventListener("pagehide",s)}};this.actionChallenge=a,this.lastChallengeTelemetry=t,t.record("handoff_planned"),ue(e)==="invalid"&&t.record("action_invalid",{reason:"invalid_url"}),document.addEventListener("securitypolicyviolation",o),window.addEventListener("pagehide",s);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,v=!!g&&typeof g=="object"&&g.source==="flopay-vault-3ds-return";if(m.source!==c.contentWindow){v&&h<$r&&(h+=1,t.record("return_rejected",{reason:"untrusted_source",evidenceBasis:"message_origin_check"}));return}v&&(t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),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()},Yr)}reportChallengeAbandoned(){ne((0,_.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:Wr})}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 Q((0,_.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 wt(r,e){let t=X;return new t(r,{reporter:e})}var At=Symbol.for("@flopay/js.telemetry.bridge.v1");function kt(r,e,t){let n=()=>e?.now()??t();Object.defineProperty(r,At,{configurable:!1,enumerable:!1,writable:!1,value:{error:o=>e?.error(o),log:o=>e?.log(o),performance:o=>e?.performance(o),terminal:o=>e?.terminal(o),now:n,elapsed:o=>Math.max(0,n()-o),setCheckoutContext:o=>e?.setCheckoutContext(o),beginCheckout:(o={})=>e?.beginCheckout(o)??n(),disable:()=>e?.disable(),subscribe:o=>e?.subscribe(o)??(()=>{}),flush:()=>e?.flush()??Promise.resolve()}})}function Et(r){return r[At]}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}),kt(this,this.telemetryReporter,E)}cardCapture(e){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?wt({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 o,s,a=c=>{if(o===void 0)return;let u=o,h=s;o=void 0,s=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=bt(n,{now:()=>this.telemetryReporter?.now()??E(),onFirstByte:(c,u)=>{o=c,s=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 Mt(r,e,t){let n=ye;return new n(r,e,t)}var B=require("@flopay/shared");var He=require("@flopay/shared"),It=require("@stripe/stripe-js"),oe=require("@flopay/shared"),Pt=new WeakSet;function Dt(r){return r instanceof He.FloPayError&&Pt.has(r)}var ie=class{constructor(){this.name="stripe";this.stripe=null}async initialize(e){if(typeof window>"u")return;let t=await(0,It.loadStripe)(e.publishableKey,{locale:e.locale??"auto"});if(!t){let n=new He.FloPayError("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw Pt.add(n),n}this.stripe=t}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var Ft=new Map;function Ke(r){return Array.isArray(r)?r.map(Ke):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Ke(t)])):r}function hn(r,e){return JSON.stringify([r,(0,B.resolveBillingApiUrl)(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,Ke(e?.appearance??null)])}var Fe=new Map;async function xt(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=hn(r,e),n=Ft.get(t);if(n)return e?.telemetry!==!1&&Et(n)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),n;let i=Fe.get(t);if(i)return i;let o={...e,publishableKey:r},s=(async()=>{let a=new A({billingApiUrl:(0,B.resolveBillingApiUrl)(o.billingApiUrl),sdkVersion:B.SDK_VERSION,enabled:o.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(o)}catch(y){throw a.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:Dt(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=Mt(c,o,a);return Ft.set(t,p),p})();Fe.set(t,s);try{return await s}finally{Fe.get(t)===s&&Fe.delete(t)}}var $=require("@flopay/shared");var yn=4,gn=1e3,fn=1e3,Cn=15e3;function vn(r){let e=!!r?.gateways?.stripe,t=!!r?.gateways?.worldpayCorporateGateway;return e===t?"unknown":e?"stripe":"worldpay"}function Ut(r,e,t){try{return typeof r?.beginThreeDsChallenge!="function"?void 0:r.beginThreeDsChallenge(e,{provider:vn(t)})}catch{return}}function ge(r){return new $.FloPayError("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:r})}function Lt(){return new $.FloPayError("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function qt(r){return r.replace(/\/+$/,"")}function Tn(r){return r.status==="succeeded"||r.status==="authorized"||r.status==="declined"}function bn(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=Je(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 o=`${qt(r.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(r.sessionId)}/3ds/complete`,s=async()=>{let m=new AbortController,g=()=>m.abort();r.signal?.aborted?m.abort():r.signal?.addEventListener("abort",g);let v=window.setTimeout(()=>m.abort(),Cn);try{let f=await fetch(o,{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 S=await f.json().catch(()=>null),C=bn(S);return i(C),C}catch{return{status:"unknown"}}finally{window.clearTimeout(v),r.signal?.removeEventListener("abort",g)}},a,l=()=>r.pollCompletionEndpoint!==!1?s():(a??(a=s()),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=Se(r.nextActionRedirectUrl);try{let m=await new Promise((g,v)=>{let f=!1,S=0,C=0,F=0,G=!1,V=!1,x=!1,I=0,w=()=>{window.clearTimeout(S),window.clearInterval(C),window.clearTimeout(F),window.removeEventListener("message",P),window.removeEventListener("pagehide",se),document.removeEventListener("securitypolicyviolation",U),h.removeEventListener("load",Y),r.signal?.removeEventListener("abort",ae)},Z=async()=>{if(!(f||G)){G=!0;try{let R=await l();if(f||!Tn(R))return;f=!0,w(),e.terminal("status_poll",{evidenceBasis:"server_status"}),g(R)}finally{G=!1}}},se=()=>{e.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},U=R=>{if(x)return;let b=_e(R,y);b&&(x=!0,e.record("policy_violation",{reason:b,evidenceBasis:"parent_csp_event"}))},Y=()=>{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,w(),n(r.signal?.reason),v(ge()))},z=R=>{f||I>=yn||(I+=1,e.record("return_rejected",{reason:R,evidenceBasis:"message_origin_check"}))},P=R=>{let b=R.data,j=!!b&&typeof b=="object"&&b.source==="flopay-vault-3ds-return";if(R.source!==h.contentWindow){j&&z("untrusted_source");return}if(p&&R.origin!==p){j&&z("untrusted_origin");return}j&&(f||(f=!0,w(),e.record("trusted_return",{evidenceBasis:"message_origin_check"}),e.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),g(null)))};S=window.setTimeout(()=>{f||(f=!0,w(),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"}),v(Lt()))},$.THREE_DS_CHALLENGE_WINDOW_MS),r.pollCompletionEndpoint!==!1&&(C=window.setInterval(()=>{Z()},fn)),h.addEventListener("load",Y),window.addEventListener("message",P),window.addEventListener("pagehide",se),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(R){throw f=!0,w(),e.record("render_failed"),R}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 Ot(r,e){try{let t=e.data.session?.status;t==="complete"?r.reconcile("succeeded"):t==="authorized"&&r.reconcile("authorized")}catch{}}function _n(r){return new $.FloPayError("Card was declined.","api_error",{code:r.declineReason??"authorization_declined",...r.gatewayDeclineReason?{declineCode:r.gatewayDeclineReason}:{}})}async function Nt(r,e){let t=`${qt(r.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(r.sessionId)}/status`,n=new AbortController,i=new AbortController,o=()=>{n.abort(r.signal?.reason),i.abort(r.signal?.reason)};r.signal?.aborted?o():r.signal?.addEventListener("abort",o,{once:!0});let s=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:gn,nonce:r.nonce,statusUrl:t,continueAfterActionRequired:!0,timeoutMs:$.THREE_DS_CHALLENGE_WINDOW_MS+15e3,signal:i.signal,...s.attemptId?{challengeAttemptId:s.attemptId}:{}});l.catch(()=>{}),a.catch(()=>{});try{let c=await Promise.race([a,l]);if("data"in c)return s.terminal("status_poll",{evidenceBasis:"server_status"}),Ot(s,c),c;if(c.status==="declined")throw(r.createDeclineError??_n)(c);if(c.status==="timeout")throw Lt();let u=await l;return Ot(s,u),u}catch(c){throw r.signal?.aborted||c instanceof Error&&c.name==="AbortError"?ge(c):c}finally{r.signal?.removeEventListener("abort",o),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 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});
|