@flopay/js 1.20.14 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- "use strict";var Q=Object.defineProperty;var He=Object.getOwnPropertyDescriptor;var je=Object.getOwnPropertyNames;var Ge=Object.prototype.hasOwnProperty;var Ke=(n,e)=>{for(var t in e)Q(n,t,{get:e[t],enumerable:!0})},$e=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of je(e))!Ge.call(n,i)&&i!==t&&Q(n,i,{get:()=>e[i],enumerable:!(r=He(e,i))||r.enumerable});return n};var Ye=n=>$e(Q({},"__esModule",{value:!0}),n);var mr={};Ke(mr,{PaymentAPI:()=>P,PciVaultCardCapture:()=>Y,clearSetupRedirectParams:()=>Ue,readSetupRedirectReturn:()=>Le});module.exports=Ye(mr);var l=require("@flopay/shared");function oe(n){return typeof n=="string"&&n.trim()?n:void 0}function ae(n){if(typeof n=="string")return n.trim()?n:void 0;if(Array.isArray(n))return n.filter(t=>typeof t=="string"&&t.trim().length>0).join("; ")||void 0}function D(n=12e3){let e=Number.isFinite(n)&&n>=0?n:12e3,t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function We(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function q(n,e){let t=150*2**n,r=Math.round(t*(.75+Math.random()*.5));return new Promise((i,s)=>{let o,a=()=>e.removeEventListener("abort",d),d=()=>{o!==void 0&&clearTimeout(o),a(),s(We())};if(e.aborted){d();return}o=setTimeout(()=>{a(),i()},r),e.addEventListener("abort",d,{once:!0})})}var Je="flopay_session_display:";var N=new Map;function V(n){return`${Je}${n}`}function X(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function Z(n,e,t){if(!n)return;let r=t?.ttlMs??36e5,i={data:e,expiresAt:Date.now()+r},s=X();if(s)try{s.setItem(V(n),JSON.stringify(i));return}catch{}N.set(n,i)}function le(n){if(!n)return null;let e=X();if(e)try{let r=e.getItem(V(n));if(r){let i=JSON.parse(r);if(i&&typeof i.expiresAt=="number"&&i.expiresAt>Date.now())return i.data;e.removeItem(V(n))}}catch{}let t=N.get(n);if(t){if(t.expiresAt>Date.now())return t.data;N.delete(n)}return null}function de(n){if(!n)return;N.delete(n);let e=X();if(e)try{e.removeItem(V(n))}catch{}}var b=require("@flopay/shared");var ee=require("@flopay/shared"),Qe=32,ce=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function Xe(){let n=globalThis,e=n[ce];if(e instanceof Map)return e;let t=new Map;try{Object.defineProperty(n,ce,{configurable:!0,enumerable:!1,writable:!1,value:t})}catch{}return t}function Ze(n,e){let t=Xe(),r=t.get(n);if(r)return r;for(;t.size>=Qe;){let s=t.keys().next();if(s.done)break;t.delete(s.value)}let i={nextSequence:0,startedAt:e,terminated:!1,reconciled:new Set,provider:"unknown"};return t.set(n,i),i}var et=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),tt=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function ue(n,e={}){let t=(0,ee.isThreeDsChallengeAttemptId)(e.attemptId)?e.attemptId.toLowerCase():n.newAttemptId(),r=()=>{try{let a=n.now();return Number.isFinite(a)?a:0}catch{return 0}},i=Ze(t,r());(e.provider==="stripe"||e.provider==="worldpay")&&(i.provider=e.provider);let s=i.provider,o=(a,d)=>{if(i.terminated&&!tt.has(a))return;let c={attemptId:t,phase:a,attemptSequence:i.nextSequence,elapsedMs:Math.max(0,r()-i.startedAt),provider:s};i.nextSequence+=1,d.reason!==void 0&&(c.reason=d.reason),d.evidenceBasis!==void 0&&(c.evidenceBasis=d.evidenceBasis),d.terminalSource!==void 0&&(c.terminalSource=d.terminalSource),d.providerOutcome!==void 0&&(c.providerOutcome=d.providerOutcome);try{n.emit(c,et.has(a))}catch{}};return{attemptId:t,record(a,d={}){a==="browser_terminal"||a==="provider_reconciled"||o(a,{reason:d.reason,evidenceBasis:d.evidenceBasis})},terminal(a,d={}){i.terminated||(o("browser_terminal",{terminalSource:a,reason:d.reason,evidenceBasis:d.evidenceBasis}),i.terminated=!0)},reconcile(a){i.reconciled.has(a)||(i.reconciled.add(a),o("provider_reconciled",{providerOutcome:a,evidenceBasis:"provider_fact"}))}}}function he(n){let e=null;try{e=(0,ee.isThreeDsChallengeAttemptId)(n?.attemptId)?n?.attemptId??null:null}catch{e=null}return{attemptId:e,record(t,r){try{n?.record(t,r)}catch{}},terminal(t,r){try{n?.terminal(t,r)}catch{}},reconcile(t){try{n?.reconcile(t)}catch{}}}}function te(n){if(typeof n!="string"||n.trim()==="")return"missing";try{let e=new URL(n);return e.protocol==="https:"||e.protocol==="http:"?"valid":"invalid"}catch{return"invalid"}}function me(n){try{if(typeof window>"u"||typeof window.getComputedStyle!="function")return null;for(let e=n;e;e=e.parentElement){let t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||t.visibility==="collapse"||t.opacity==="0")return"hidden"}return"visible"}catch{return null}}function pe(n,e){if(!e)return null;try{let t=n,r=String(t.effectiveDirective||t.violatedDirective||"").trim().split(/\s+/)[0],i=null;return r==="frame-src"&&(i="frame_src"),r==="child-src"&&(i="child_src"),!i||typeof t.blockedURI!="string"?null:new URL(t.blockedURI).origin===e?i:null}catch{return null}}function ye(n){try{return te(n)==="valid"?new URL(n).origin:null}catch{return null}}var rt="/v1/sdk-telemetry/events",B=16,ge=64,nt=1500,fe=1e3,it=64,st="00000000-0000-4000-8000-000000000000",ot={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},at=48;function E(){try{return globalThis.crypto.randomUUID()}catch{let n=new Uint8Array(16);try{globalThis.crypto.getRandomValues(n)}catch{for(let t=0;t<n.length;t+=1)n[t]=Math.floor(Math.random()*256)}n[6]=(n[6]??0)&15|64,n[8]=(n[8]??0)&63|128;let e=[...n].map(t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}}function lt(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function dt(n){return JSON.stringify([n.code,n.failureCategory,n.reason,n.stage,n.provider,n.attempt,n.statusClass,n.requestCategory,n.paymentMethodCategory,n.walletType,n.operationOutcome,n.checkoutMode,n.layout,n.inAppBrowser,n.appFamily,n.popupCapability,n.presentationMode,n.terminalReason])}function S(){return globalThis.performance?.now()??0}var k=class{constructor(e){this.ingestionDisabled=!1;this.queue=[];this.sequence=0;this.threeDsChallengeCount=0;this.flushTimer=null;this.flushInFlight=null;this.reportedFailures=new Map;this.checkoutContext={};this.checkoutStartedAt=null;this.destroyed=!1;this.observers=new Set;this.pageExitHandler=()=>{this.drainQueue()};this.visibilityHandler=()=>{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(/\/+$/,"")}${rt}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=E(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??S,this.browserTransportAvailable=typeof window<"u"&&typeof document<"u",this.browserTransportAvailable&&(window.addEventListener("pagehide",this.pageExitHandler),document.addEventListener("visibilitychange",this.visibilityHandler))}log(e){this.notify({...e,class:"lifecycle"}),this.canCollect()&&this.enqueue((0,b.buildTelemetryLogEvent)({...this.checkoutContext,...e,eventId:E(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=(0,b.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:st,sequence:0}),r=dt(t),i=this.now();this.pruneReportedFailures(i);let s=this.reportedFailures.get(r);if(s!==void 0&&i>=s&&i-s<fe){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt,inAppBrowser:e.inAppBrowser,appFamily:e.appFamily,popupCapability:e.popupCapability,presentationMode:e.presentationMode,terminalReason:e.terminalReason});return}this.rememberReportedFailure(r,i),this.enqueue((0,b.buildTelemetryErrorEvent)({...this.checkoutContext,...e,eventId:E(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue((0,b.buildTelemetryPerformanceEvent)({...this.checkoutContext,...e,eventId:E(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue((0,b.buildTelemetryTerminalEvent)({...this.checkoutContext,...e,eventId:E(),sequence:this.sequence++})),e.outcome!=="action_required"&&this.checkoutStartedAt!==null)){let t=this.checkoutStartedAt;this.checkoutStartedAt=null,this.performance({...e,stage:"total_journey",durationMs:Math.max(0,this.now()-t),durationMode:"total"})}}beginThreeDsChallenge(e={}){return ue({now:()=>this.now(),newAttemptId:E,emit:(t,r)=>this.recordThreeDsChallenge(t,r)},e)}recordThreeDsChallenge(e,t){if(!this.canCollect()||this.threeDsChallengeCount>=at)return;let r=(0,b.buildTelemetryLogEvent)({...this.checkoutContext,...e,name:"three_ds.challenge",stage:"three_ds_handoff",eventId:E(),sequence:this.sequence++});if(!(this.queue.length>=ge)){if(this.threeDsChallengeCount+=1,this.queue.push(r),t){this.drainQueue();return}if(this.queue.length>=B){this.flush();return}this.scheduleFlush()}}now(){try{return this.clock()}catch{return S()}}subscribe(e){return this.destroyed?()=>{}:(this.observers.add(e),()=>this.observers.delete(e))}notify(e){if(!this.destroyed)for(let t of this.observers)try{t(e)}catch{}}pruneReportedFailures(e){for(let[t,r]of this.reportedFailures)(e<r||e-r>=fe)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=it;){let r=this.reportedFailures.keys().next();if(r.done)break;this.reportedFailures.delete(r.value)}this.reportedFailures.set(e,t)}setCheckoutContext(e){this.checkoutContext={checkoutMode:e.checkoutMode,layout:e.layout}}beginCheckout(e={}){return this.canCollect()?(this.drainQueue(),this.setCheckoutContext(e),this.sequence=0,this.threeDsChallengeCount=0,this.reportedFailures.clear(),this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0},this.checkoutStartedAt=this.now(),this.checkoutStartedAt):0}enqueue(e){if(this.canCollect()&&!(this.queue.length>=ge||this.eventCounts[e.class]>=ot[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=B){this.flush();return}this.scheduleFlush()}}canCollect(){return this.browserTransportAvailable&&this.merchantEnabled&&!this.ingestionDisabled&&!this.destroyed}async flush(){if(this.flushInFlight!==null)return this.flushInFlight;if(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0)return;this.clearFlushTimer();let e=this.queue.splice(0,B);return this.flushInFlight=this.sendBatch(e).finally(()=>{this.flushInFlight=null,this.queue.length>0&&this.scheduleFlush()}),this.flushInFlight}destroy(){this.destroyed||(this.drainQueue(),this.destroyed=!0,this.clearFlushTimer(),this.browserTransportAvailable&&(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,B);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=(0,b.serializeTelemetryBatch)(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:E()});if(lt(t)>b.TELEMETRY_MAX_BATCH_BYTES)return;let r=typeof AbortController>"u"?null:new AbortController,i=null;try{let s=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:r?.signal}).then(async d=>{if(d.status!==202)return null;let c=null;try{c=await d.json()}catch{}return c?.status==="disabled"?"disabled":null}).catch(()=>null),o=new Promise(d=>{i=setTimeout(()=>{r?.abort(),d(null)},nt)});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)}},ve=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),Ce=globalThis;Ce[ve]===void 0&&Object.defineProperty(Ce,ve,{configurable:!0,enumerable:!1,writable:!1,value:n=>new k(n)});function ct(n){return n==="on_session"||n==="off_session"}function ut(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function ht(n){let e=n.vaultOutcome;if(!(!e||e.code!==l.CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED))return typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0}var mt="x-flopay-process-result-source",pt="status",Ie=new WeakSet;function yt(n,e){let t=new l.FloPayError(n,"api_error",{code:e,statusCode:500});return Ie.add(t),t}function gt(n){return typeof n=="object"&&n!==null&&Ie.has(n)}function Te(n){return n?.result==="DECLINE"||n?.result==="ERROR"}var ft=50,I=new Map;function vt(n,e){return I.get(n)?.has(e)===!0}function Ct(n,e){let t=I.get(n)??new Set;if(t.add(e),I.delete(n),I.set(n,t),I.size>ft){let r=I.keys().next().value;r!==void 0&&I.delete(r)}}function Tt(n){let e=n?.threeDSecureActionResultTokenId;if(typeof e=="string"&&e.length>0)return e;if(n?.gateway==="paypal"&&n.type!=="paypal_setup_token"&&typeof n.id=="string"&&n.id.length>0)return n.id}var be=0,_e=500,z=15e3,Re=15e3,bt=3e3,_t=1e4,Rt=1e4;function L(n){return typeof n=="object"&&n!==null}function M(n,e){return oe(n?.[e])}function Se(n,e){return ae(n?.[e])}function St(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function j(n,e){return e?new Promise((t,r)=>{let i=()=>{clearTimeout(s),r(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},s=setTimeout(()=>{e.removeEventListener("abort",i),t()},n);e.aborted?i():e.addEventListener("abort",i,{once:!0})}):new Promise(t=>setTimeout(t,n))}function re(n){return n instanceof Error&&n.name==="AbortError"}function R(){return new l.FloPayError(l.CHECKOUT_PROCESSING_TIMEOUT_MESSAGE,"api_error",{code:"checkout_processing_timeout"})}async function w(n,e){let t=await n.json().catch(()=>null),r=L(t?.error)?t.error:null,i=Se(t,"message")??Se(r,"message")??e,s=M(t,"code")??M(t,"gatewayErrorCode")??M(r,"code")??`http_${n.status}`;return(0,l.withTelemetryHttpDiagnostics)(new l.FloPayError(i,"api_error",{code:s,statusCode:n.status}),n)}async function At(n){if(n.status!==403)return!1;let e=await n.clone().json().catch(()=>null),t=L(e?.error)?e.error:null;return(M(e,"code")??M(t,"code"))==="verification_required"}function wt(n){if(!(!L(n)||typeof n.required!="boolean"))return{required:n.required,provider:"turnstile"}}async function Et(n){let e=n.status===400?await n.clone().json().catch(()=>null):null;return(0,l.classifyPaymentRejection)(n.status,e)}function Ae(n){return n===400||n===422}var G=2;async function H(n,e,t=G,r,i){let s;for(let o=0;;o++)try{return i?.(o),await fetch(n,e)}catch(a){if(e?.signal?.aborted||a instanceof Error&&a.name==="AbortError")throw a;if(s=a,o>=t)throw s;try{r?.(o+1)}catch{}await j(150*2**o,e?.signal??void 0)}}var kt=2e3,Mt=1e4,It=150;async function Pt(n){try{let t=(await n.json())?.data?.status;return t==="closed"||t==="not_open"?t:"failed"}catch{return"failed"}}async function we(n,e,t){let r=new AbortController,i=()=>r.abort();t?.addEventListener("abort",i,{once:!0});let s,o=new Promise(a=>{s=setTimeout(()=>{r.abort(),a("timeout")},Mt)});try{let a=await Promise.race([fetch(n,{...e,signal:r.signal}),o]);return a==="timeout"?"failed":a.status>=500?"retry":a.ok?await Pt(a):"failed"}catch{return r.signal.aborted?"failed":"retry"}finally{clearTimeout(s),t?.removeEventListener("abort",i)}}function Dt(n,e){return new Promise(t=>{let r=setTimeout(t,e);n.then(()=>{clearTimeout(r),t()},()=>{clearTimeout(r),t()})})}var Ee="stripe-account-switch-v1",Ft=Symbol.for("@flopay/js.session-create.telemetry.v1");function Ot(n){return n[Ft]}function xt(n){return"now"in n||"onFirstByte"in n||"onSessionCreateFailure"in n||"onRetry"in n}function Pe(n){let e=(0,l.isCardHolderNamePlaceholder)(n.firstName,n.lastName);return{userId:n.userId,firstName:e?null:n.firstName??null,lastName:e?null:n.lastName??null,email:n.email,country:n.country??null,gender:n.gender??null,city:n.city??null,state:n.state??null,zip:n.zip??null,addressLine1:n.addressLine1??null,addressLine2:n.addressLine2??null}}function De(n,e){e.checkoutMetadata!==void 0&&(n.checkoutMetadata=e.checkoutMetadata),e.tagsData&&(n.tagsData=e.tagsData),e.utmMetadata&&e.utmMetadata.length>0&&(n.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(n.avsCheck=e.avsCheck),e.checkoutType&&(n.checkoutType=e.checkoutType),e.checkoutLayout&&(n.checkoutLayout=e.checkoutLayout),e.avsConfig&&(n.avsConfig=e.avsConfig)}function ke(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function Lt(n){let e={};if(n.country&&(e.country=n.country),!(0,l.isCardHolderNamePlaceholder)(n.firstName,n.lastName)){let t=ke(n.firstName),r=ke(n.lastName);t&&(e.firstName=t),r&&(e.lastName=r)}return Object.keys(e).length>0?e:void 0}function Ut(n,e,t){let r={clientId:n.clientId,checkoutVersion:l.SDK_VERSION,successUrl:n.successUrl,cancelUrl:n.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};n.captureMethod==="manual"&&(r.captureMethod=n.captureMethod);let i=Lt(n.account);i&&(r.accountData=i),De(r,n);let s=qt(t);return s&&(r.routingProducts=s),r}function qt(n){let e=new Set;for(let t of n){let r=[t.code,t.providerItemId,t.providerPlanId].map(i=>typeof i=="string"?i.trim():"").find(i=>i.length>0);r&&e.add(r)}return e.size>0?Array.from(e,t=>({code:t})):void 0}function Me(n,e,t){return{currency:e,products:t.map(r=>(0,l.buildProductPayload)(r,e)),couponCodes:n.couponCodes??[],accountData:Pe(n.account)}}function Nt(n,e,t){return{currency:e,products:t.map(r=>(0,l.buildProductPayload)(r,e)),couponCodes:n.couponCodes??[]}}function Vt(n){let e={},t=(0,l.isCardHolderNamePlaceholder)(n.firstName,n.lastName);for(let[r,i]of Object.entries(n)){if(t&&r.endsWith("Name")||typeof i!="string")continue;let s=i.trim();s&&(e[r]=s)}return{accountData:e}}function Bt(n){return typeof n=="string"?{expiresAt:n}:n===null?{expiresAt:null}:{}}var A=class A{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=xt(t);this.telemetryHooks=r?t:void 0,this.stripeAccountSwitch=!r&&t.stripeAccountSwitch===!0,this.directTelemetry=r||t.telemetry===!1?void 0:new k({billingApiUrl:this.baseUrl,sdkVersion:l.SDK_VERSION})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,i,s="unknown"){let o=(0,l.classifyTelemetryFailure)(e,t);this.directTelemetry?.error({...o,...gt(e)?{reason:"capture_failed"}:{},stage:r,requestCategory:i,paymentMethodCategory:s})}reportAccountSnapshotFailure(e,t){let r=(0,l.classifyTelemetryFailure)(e,"NETWORK_REQUEST_FAILED");if(t==="best_effort"&&r.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...r,stage:"processing",requestCategory:"account_snapshot",paymentMethodCategory:"unknown"})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??S()}catch{return S()}}beginDirectTelemetryCheckout(e){!this.directTelemetry||this.directTelemetryCheckoutId===e||(this.directTelemetryCheckoutId=e,this.directTelemetry.beginCheckout())}beginDirectTelemetryOperation(){this.directTelemetry&&(this.directTelemetryCheckoutId=void 0,this.directTelemetry.beginCheckout())}adoptDirectTelemetryCheckout(e){e&&(this.directTelemetryCheckoutId=e)}async getCheckoutSession(e,t){return this.fetchCheckoutSession(e,t)}async fetchCheckoutSession(e,t,r=!0,i){this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp(),o=s,a=0;this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let d={[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION};t&&(d["x-checkout-session-token"]=t);let c=!1;try{let u=await H(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:d,signal:i,cache:"no-store"},G,h=>{this.telemetryHooks?.onRetry?.("session_read",h),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:h})},h=>{a=h,o=this.telemetryTimestamp()});c=!0;let y=Math.max(0,this.telemetryTimestamp()-o);try{this.telemetryHooks?.onFirstByte?.(y,a)}catch{}let m=`${Math.floor(u.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:m,attempt:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:y,durationMode:"machine",requestCategory:"session_read",statusClass:m,attempt:a}),!u.ok)throw await w(u,"Failed to get checkout session");let p=await u.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:m}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"session_read",statusClass:m}),{...p,data:this.mergeCachedDisplayData(p.data)}}catch(u){throw c&&(0,l.markSessionResponseReceived)(u),r&&this.directTelemetry?.error({...(0,l.classifyTelemetryFailure)(u,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),u}}cacheSessionDisplayData(e,t,r){Z(e,t,r)}clearSessionDisplayData(e){de(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,i=A.activeVaultCaptureRequests.get(r);if(i!==void 0)return i;let s=A.pendingThreeDsAbandonReports.get(e),o=s===void 0?this.requestVaultCapture(e,t):Dt(s,kt).then(()=>this.requestVaultCapture(e,t));A.activeVaultCaptureRequests.set(r,o);try{return await o}finally{A.activeVaultCaptureRequests.get(r)===o&&A.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,i=setTimeout(()=>r.abort(),Rt);this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let o={"Content-Type":"application/json"};t&&(o["x-checkout-session-token"]=t);try{let a=await H(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:o,signal:r.signal,cache:"no-store"},G,c=>{this.telemetryHooks?.onRetry?.("vault_capture",c),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:c})});if(await At(a))return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"4xx"}),{verification:{required:!0,provider:"turnstile"}};if(!a.ok)throw await w(a,"Failed to load the secure card form");let d=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(d)}catch(a){let d=r.signal.aborted?new l.FloPayError("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(d,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),d}finally{clearTimeout(i)}}async getUnifiedCheckoutSession(e,t){let r=await this.getCheckoutSession(e,t);return this.normalizeCheckoutSessionResponse(r)}async getUnifiedCheckoutSessionForRecovery(e,t,r){let i=await this.fetchCheckoutSession(e,t,!1,r);return this.normalizeCheckoutSessionResponse(i)}normalizeCheckoutSessionResponse(e){try{let t=this.normalizeRawSession(e.data),r=e.vault;return r&&t.data.session&&(t.data.session.vault=this.toVaultBlock(r)),t}catch(t){throw(0,l.markSessionResponseReceived)(t)}}async processPayment(e,t,r){this.beginDirectTelemetryCheckout(t.sessionId);let i=t.paymentMethodCategory??"unknown";if(!t.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:i}),new l.FloPayError("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:i});let{nonce:o,paymentMethodCategory:a,...d}=t,c=Tt(t.tokenizedData),u,y;try{u=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":o},body:JSON.stringify(d)}),y=u}catch(m){if(re(m))throw this.reportDirectFailure(m,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),m;u=await this.reconcileProcessPayment(t.sessionId,{...r,nonce:o,paymentMethodCategory:i,submittedIntentId:c})}if(!u.ok&&u.status!==202){let m=await Et(u);return m?this.directTelemetry?.terminal({outcome:m,stage:"processing",requestCategory:"process_payment",statusClass:"4xx",paymentMethodCategory:i}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:(0,l.telemetryStatusClass)(u.status),failureCategory:u.status>=500?"server_error":void 0,paymentMethodCategory:i,...(0,l.readTelemetryHttpDiagnostics)(y)}),u}try{let m=await this.resolveProcessResponse(u,t.sessionId,{...r,nonce:o,paymentMethodCategory:i,submittedIntentId:c});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:(0,l.telemetryStatusClass)(m.status),paymentMethodCategory:i}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"process_payment",statusClass:(0,l.telemetryStatusClass)(m.status),paymentMethodCategory:i}),m}catch(m){throw m instanceof l.FloPayError&&m.code==="checkout_processing_timeout"||this.reportDirectFailure(m,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),m}}async patchAccountSnapshot(e,t,r,i){this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let o=i?.timeoutMs??_t,a=new AbortController,d=()=>a.abort();i?.signal&&(i.signal.aborted?a.abort():i.signal.addEventListener("abort",d,{once:!0}));let c=setTimeout(()=>a.abort(),o);try{let u;try{u=await H(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(r),signal:a.signal},G,y=>{this.telemetryHooks?.onRetry?.("account_snapshot",y),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:y})})}finally{clearTimeout(c),i?.signal?.removeEventListener("abort",d)}if(!u.ok)throw await w(u,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(u){throw this.reportAccountSnapshotFailure(u,i?.telemetryMode??"blocking"),u}}async createSessionIntent(e,t,r,i){if(!t)throw new l.FloPayError("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=r,o=s.paymentMethodType,a=typeof o=="string"&&o.trim().toLowerCase()==="card",d=typeof o=="string"&&o.length>0&&!a&&(typeof s.paymentMethodId=="string"||s.paymentMethodId===null),c=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(s.intentKind==="payment"||s.intentKind==="setup"),u=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodId===null&&(s.paymentMethodType==="paypal"&&s.intentKind==="payment"||s.paymentMethodType===l.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&(s.intentKind==="payment"||s.intentKind==="setup"));if(!d||!c&&!u)throw new l.FloPayError("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let y=s.authorizationAttemptId;if(y!==void 0&&!(0,l.isUuidV4)(y))throw new l.FloPayError("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let m=(0,l.isUuidV4)(y)?y:(0,l.randomUuidV4)();this.beginDirectTelemetryCheckout(e);let p=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let h={"Content-Type":"application/json","x-checkout-session-token":t,[l.IDEMPOTENCY_KEY_HEADER]:i?.idempotencyKey||m},g=!1;try{let C=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:h,body:JSON.stringify({...r,authorizationAttemptId:m}),signal:i?.signal});if(!C.ok){g=!0;let J=await w(C,"Failed to create checkout intent"),ze=(0,l.classifyTelemetryFailure)(J,"PAYMENT_PROCESSING_FAILED");throw Ae(J.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...ze,stage:"processing",requestCategory:"intent_create"}),J}let v=await C.json();if(C.status===202&&L(v)&&v.type==="checkout_processing")return g=!0,await this.settleProcessingSessionIntent(v,C,e,t,r);let _=v.data;if(!_||typeof _!="object")throw new l.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let f=_,se=f.paymentMethodType,qe=(f.paymentMethodCategory==="wallet"||f.paymentMethodCategory==="apm")&&typeof se=="string"&&se.trim().toLowerCase()!=="card"&&(typeof f.paymentMethodId=="string"||f.paymentMethodId===null)&&typeof f.providerObjectId=="string",Ne=f.provider==="stripe"&&(f.intentKind==="payment"||f.intentKind==="setup")&&typeof f.clientSecret=="string",Ve=f.provider==="paypal"&&f.paymentMethodCategory==="wallet"&&f.paymentMethodId===null&&(f.paymentMethodType==="paypal"&&f.intentKind==="payment"&&(f.providerObjectType==="order"||f.providerObjectType==="subscription")||f.paymentMethodType===l.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&f.intentKind==="payment"&&f.providerObjectType==="order"||f.paymentMethodType===l.PAYPAL_VAULTED_PAYMENT_METHOD_TYPE&&f.intentKind==="setup"&&f.providerObjectType==="setup_token")&&f.clientSecret===null,Be=f.provider===r.provider&&f.paymentMethodCategory===r.paymentMethodCategory&&f.paymentMethodType===r.paymentMethodType&&f.paymentMethodId===r.paymentMethodId&&f.intentKind===r.intentKind;if(!qe||!Ne&&!Ve||!Be)throw new l.FloPayError("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:(0,l.telemetryStatusClass)(C.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-p),durationMode:"machine",requestCategory:"intent_create",statusClass:(0,l.telemetryStatusClass)(C.status)}),f}catch(C){throw g||this.reportDirectFailure(C,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),C}}async settleProcessingSessionIntent(e,t,r,i,s){let o=this.toCheckoutProcessingPending(e,t,r);try{return{settled:!0,response:await this.resolveCheckoutProcessing(o,r,{nonce:i,paymentMethodCategory:s.provider==="paypal"?"paypal":s.paymentMethodCategory})}}catch(a){throw a instanceof l.FloPayError&&a.code==="checkout_processing_timeout"?new l.FloPayError(a.message,a.type,{code:a.code,statusCode:202,sessionId:o.sessionId,cause:a}):a}}closeThreeDsChallenge(e,t,r,i={}){if(!e||!t||!r||i.signal?.aborted)return Promise.resolve("failed");let s=this.requestThreeDsChallengeClose(e,t,r,i.signal),o=A.pendingThreeDsAbandonReports;return o.set(e,s),s.then(()=>{o.get(e)===s&&o.delete(e)}),s}async requestThreeDsChallengeClose(e,t,r,i){let s=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/3ds/abandoned`,o={method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify({providerIntentId:r})};try{let a=await we(s,o,i);if(a!=="retry")return a;if(i?.aborted)return"failed";await j(It,i);let d=await we(s,o,i);return d==="retry"?"failed":d}catch{return"failed"}}async reportSessionIntentDecline(e,t,r,i){if(!t)throw new l.FloPayError("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=r,o=s.providerDeclineReason,a=s.paymentMethodType,d=s.providerIntentId,c=typeof o=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(o)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(o),u=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&c,y=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(d===void 0||typeof d=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(d)),m=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodType==="paypal"&&d===void 0;if(!u||!y&&!m)throw new l.FloPayError("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let p=m?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:o}:{provider:"stripe",paymentMethodCategory:s.paymentMethodCategory,paymentMethodType:s.paymentMethodType,providerDeclineReason:o,...typeof d=="string"?{providerIntentId:d}:{}},h=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents/decline`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(p),signal:i?.signal});if(!h.ok)throw await w(h,"Failed to report checkout decline")}async resolvePaymentMethodLayout(e,t,r,i){if(!t)throw new l.FloPayError("resolvePaymentMethodLayout requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/payment-method-layout`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION},body:JSON.stringify(r),signal:i?.signal});if(s.status===404||s.status===405)return null;if(!s.ok)throw await w(s,"Failed to resolve the payment method layout");let o=await s.json();return(0,l.normalizePaymentMethodLayout)(o?.data)}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let i=t?.page??1,s=t?.limit??1,o=new URLSearchParams({email:e,page:String(i),limit:String(s),sortField:"createdAt",sortDirection:"DESC"});try{let a=await fetch(`${this.baseUrl}/v1/payments?${o.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!a.ok)throw(0,l.withTelemetryHttpDiagnostics)(new l.FloPayError("Failed to fetch payments","api_error",{statusCode:a.status}),a);let d=await a.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),d}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if((0,l.isDetachedSessionEligible)(e)){let s=e.account.email?.trim();if(s&&!(0,l.isValidEmail)(s))throw new l.FloPayError("Buyer email must be valid when supplied.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"});return(await this.createDetachedSession(e)).claimed}this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=D(e.timeoutMs??12e3),i={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let s=await this.createAndFetchSessionRequest(e,r.signal,i);return this.adoptDirectTelemetryCheckout(s.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:i.statusClass}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:i.statusClass,attempt:i.attempt}),s}catch(s){throw this.reportSessionCreateFailure(s,t,i),s}finally{r.clear()}}async createAndFetchSessionRequest(e,t,r){let i=e.products??(0,l.foldIntoProducts)(e.items,e.subscriptions);(0,l.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:i});let s=(0,l.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,i);if(!s)throw new l.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let o={clientId:e.clientId,checkoutVersion:l.SDK_VERSION,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:s,checkoutMode:e.checkoutMode??"full",products:i.map(c=>(0,l.buildProductPayload)(c,s)),accountData:Pe(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(o.captureMethod=e.captureMethod),e.tokenizedData&&(o.tokenizedData=e.tokenizedData),De(o,e);let a=await this.postCheckoutSessionCreate(o,e,t,r),d=!1;try{let c=await a.json();if(c.data&&"gateways"in c.data){this.autoCacheDisplayData(c.data.uuid,e);let m=this.mergeCachedDisplayData(c.data),p=this.normalizeRawSession(m);return c.vault&&p.data.session&&(p.data.session.vault=this.toVaultBlock(c.vault)),{...p,autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}let u=c.data?.uuid;if(!u)throw new l.FloPayError("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(u,e),this.adoptDirectTelemetryCheckout(u),d=!0,{...await this.getUnifiedCheckoutSession(u),autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}catch(c){throw d?c:(0,l.markSessionResponseReceived)(c)}}async postCheckoutSessionCreate(e,t,r,i){let s={"Content-Type":"application/json",[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION},o=(0,l.resolveIdempotencyKey)(t.idempotencyKey);o&&(s[l.IDEMPOTENCY_KEY_HEADER]=o);let a=[];t.checkoutMode==="auto"&&a.push(l.ASYNC_AUTO_CHECKOUT_CAPABILITY),this.stripeAccountSwitch&&e.deferDataAttachment===!0&&a.push(Ee),a.length>0&&(s[l.FLO_SDK_CAPABILITIES_HEADER]=a.join(", "));let d,c=!1,u=Ot(t),y=(p,h,g)=>{c||(c=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:g,attempt:p}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-h),durationMode:"machine",requestCategory:"session_create",statusClass:g,attempt:p}))},m=p=>{try{this.telemetryHooks?.onRetry?.("session_create",p),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:p})}catch{}};for(let p=0;p<3;p++){i.attempt=p;let h=this.telemetryTimestamp();try{u?.onAttempt?.(p)}catch{}try{d=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:s,body:JSON.stringify(e),signal:r})}catch(v){if(i.statusClass=r.aborted||v instanceof Error&&v.name==="AbortError"?"timeout":"network_error",r.aborted||v instanceof Error&&v.name==="AbortError"||p>=2)throw v;let _=p+1;m(_),await q(p,r);continue}let g=(0,l.telemetryStatusClass)(d.status);if(i.statusClass=g,d.status===204)throw y(p,h,g),new l.FloPayError("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(d.ok){y(p,h,g);break}let C=await w(d,"Failed to create checkout session");if(C.code===l.IDEMPOTENCY_IN_PROGRESS_CODE&&p<2){m(p+1),await q(p,r);continue}throw y(p,h,g),C}if(!d)throw new TypeError("Checkout-session creation exhausted its retry budget.");return d}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=D(e.timeoutMs??12e3),i={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let s=e.products??(0,l.foldIntoProducts)(e.items,e.subscriptions);try{(0,l.assertCaptureMethodEligible)({captureMethod:e.captureMethod,products:s})}catch(v){throw r.clear(),this.reportSessionCreateFailure(v,t,i),v}let o=(0,l.resolveSessionCurrency)(e.currency,e.items,e.subscriptions,s);if(!o)throw r.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new l.FloPayError("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});try{Me(e,o,s)}catch(v){throw r.clear(),this.reportSessionCreateFailure(v,t,i),v}let a,d,c=!1;try{let v=await this.postCheckoutSessionCreate(Ut(e,o,s),e,r.signal,i);if(c=!0,d=await v.json(),!d.data||!("gateways"in d.data))throw new l.FloPayError("The billing API returned no session shell for a detached create. It must support `deferDataAttachment` (TeamFloPay/backend#1099).","api_error",{code:"InvalidCheckoutSessionResponse"});a=this.normalizeRawSession(this.mergeCachedDisplayData(d.data)),d.vault&&a.data.session&&(a.data.session.vault=this.toVaultBlock(d.vault))}catch(v){throw r.clear(),c&&(0,l.markSessionResponseReceived)(v),this.reportSessionCreateFailure(v,t,i),v}let u=a.data.session?.id??d.data.uuid??"",y=a.data.session?.clientSecret??d.data.nonce??"";if(!u||!y){r.clear();let v=new l.FloPayError("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(v,t,i),v}r.clear(),this.adoptDirectTelemetryCheckout(u),this.directTelemetry?.log({name:"session.shell.ready",stage:"session_shell",requestCategory:"session_create",statusClass:i.statusClass,paymentMethodCategory:"card"}),this.directTelemetry?.performance({stage:"session_shell",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:i.statusClass,attempt:i.attempt,paymentMethodCategory:"card"});let m=!e.account.email?.trim(),p=D(e.timeoutMs??12e3),h=this.claimCheckoutSession(u,y,m?Nt(e,o,s):Me(e,o,s),{params:e,startedAt:t,deadline:p,createAttempt:i.attempt}),g=m?void 0:h,C=(v={})=>{if(g!==void 0)return g;let _={...e,account:{...e.account,...v,email:v.email?.trim()||e.account.email?.trim()}};return(0,l.isValidEmail)(_.account.email)?(g=h.then(()=>{let f=this.telemetryTimestamp();return this.claimCheckoutSession(u,y,Vt(_.account),{params:_,startedAt:f,deadline:D(e.timeoutMs??12e3),createAttempt:0})}),g.catch(()=>{}),g):Promise.reject(new l.FloPayError("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return h.catch(()=>{}),{shell:a,sessionId:u,nonce:y,claimed:h,claim:C}}async claimCheckoutSession(e,t,r,i){let s=i?.startedAt??this.telemetryTimestamp(),o=this.telemetryTimestamp(),a=i?.deadline??D(12e3),d=JSON.stringify(r),c="unknown",u=0,y=!1;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let m;for(u=0;u<3;u++){try{m=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION,...this.stripeAccountSwitch?{[l.FLO_SDK_CAPABILITIES_HEADER]:Ee}:{}},body:d,signal:a.signal})}catch(g){let C=a.signal.aborted||g instanceof Error&&g.name==="AbortError";if(c=C?"timeout":"network_error",C||u>=2)throw g;try{this.telemetryHooks?.onRetry?.("session_claim",u+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:u+1})}catch{}await q(u,a.signal);continue}if(c=(0,l.telemetryStatusClass)(m.status),m.ok)break;throw await w(m,"Failed to attach checkout session data")}if(!m)throw new TypeError("Checkout-session claim exhausted its retry budget.");y=!0;let p=await m.json();if(!p.data?.gateways)throw new l.FloPayError("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});i?.params&&this.autoCacheDisplayData(p.data.uuid??e,i.params);let h=this.normalizeRawSession(this.mergeCachedDisplayData(p.data));return p.vault&&h.data.session&&(h.data.session.vault=this.toVaultBlock(p.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:c}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_claim",statusClass:c,attempt:u}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:c}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"session_create",statusClass:c,attempt:i?.createAttempt??u}),h}catch(m){throw y&&(0,l.markSessionResponseReceived)(m),this.reportSessionCreateFailure(m,o,{attempt:u,statusClass:c},"session_claim"),m}finally{a.clear()}}reportSessionCreateFailure(e,t,r,i="session_create"){if(!(e instanceof l.FloPayError&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let s=(0,l.classifyTelemetryFailure)(e,"CHECKOUT_SESSION_CREATE_FAILED");if(this.directTelemetry?.performance({stage:i,durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:i==="session_claim"?"session_claim":"session_create",statusClass:s.statusClass,attempt:r.attempt}),e instanceof l.FloPayError&&e.type==="validation_error"||e instanceof l.FloPayError&&Ae(e.statusCode)){this.directTelemetry?.terminal({outcome:"validation_rejected",stage:i,requestCategory:i==="session_claim"?"session_claim":"session_create",...e.type==="validation_error"?{}:{statusClass:"4xx"}});return}e instanceof l.FloPayError&&e.code==="session_auto_completed"||this.directTelemetry?.error({...s,stage:i,requestCategory:i==="session_claim"?"session_claim":"session_create"})}reportThreeDsAbandoned(e){this.beginDirectTelemetryCheckout(e),this.directTelemetry?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",paymentMethodCategory:"saved"})}beginThreeDsChallenge(e,t={}){try{return this.directTelemetry?(this.beginDirectTelemetryCheckout(e),this.directTelemetry.beginThreeDsChallenge(t)):void 0}catch{return}}async waitForCheckoutSessionCompletion(e,t){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp(),i=t?.paymentMethodCategory??"saved";this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:i});let s=t?.timeoutMs??z,o=Date.now()+s,a=new AbortController,d=!1,c,u=setTimeout(()=>{c=setTimeout(()=>{d=!0,a.abort()},Re)},s),y=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?y():t?.signal?.addEventListener("abort",y,{once:!0});let m=this.clampRetryAfterMs(t?.initialDelayMs??be),p=0;try{if(t?.statusUrl){let h=await this.waitForCheckoutStatus(e,{initialDelayMs:m,timeoutMs:s,nonce:t.nonce,statusUrl:t.statusUrl,pollAfterAction:t.continueAfterActionRequired,signal:a.signal});if(h){let g=await this.resolveCheckoutSessionStatus(e,h,t.nonce,a.signal,()=>d);return this.reportRecoveryCompleted(r,i,t.challengeAttemptId),g}}for(;;){let h=o-Date.now();if(h<=0)throw R();if(m>0){try{p+=1,this.telemetryHooks?.onRetry?.("session_read",p),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:i,attempt:p})}catch{}if(await j(Math.min(m,h),a.signal),Date.now()>=o)throw R()}let g=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,a.signal),C=g.data.session?.status;if(C==="authorized"||C==="complete"||C==="expired")return this.reportRecoveryCompleted(r,i,t?.challengeAttemptId),g;if(Date.now()>=o)throw R();m=this.clampRetryAfterMs(Math.max(m*2,_e))}}catch(h){let g=d&&re(h)?R():h;throw this.reportDirectFailure(g,"RECOVERY_FAILED","recovery","session_read",i),g}finally{clearTimeout(u),clearTimeout(c),t?.signal?.removeEventListener("abort",y)}}reportRecoveryCompleted(e,t,r){let i={stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t};if(this.directTelemetry?.log({name:"operation.recovery.completed",...i}),r)try{this.directTelemetry?.beginThreeDsChallenge({attemptId:r}).record("recovery_read_completed",{evidenceBasis:"server_status"})}catch{}this.directTelemetry?.performance({...i,durationMs:Math.max(0,this.telemetryTimestamp()-e),durationMode:"machine"})}async resolveCheckoutSessionStatus(e,t,r,i,s){let o=t.latestTransactionAttempt;if(this.rememberReportedFailure(e,t),o?.result==="DECLINE"){let c=o.code===l.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE;throw new l.FloPayError(c?l.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.","api_error",{code:o.code??o.declineReason??"authorization_declined",statusCode:400})}if(o?.result==="ERROR"||t.status==="voided")throw yt("Payment could not be completed. Please try again.",o?.code??"payment_processing_error");let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,r,i)}catch(c){if(!s?.()||!re(c))throw c;a={providers:[],mode:"tokenize",data:{},raw:t}}let d=a.data.session;return d&&o?.result==="SUCCESS"?{...a,data:{...a.data,session:{...d,status:"complete"}}}:d&&o?.result==="AUTHORIZED"?{...a,data:{...a.data,session:{...d,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:d&&t.status==="completed"?{...a,data:{...a.data,session:{...d,status:"complete"}}}:d&&t.status==="authorized"?{...a,data:{...a.data,session:{...d,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:d&&t.status==="expired"?{...a,data:{...a.data,session:{...d,status:"expired"}}}:o?.result!=="ACTION_REQUIRED"?a:o.gateway==="paypal"&&o.providerIntentId?{...a,autoProcessingError:{type:"paypal_direct_required",message:"PayPal authorization required",orderId:o.providerIntentId,checkoutMethod:"paypal"}}:o.nextActionRedirectUrl?{...a,autoProcessingError:{type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:o.nextActionRedirectUrl}}:a}async waitForCheckoutStatus(e,t){let r=t.timeoutMs??z,i=Date.now()+r,s=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let o=i-Date.now();if(o<=0||s>0&&(await j(Math.min(s,o),t.signal),Date.now()>=i))throw R();let a=i-Date.now();if(a<=0)throw R();let d=new AbortController,c,u=t.signal?new Promise((_,f)=>{c=f}):null,y=()=>{d.abort(t.signal?.reason),c?.(t.signal?.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))};t.signal?.aborted?y():t.signal?.addEventListener("abort",y,{once:!0});let m,p=t.signal?null:new Promise((_,f)=>{m=setTimeout(()=>{f(R()),d.abort()},a+Re)}),h;try{let _=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,d.signal);h=await Promise.race([_,p,u].filter(f=>f!==null))}finally{m!==void 0&&clearTimeout(m),t.signal?.removeEventListener("abort",y)}if(!h)return null;let g=Te(h.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,h,t.submittedIntentId);if(h.status==="completed"||h.status==="authorized"||h.status==="expired"||h.status==="voided")return g?{...h,latestTransactionAttempt:null}:h;let C=h.latestTransactionAttempt?.result,v=t.pollAfterAction===!0&&C==="ACTION_REQUIRED";if(!g&&C!==void 0&&C!=="PENDING"&&!v)return h;s=this.clampRetryAfterMs(Math.max(s*2,_e))}}isOwnFailedAttempt(e,t,r){let i=t.latestTransactionAttempt?.providerIntentId??null;return r!==void 0?i===r:i===null?!0:!vt(t.uuid||e,i)}rememberReportedFailure(e,t){let r=t.latestTransactionAttempt;!Te(r)||!r.providerIntentId||Ct(t.uuid||e,r.providerIntentId)}async fetchCheckoutStatus(e,t,r,i){let s=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,o=s;if(r)try{let u=new URL(r,`${this.baseUrl}/`),y=new URL(s);u.origin===y.origin&&(o=u.toString())}catch{}let a={[l.FLO_SDK_VERSION_HEADER]:l.SDK_VERSION};t&&(a["x-checkout-session-token"]=t);let d=await H(o,{headers:a,signal:i});if(d.status===404||d.status===405)return null;if(!d.ok)throw await w(d,"Failed to get checkout session status");let c=await d.json();return L(c.data)&&"latestTransactionAttempt"in c.data?c.data:null}normalizeRawSession(e){let t=e.gateways??{},r=[],i={session:this.toCheckoutSession(e)},s=t.stripe;if(s?.publishableKey){r.push("stripe");let d=[e.stripeClientSecret,s.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);i.stripe={clientSecret:d??"",publishableKey:s.publishableKey??void 0,paypalPublishableKey:s.paypalPublishableKey??void 0,environment:s.environment,enabledPaymentMethods:Array.isArray(s.enabledPaymentMethods)?s.enabledPaymentMethods.filter(c=>typeof c=="string"):void 0}}let o=t.paypal;return o?.publishableKey&&(r.push("paypal"),i.paypal={publishableKey:o.publishableKey,environment:o.environment,providerObjectType:o.providerObjectType,approvalPresentation:o.approvalPresentation}),{providers:r,mode:"tokenize",...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},data:i,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],r=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),i=t.reduce((c,u)=>c+(u.overrideAmount??u.totalAmount??0),0),s=r?e.totalAmount:i,o=Math.round(s*100),a=e.currency??t[0]?.currency??"USD",d="payment";return e.checkoutMode==="setup"?d="setup":t.some(c=>c.type==="subscription")&&(d="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:d,status:this.toCheckoutSessionStatus(e.status),amount:o,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:(0,l.normalizeCheckoutFailureOutcome)(e.outcome)??(0,l.normalizeCheckoutFailureOutcome)(e.failureReason)??(e.status==="expired"&&e.captureMethod==="manual"?"authorization_expired":void 0),customer:{id:e.accountData.userId??void 0,email:e.accountData.email??void 0,firstName:e.accountData.firstName??void 0,lastName:e.accountData.lastName??void 0,country:e.accountData.country??void 0,city:e.accountData.city??void 0,state:e.accountData.state??void 0,zip:e.accountData.zip??void 0,gender:e.accountData.gender??void 0,line1:e.accountData.addressLine1??void 0,line2:e.accountData.addressLine2??void 0},...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},metadata:{},checkoutMode:e.checkoutMode,...Array.isArray(e.advertisedPaymentMethods)?{advertisedPaymentMethods:e.advertisedPaymentMethods}:{},...ct(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(ut)}:{},buyerIdentified:e.buyerIdentified,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(c=>({...c,totalAmount:typeof c.totalAmount=="number"?c.totalAmount:void 0,overrideAmount:typeof c.overrideAmount=="number"?c.overrideAmount:null,currency:typeof c.currency=="string"?c.currency:void 0,metadata:c.metadata??null})),successUrl:e.successUrl,cancelUrl:e.cancelUrl,coupons:e.coupons,subtotalAmount:e.subtotalAmount,discountAmount:e.discountAmount,totalAmount:e.totalAmount,createdAt:e.createdAt,gateways:e.gateways,accountData:e.accountData,tagsData:e.tagsData}}toVaultBlock(e){let t=wt(e.verification);return{html:typeof e.html=="string"?e.html:void 0,url:typeof e.url=="string"?e.url:void 0,messageToken:typeof e.messageToken=="string"?e.messageToken:void 0,expectedOrigin:typeof e.expectedOrigin=="string"?e.expectedOrigin:void 0,...Bt(e.expiresAt),...t?{verification:t}:{}}}toCheckoutSessionStatus(e){return e==="completed"?"complete":e==="authorized"?"authorized":e==="expired"?"expired":"open"}async resolveProcessResponse(e,t,r){if(e.status!==202)return e;let i=await e.json().catch(()=>null),s=this.toCheckoutProcessingPending(i,e,t);return this.resolveCheckoutProcessing(s,t,r)}async resolveCheckoutProcessing(e,t,r){let i=r?.pollTimeoutMs??z,s=Date.now()+i;if(e.statusUrl){let a=await this.waitForCheckoutStatus(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:i,nonce:r?.nonce,statusUrl:e.statusUrl,submittedIntentId:r?.submittedIntentId});if(a)return this.toProcessResponseFromStatus(a,t,r?.nonce)}let o=await this.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:s-Date.now(),nonce:r?.nonce,paymentMethodCategory:r?.paymentMethodCategory});return this.toProcessResponseFromSession(o,t)}async toProcessResponseFromStatus(e,t,r){let i=e.latestTransactionAttempt?.result,s={[mt]:pt},o={"Content-Type":"application/json",...s};if(e.status==="completed"||i==="SUCCESS")return new Response(null,{status:204,statusText:"No Content",headers:s});if(e.status==="authorized"||i==="AUTHORIZED")return new Response(JSON.stringify({status:"authorized",paymentId:e.paymentId??void 0,sessionId:e.uuid||t,authorizationExpiresAt:e.authorizationExpiresAt??void 0}),{status:200,headers:o});if(e.status==="expired"){let a=await this.resolveCheckoutSessionStatus(t,e,r);return this.toProcessResponseFromSession(a,t)}if(this.rememberReportedFailure(t,e),i==="DECLINE"){let a=e.latestTransactionAttempt,d=a?.code===l.STORED_PAYMENT_METHOD_UNSUPPORTED_CODE,c=a?.declineReason??void 0;return new Response(JSON.stringify({type:c??"authorization_declined",message:d?l.STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE:"Payment was declined. Please choose another payment method.",code:a?.code??c??"authorization_declined",...c?{declineCode:c}:{}}),{status:400,headers:o})}if(i==="ACTION_REQUIRED"&&e.latestTransactionAttempt?.gateway==="paypal"&&e.latestTransactionAttempt.providerIntentId)return new Response(JSON.stringify({type:"paypal_direct_required",message:"PayPal authorization required",orderId:e.latestTransactionAttempt.providerIntentId}),{status:400,headers:o});if(i==="ACTION_REQUIRED"&&e.latestTransactionAttempt?.nextActionRedirectUrl)return new Response(JSON.stringify({type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:e.latestTransactionAttempt.nextActionRedirectUrl}),{status:400,headers:o});if(i==="ERROR"||e.status==="voided")return new Response(JSON.stringify({type:"unknown",code:e.latestTransactionAttempt?.code??"payment_processing_error",message:ht(e)??"Payment could not be completed. Please try again."}),{status:500,headers:o});throw R()}async reconcileProcessPayment(e,t){let r=t?.pollTimeoutMs??z,i=Date.now()+r,s=null;try{s=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:r,nonce:t?.nonce,submittedIntentId:t?.submittedIntentId})}catch(d){if(this.reportDirectFailure(d,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),d instanceof l.FloPayError&&d.code==="checkout_processing_timeout")throw d}if(s)return this.toProcessResponseFromStatus(s,e,t?.nonce);let o=i-Date.now();if(o<=0)throw R();let a=await this.waitForCheckoutSessionCompletion(e,{initialDelayMs:0,timeoutMs:o,nonce:t?.nonce,paymentMethodCategory:t?.paymentMethodCategory});return this.toProcessResponseFromSession(a,e)}toProcessResponseFromSession(e,t){if(e.data.session?.status==="complete")return new Response(null,{status:204,statusText:"No Content"});if(e.data.session?.status==="authorized"){let r=e.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:r.paymentId,sessionId:r.id||t,authorizationExpiresAt:r.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(e.data.session?.status==="expired"){let r=e.data.session.failureOutcome==="authorization_expired"||e.data.session.captureMethod==="manual";throw new l.FloPayError(r?"Authorization has expired.":"Checkout session has expired.","api_error",{code:r?"authorization_expired":"checkout_session_expired"})}throw R()}toCheckoutProcessingPending(e,t,r){let i=t.headers.get("Retry-After"),s=i===null||i.trim()===""?void 0:Number(i),o=s!==void 0&&Number.isFinite(s)?s*1e3:void 0;return{type:"checkout_processing",sessionId:M(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs(St(e,"retryAfterMs")??o??be),statusUrl:M(e,"statusUrl"),sessionUrl:M(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,bt))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??(0,l.foldIntoProducts)(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let i=t.products!==void 0,s=(0,l.resolveSessionCurrency)(t.currency,i?void 0:t.items,i?void 0:t.subscriptions,r);Z(e,{currency:s??void 0,products:r.map(o=>({code:o.code??o.providerItemId??o.providerPlanId,type:o.type,name:o.name??o.itemName??o.providerItemName??o.subscriptionName??o.providerPlanName??null,totalAmount:o.totalAmount,overrideAmount:o.overrideAmount,currency:o.currency??s??void 0}))})}mergeCachedDisplayData(e){let t=le(e.uuid),r=new Map,i=o=>o?`code:${o}`:void 0;for(let o of t?.products??[]){let a=i(o.code);a&&r.set(a,o)}let s=(e.products??[]).map(o=>{let a=i(o.code),d=a?r.get(a):void 0;return{...o,name:o.name??d?.name??null,totalAmount:o.totalAmount??d?.totalAmount,overrideAmount:o.overrideAmount??d?.overrideAmount,currency:o.currency??d?.currency}});return{...e,currency:e.currency??t?.currency,products:s}}};A.activeVaultCaptureRequests=new Map,A.pendingThreeDsAbandonReports=new Map;var P=A;var T=require("@flopay/shared");var $=require("@flopay/shared");function Fe(n){if(!n)return null;try{let e=new URL(n,window.location.href);return e.origin==="null"?null:e.origin}catch{return null}}var K=class{constructor(e){this.options=e;this.handlers=new Set;this.active=!1;this.readyReported=!1;this.failureReported=!1;this.startedAt=0;this.timer=null;this.detach=null}subscribe(e){return this.handlers.add(e),()=>{this.handlers.delete(e)}}begin(){this.end(),this.active=!0,this.readyReported=!1,this.failureReported=!1,this.startedAt=this.options.now();let e=(0,$.resolveCardFieldsTimeoutMs)(this.options.timeoutMs);this.timer=setTimeout(()=>{this.timer=null,this.reportFailure("timeout",e)},e)}watch(e){if(!this.active)return;this.detachWatchers();let t=new Set,r=[];for(let s of Array.from(e.querySelectorAll("script[src], iframe[src]"))){let o=Fe(s.getAttribute("src"));if(o&&t.add(o),s.tagName==="SCRIPT"){let a=()=>this.fail("load_error");s.addEventListener("error",a),r.push(()=>s.removeEventListener("error",a))}}let i=s=>{let o=Fe(s.blockedURI);o&&t.has(o)&&this.fail("blocked")};document.addEventListener("securitypolicyviolation",i),r.push(()=>document.removeEventListener("securitypolicyviolation",i)),this.detach=()=>{for(let s of r)s()}}ready(){!this.active||this.readyReported||(this.readyReported=!0,this.clearTimer(),this.detachWatchers(),this.dispatch({type:"card_fields_ready",elapsedMs:this.elapsed()}))}fail(e){this.reportFailure(e,0)}reportFailure(e,t){!this.active||this.readyReported||this.failureReported||(this.failureReported=!0,this.clearTimer(),this.dispatch({type:"card_fields_failed",reason:e,elapsedMs:Math.max(t,this.elapsed())}))}end(){this.active=!1,this.clearTimer(),this.detachWatchers()}elapsed(){return Math.max(0,Math.round(this.options.now()-this.startedAt))}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}detachWatchers(){this.detach?.(),this.detach=null}dispatch(e){try{this.options.report?.(e)}catch{}for(let t of Array.from(this.handlers))(0,$.invokeMerchantCallback)(()=>t(e))}};var zt=4,W="flopay-vault",Ht=3e4,jt=T.THREE_DS_CHALLENGE_WINDOW_MS+Ht,Gt="Card authentication timed out.",ne=2,Kt=6e4;function $t(n){if(!n)return!1;let e=Date.parse(n);return Number.isNaN(e)?!1:e-Date.now()<Kt}function Yt(n){if(!n)return!1;let e=Date.parse(n);return Number.isFinite(e)&&e>Date.now()}var Oe={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 Wt(n){return n.class==="lifecycle"?n.name:n.class==="technical_error"?n.code:n.class==="expected_outcome"?n.outcome:"sdk.performance"}function F(n){let e={class:n.class,stage:n.stage};"code"in n&&(e.code=n.code),"provider"in n&&n.provider&&(e.provider=n.provider),"paymentMethodCategory"in n&&n.paymentMethodCategory&&(e.paymentMethodCategory=n.paymentMethodCategory),"outcome"in n&&(e.outcome=n.outcome),"durationMs"in n&&n.durationMs!==void 0&&(e.durationMs=n.durationMs),"durationMode"in n&&n.durationMode&&(e.durationMode=n.durationMode);try{globalThis.Sentry?.addBreadcrumb?.({category:"flopay.telemetry",level:n.class==="technical_error"?"error":"info",message:Wt(n),data:e})}catch{}}function U(n,e){return(0,T.buildTelemetryLogEvent)({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var Jt=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function Qt(n){return typeof n=="string"&&Jt.has(n)?n:"unknown"}var Xt=new Set(["verification_failed","verification_expired"]);function Zt(n){return n==null?!0:typeof n=="string"&&Xt.has(n)}var er="vault_mount";function tr(n){return n.failureStage===er}function ie(n,e){return n&&!tr(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:Qt(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function xe(n,e,t="checkout"){return t==="card_setup"?n.type==="decline"?"card_setup_declined":"card_setup_succeeded":n.type==="decline"?"payment_declined":n.outcome==="authorized"||e==="manual"?"payment_authorized":"payment_succeeded"}function rr(n,e,t,r="checkout"){let{type:i}=n;if(i==="complete"||i==="decline")return(0,T.buildTelemetryTerminalEvent)({eventId:"22222222-2222-4222-8222-222222222222",outcome:xe(n,t,r),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(i==="error"){let a=ie(e,n);return(0,T.buildTelemetryErrorEvent)({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[s,o]=Oe[i];return U(s,o)}function nr(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===W&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function ir(n){if(typeof n!="object"||n===null)return;let e=n;if(typeof e.code!="string"||e.code.trim()==="")return;let t=typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0;return t?{code:e.code,message:t}:{code:e.code}}function sr(n){if(typeof n!="object"||n===null)return;let e=n,t=e.status;if(!(typeof e.id!="string"||e.id.trim()===""||typeof e.brand!="string"||e.brand.trim()===""||typeof e.lastFour!="string"||!/^\d{4}$/.test(e.lastFour)||typeof e.expiryMonth!="number"||!Number.isInteger(e.expiryMonth)||e.expiryMonth<1||e.expiryMonth>12||typeof e.expiryYear!="number"||!Number.isInteger(e.expiryYear)||e.expiryYear<1970||e.expiryYear>9999||t!=="pending"&&t!=="active"&&t!=="deleted"))return{id:e.id,brand:e.brand,lastFour:e.lastFour,expiryMonth:e.expiryMonth,expiryYear:e.expiryYear,status:t}}function or(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===W&&e.type==="validation"&&Array.isArray(e.messages)}function ar(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===W&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}function lr(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===W&&e.type==="fields_interactive"}function dr(n){let e=n.capabilities;return Array.isArray(e)&&e.includes("fields_interactive")}var cr=["number","expiry","cvv","name"];function ur(n){if(n===null||typeof n!="object")return;let e=n,t={};for(let r of cr){let i=e[r];typeof i=="string"&&(t[r]=i)}return t}var Y=class{constructor(e={},t){this.provider="pcivault";this.container=null;this.messageHandler=null;this.actionOverlay=null;this.threeDsReturnHandler=null;this.actionChallenge=null;this.lastChallengeTelemetry=null;this.actionOverlayPreviousFocus=null;this.actionOverlayTimer=null;this.actionChallengeIntentId=null;this.messageToken=null;this.expectedOrigin=null;this.theme=void 0;this.submitGateBlocked=!1;this.cardFieldOrder=null;this.cardAutoFocus=!0;this.cardBrandIcons=!1;this.showCardFieldLabels=void 0;this.cardFieldLabels=void 0;this.submitLabel=void 0;this.cardFieldPlaceholders=void 0;this.mountStartedAt=0;this.vaultReadyReported=!1;this.verificationRequired=!1;this.submissionStarted=!1;this.submissionStartedAt=null;this.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 K({timeoutMs:e.cardFieldsTimeoutMs,now:()=>this.telemetryReporter?.now?.()??S(),report:r=>this.reportCardFields(r)}),this.ownsTelemetryReporter=!t&&e.telemetry!==!1,this.telemetryReporter=t?.reporter??(this.ownsTelemetryReporter?new k({billingApiUrl:(0,T.resolveBillingApiUrl)(e.billingApiUrl),sdkVersion:T.SDK_VERSION}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new k({billingApiUrl:(0,T.resolveBillingApiUrl)(this.config.billingApiUrl),sdkVersion:T.SDK_VERSION}));let r=this.telemetryReporter;if(this.config.operation==="card_setup"&&r&&this.setupTelemetryReporter!==r){this.setupTelemetryReporter=r;try{r.beginCheckout({checkoutMode:"setup"})}catch{}}if(this.mountStartedAt=this.telemetryReporter?.now?.()??S(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,this.cardFields.begin(),typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),new T.FloPayError("The vault card form is only available in the browser.","api_error",{code:"card_capture_no_window"});if(!t?.html?.trim())throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),new T.FloPayError("No vault capture widget HTML was provided to mount the secure card form.","api_error",{code:"card_capture_no_widget_html"});this.container=e,this.verificationRequired=t.verificationRequired===!0,this.messageToken=t.messageToken??null,this.expectedOrigin=t.expectedOrigin??this.config.expectedOrigin??null,this.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(),F(U("vault.widget.mounted","vault_mount")),this.telemetryReporter?.log({name:"vault.widget.mounted",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?.performance?.({stage:"vault_mount",durationMs:Math.max(0,(this.telemetryReporter.now?.()??S())-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),this.emit("ready",{sessionId:this.config.sessionId}),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 r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>{this.listeners.get(e)?.delete(t)}}onCardFields(e){return this.cardFields.subscribe(e)}failCardFieldsMount(){this.cardFields.fail("other"),this.cardFields.end()}reportCardFields(e){let t=e.type==="card_fields_ready",r=this.config.sessionId;this.telemetryReporter?.log({name:t?"vault.fields.ready":"vault.fields.failed",stage:t?"vault_ready":"vault_mount",provider:"pcivault",paymentMethodCategory:"card",elapsedMs:e.elapsedMs,...e.type==="card_fields_failed"?{loadFailureReason:e.reason}:{},...r?{checkoutSessionId:r}:{}})}unmount(){if(this.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>=ne?(this.emitRemint("form_unavailable","capped"),!1):(this.beginRemint("form_unavailable"),!0)}considerRemint(e){if(!(this.remintBlocked()||!this.canRemint()||this.remintTask!==null)&&$t(this.captureExpiresAt)){if(this.remintPosts>=ne){this.emitRemint(e,"capped");return}this.beginRemint(e)}}beginRemint(e){let t=this.remintGeneration;this.remintFormRefused=e==="form_unavailable";let r=this.performRemint(e,t).finally(()=>{this.remintTask===r&&(this.remintTask=null)});return this.remintTask=r,r}async performRemint(e,t){let r=this.config.sessionId,i=this.config.sessionToken;if(!r||!i)return;let s=new P((0,T.resolveBillingApiUrl)(this.config.billingApiUrl),{telemetry:!1}),o=!1;for(;this.remintPosts<ne&&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(r,i);if(t!==this.remintGeneration||!this.container)return;this.adoptFreshBlock(a,r,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||!Yt(this.captureExpiresAt))&&this.showRemintLoadError()}adoptFreshBlock(e,t,r){if(!this.container)return;let i=(0,T.resolveVaultMountOptions)(e,{billingApiUrl:(0,T.resolveBillingApiUrl)(this.config.billingApiUrl),sessionId:t,nonce:r});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 r=Array.from(e.querySelectorAll("script"));for(let i of r){let s=document.createElement("script");for(let o of Array.from(i.attributes))s.setAttribute(o.name,o.value);s.text=i.text,i.replaceWith(s)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let r=t.data;if(ar(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(or(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let c=r.messages.filter(u=>typeof u=="string"&&u.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:c||void 0});return}if(lr(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let c=typeof r.sessionId=="string"?r.sessionId:void 0;if(this.config.sessionId&&c&&c!==this.config.sessionId)return;this.cardFields.ready(),this.remintPosts=0;return}if(!nr(r)||this.messageToken&&r.messageToken!==this.messageToken)return;let i=this.config.sessionId,s=typeof r.sessionId=="string"?r.sessionId:void 0;if(i&&s&&s!==i||(r.type==="complete"||r.type==="decline")&&i&&s!==i||r.type==="error"&&r.code==="form_unavailable"&&this.recoverUnavailableForm())return;let o=sr(r.paymentMethod),a=ir(r.vaultOutcome),d={...r.sessionId??this.config.sessionId?{sessionId:r.sessionId??this.config.sessionId}:{},...r.outcome?{outcome:r.outcome}:{},...r.paymentId?{paymentId:r.paymentId}:{},...r.authorizationExpiresAt?{authorizationExpiresAt:r.authorizationExpiresAt}:{},...r.failureOutcome?{failureOutcome:r.failureOutcome}:{},...r.intentId?{intentId:r.intentId}:{},...r.declineReason?{declineReason:r.declineReason}:{},...r.message?{message:r.message}:{},...a?{vaultOutcome:a}:{},...o?{paymentMethod:o}:{}};r.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??S(),this.chargeInFlight=!0,this.remintGeneration+=1,this.remintTask=null),(r.type==="complete"||r.type==="decline"||r.type==="error")&&(this.chargeInFlight=!1),this.isVerificationStateError(r)?(F(U("operation.state_transition","vault_mount")),this.telemetryReporter?.log({name:"operation.state_transition",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})):(F(rr(r,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(r),r.type==="error"&&ie(this.submissionStarted,r).errorCode==="VAULT_LOAD_FAILED"&&this.cardFields.fail("load_error")),r.type==="ready"&&(this.remintPosts=0,this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postCardBrandIcons(),this.postCardFieldLabels(),this.postCardFieldPlaceholders(),this.postSubmitLabel(),dr(r)||this.cardFields.ready()),r.type==="action_required"&&r.nextActionRedirectUrl&&(this.showActionRequiredOverlay(r.nextActionRedirectUrl),this.actionOverlay&&typeof r.intentId=="string"&&r.intentId&&(this.actionChallengeIntentId=r.intentId)),(r.type==="complete"||r.type==="decline"||r.type==="error"||r.type==="submitting")&&(this.endActionChallengeFromWidget(r.type),this.hideActionRequiredOverlay()),r.type!=="action_required"&&this.emit(r.type,d)};this.messageHandler=e,window.addEventListener("message",e)}isVerificationStateError(e){return e.type==="error"&&this.verificationRequired&&!this.submissionStarted&&Zt(e.failureOutcome)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;let{type:r}=e;if(r==="ready"&&!this.vaultReadyReported&&(this.vaultReadyReported=!0,t.performance({stage:"vault_ready",durationMs:Math.max(0,t.now()-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card",requestCategory:"provider_sdk"})),r==="complete"||r==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:xe(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="error"){let o=ie(this.submissionStarted,e);t.log({name:"vault.terminal",stage:o.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...o,provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="action_required"){t.log({name:"vault.action.required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),t.log({name:"vault.three_ds.handoff",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});let o=this.submissionStartedAt;this.submissionStartedAt=null,o!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-o),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[i,s]=Oe[r];t.log({name:i,stage:s,provider:"pcivault",paymentMethodCategory:"card"})}applyTheme(e){this.theme=e,this.postTheme()}postTheme(){this.theme!==void 0&&this.postToHostedWindow({source:"flopay-vault-host",type:"theme",theme:this.theme},this.directiveTargetOrigin())}setSubmitGate(e){this.submitGateBlocked=e,this.postSubmitGate()}postSubmitGate(){this.postToHostedWindow({source:"flopay-vault-host",type:"gate",blocked:this.submitGateBlocked},this.directiveTargetOrigin())}setCardFieldOrder(e,t){this.cardFieldOrder=e,this.cardAutoFocus=t,this.postCardFieldOrder()}postCardFieldOrder(){this.postToHostedWindow({source:"flopay-vault-host",type:"fieldOrder",order:this.cardFieldOrder,autoFocus:this.cardAutoFocus},this.directiveTargetOrigin())}setCardBrandIcons(e){this.cardBrandIcons=e===!0,this.postCardBrandIcons()}setShowCardFieldLabels(e){this.showCardFieldLabels=e===!0,this.postCardFieldLabels()}setCardFieldLabels(e){this.cardFieldLabels=(0,T.buildCardFieldLabelsPayload)(e),this.postCardFieldLabels()}postCardFieldLabels(){let e=this.showCardFieldLabels,t=this.cardFieldLabels;if(e===void 0&&t===void 0)return;let r=this.config.sessionId,{messageToken:i,expectedOrigin:s}=this;!r||!i||!s||this.postToHostedWindow({source:"flopay-vault-host",type:"cardFieldLabels",sessionId:r,messageToken:i,...e===void 0?{}:{show:e},...t===void 0?{}:{labels:{...t}}},s)}setCardFieldPlaceholders(e){let t=ur(e),r=t===void 0&&this.cardFieldPlaceholders!==void 0;this.cardFieldPlaceholders=t,this.postCardFieldPlaceholders(r?{}:t)}postCardFieldPlaceholders(e=this.cardFieldPlaceholders){let t=this.config.sessionId,{messageToken:r,expectedOrigin:i}=this;e===void 0||!t||!r||!i||this.postToHostedWindow({source:"flopay-vault-host",type:"cardFieldPlaceholders",sessionId:t,messageToken:r,placeholders:{...e}},i)}postCardBrandIcons(){this.postToHostedWindow({source:"flopay-vault-host",type:"cardBrandIcons",show:this.cardBrandIcons},this.directiveTargetOrigin())}setSubmitLabel(e){this.submitLabel=e,this.postSubmitLabel()}postSubmitLabel(){let e=this.submitLabel,t=this.config.sessionId,{messageToken:r,expectedOrigin:i}=this;e===void 0||!t||!r||!i||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:t,messageToken:r,label:e},i)}hostedWindow(){return this.container?.querySelector("iframe")?.contentWindow??null}postToHostedWindow(e,t){let r=this.hostedWindow();if(r)try{r.postMessage(e,t)}catch{}}directiveTargetOrigin(){return this.expectedOrigin??"*"}emit(e,t){for(let r of this.listeners.get(e)??[])r(t)}showActionRequiredOverlay(e){if(typeof document>"u")return;if(this.actionOverlay){let h=this.actionOverlay.querySelector("iframe");h instanceof HTMLIFrameElement&&h.src!==e&&(h.src=e),this.armActionRequiredTimeout();return}this.actionOverlayPreviousFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;let t=he(this.beginActionChallengeAttempt()),r=ye(e),i=!1,s=h=>{if(i)return;let g=pe(h,r);g&&(i=!0,t.record("policy_violation",{reason:g,evidenceBasis:"parent_csp_event"}))},o=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},a={telemetry:t,loaded:!1,detach:()=>{document.removeEventListener("securitypolicyviolation",s),window.removeEventListener("pagehide",o)}};this.actionChallenge=a,this.lastChallengeTelemetry=t,t.record("handoff_planned"),te(e)==="invalid"&&t.record("action_invalid",{reason:"invalid_url"}),document.addEventListener("securitypolicyviolation",s),window.addEventListener("pagehide",o);let d=document.createElement("div");d.setAttribute("data-flopay-action-required","1"),d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-label","Card authentication"),d.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let c=document.createElement("iframe");c.setAttribute("title","Card authentication"),c.setAttribute("allow","payment"),c.tabIndex=0,c.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),c.addEventListener("load",()=>{a.loaded||(a.loaded=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"}))}),c.src=e,d.appendChild(c);let u=document.createElement("button");u.type="button",u.setAttribute("aria-label","Close card authentication"),u.textContent="\xD7",u.style.cssText=["position:fixed","top:20px","right:20px","width:40px","height:40px","border:0","border-radius:9999px","background:#fff","color:#0f172a","font-size:28px","line-height:40px","cursor:pointer","box-shadow:0 4px 14px rgba(0,0,0,0.25)"].join(";"),u.addEventListener("click",()=>this.abandonActionRequiredOverlay()),d.appendChild(u),d.addEventListener("click",h=>{h.target===d&&this.abandonActionRequiredOverlay()});let y=0,m=h=>{let g=h.data,C=!!g&&typeof g=="object"&&g.source==="flopay-vault-3ds-return";if(h.source!==c.contentWindow){C&&y<zt&&(y+=1,t.record("return_rejected",{reason:"untrusted_source",evidenceBasis:"message_origin_check"}));return}C&&(t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),F(U("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",m),this.threeDsReturnHandler=m,t.record("render_attempted");try{document.body.appendChild(d)}catch(h){throw t.record("render_failed"),this.hideActionRequiredOverlay(),this.actionOverlayPreviousFocus=null,h}t.record("container_attached"),t.record("navigation_assigned");let p=me(d);p&&t.record("container_visibility",{reason:p,evidenceBasis:"parent_computed_style"}),this.actionOverlay=d,c.focus(),this.armActionRequiredTimeout(),F(U("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},jt)}reportChallengeAbandoned(){F((0,T.buildTelemetryTerminalEvent)({eventId:"77777777-7777-4777-8777-777777777777",outcome:"customer_abandoned",stage:"three_ds_handoff",sequence:0,provider:"pcivault",paymentMethodCategory:"card"})),this.telemetryReporter?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"})}timeOutActionRequiredOverlay(){if(this.actionChallenge){let{telemetry:e,loaded:t}=this.actionChallenge;t||e.record("load_unconfirmed",{evidenceBasis:"no_load_signal"}),e.record("timer_expired",{reason:"window_elapsed",evidenceBasis:"timer"}),e.terminal("timer",{reason:"window_elapsed",evidenceBasis:"timer"})}this.reportChallengeAbandoned(),this.closeAbandonedChallenge(),this.hideActionRequiredOverlay(),this.emit("error",{...this.config.sessionId?{sessionId:this.config.sessionId}:{},message:Gt})}abandonActionRequiredOverlay(){if(this.actionOverlay){if(this.actionChallenge){let{telemetry:e}=this.actionChallenge;e.record("cancel_requested",{reason:"buyer_cancel",evidenceBasis:"signal_reason"}),e.terminal("cancel",{reason:"buyer_cancel",evidenceBasis:"signal_reason"})}this.reportChallengeAbandoned(),this.closeAbandonedChallenge(),this.hideActionRequiredOverlay(),this.emit("challenge_dismissed",{...this.config.sessionId?{sessionId:this.config.sessionId}:{}})}}closeAbandonedChallenge(){let e=this.actionChallengeIntentId;this.actionChallengeIntentId=null;let{sessionId:t,sessionToken:r}=this.config;if(!(!e||!t||!r))try{new P((0,T.resolveBillingApiUrl)(this.config.billingApiUrl),{telemetry:!1}).closeThreeDsChallenge(t,r,e).catch(()=>{})}catch{}}beginActionChallengeAttempt(){try{return this.telemetryReporter?.beginThreeDsChallenge?.()}catch{return}}endActionChallengeFromWidget(e){let t=this.actionChallenge,r=t?.telemetry??this.lastChallengeTelemetry;if(this.lastChallengeTelemetry=null,!!r){if(e==="submitting"){if(!t)return;r.record("abort_observed",{reason:"unspecified",evidenceBasis:"signal_reason"}),r.terminal("abort",{reason:"unspecified",evidenceBasis:"signal_reason"});return}t&&r.terminal("status_poll",{evidenceBasis:"server_status"}),e==="complete"&&r.reconcile("succeeded"),e==="decline"&&r.reconcile("declined")}}hideActionRequiredOverlay(){if(this.actionChallengeIntentId=null,this.actionChallenge){let t=this.actionChallenge;this.actionChallenge=null;try{t.detach()}catch{}t.telemetry.record("teardown")}if(this.actionOverlayTimer&&(clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=null),this.threeDsReturnHandler&&(window.removeEventListener("message",this.threeDsReturnHandler),this.threeDsReturnHandler=null),!this.actionOverlay)return;this.actionOverlay.parentNode?.removeChild(this.actionOverlay),this.actionOverlay=null;let e=this.actionOverlayPreviousFocus;this.actionOverlayPreviousFocus=null,e?.isConnected&&e.focus()}applyHeight(e){let t=this.container?.querySelector("iframe");if(!t)return;let r=Math.max(0,Math.min(Math.ceil(e),2e3));t.style.height=`${r}px`}};var hr=["setup_intent","setup_intent_client_secret","redirect_status"];function Le(){if(typeof window>"u")return null;let n=new URLSearchParams(window.location.search);return!n.has("setup_intent")||!n.has("redirect_status")?null:{failed:n.get("redirect_status")==="failed"}}function Ue(){if(typeof window>"u")return;let n=new URL(window.location.href),e=!1;for(let t of hr)n.searchParams.has(t)&&(n.searchParams.delete(t),e=!0);e&&window.history.replaceState(window.history.state,"",n.toString())}0&&(module.exports={PaymentAPI,PciVaultCardCapture,clearSetupRedirectParams,readSetupRedirectReturn});
1
+ "use strict";var i=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var c=Object.getOwnPropertyNames;var d=Object.prototype.hasOwnProperty;var f=(e,t)=>{for(var r in t)i(e,r,{get:t[r],enumerable:!0})},p=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of c(t))!d.call(e,n)&&n!==r&&i(e,n,{get:()=>t[n],enumerable:!(a=u(t,n))||a.enumerable});return e};var l=e=>p(i({},"__esModule",{value:!0}),e);var w={};f(w,{clearSetupRedirectParams:()=>s,readSetupRedirectReturn:()=>o});module.exports=l(w);var R=["setup_intent","setup_intent_client_secret","redirect_status"];function o(){if(typeof window>"u")return null;let e=new URLSearchParams(window.location.search);return!e.has("setup_intent")||!e.has("redirect_status")?null:{failed:e.get("redirect_status")==="failed"}}function s(){if(typeof window>"u")return;let e=new URL(window.location.href),t=!1;for(let r of R)e.searchParams.has(r)&&(e.searchParams.delete(r),t=!0);t&&window.history.replaceState(window.history.state,"",e.toString())}0&&(module.exports={clearSetupRedirectParams,readSetupRedirectReturn});
@@ -1,16 +1,11 @@
1
1
  /**
2
- * Stripe-free entry for card-setup surfaces (`@flopay/js/card-setup`).
2
+ * The `@flopay/js/card-setup` entry: the setup redirect-return helpers only.
3
3
  *
4
- * The main entry eagerly imports `@stripe/stripe-js`, whose module evaluation
5
- * starts downloading the js.stripe.com script — deliberate for checkout (the
6
- * script fetches in parallel with the session fetch and is ready when the
7
- * publishable key arrives), but wrong for surfaces that never initialise
8
- * Stripe. This entry's module graph contains only what the hosted vault
9
- * card-setup flow needs, so a page importing from it stays free of Stripe
10
- * network activity by construction.
4
+ * In 2.0.0 card setup and payment method setup run in the hosted runtime (`mountSetup`, reached
5
+ * through `loadCheckoutRuntime` from the root entry), so this entry no longer exports the 1.x
6
+ * `PaymentAPI` or the hosted card capture. The runtime keeps those modules privately. What stays
7
+ * is reading, and clearing, the parameters a redirect-based setup method adds to the page URL
8
+ * when it returns the buyer.
11
9
  */
12
- export { PaymentAPI } from './payment-api.js';
13
- export type { CardCaptureOperation, PciVaultCardCaptureConfig, } from './pci-vault-card-capture.js';
14
- export { PciVaultCardCapture } from './pci-vault-card-capture.js';
15
10
  export type { SetupRedirectReturn } from './setup-redirect-return.js';
16
11
  export { clearSetupRedirectParams, readSetupRedirectReturn } from './setup-redirect-return.js';
@@ -1 +1 @@
1
- import{q as a,s as n}from"./chunk-YGLB52ZW.mjs";var i=["setup_intent","setup_intent_client_secret","redirect_status"];function o(){if(typeof window>"u")return null;let e=new URLSearchParams(window.location.search);return!e.has("setup_intent")||!e.has("redirect_status")?null:{failed:e.get("redirect_status")==="failed"}}function u(){if(typeof window>"u")return;let e=new URL(window.location.href),t=!1;for(let r of i)e.searchParams.has(r)&&(e.searchParams.delete(r),t=!0);t&&window.history.replaceState(window.history.state,"",e.toString())}export{a as PaymentAPI,n as PciVaultCardCapture,u as clearSetupRedirectParams,o as readSetupRedirectReturn};
1
+ var n=["setup_intent","setup_intent_client_secret","redirect_status"];function i(){if(typeof window>"u")return null;let e=new URLSearchParams(window.location.search);return!e.has("setup_intent")||!e.has("redirect_status")?null:{failed:e.get("redirect_status")==="failed"}}function a(){if(typeof window>"u")return;let e=new URL(window.location.href),t=!1;for(let r of n)e.searchParams.has(r)&&(e.searchParams.delete(r),t=!0);t&&window.history.replaceState(window.history.state,"",e.toString())}export{a as clearSetupRedirectParams,i as readSetupRedirectReturn};
@@ -109,6 +109,18 @@ export interface CheckoutRuntimeAutomaticPayment {
109
109
  export interface CheckoutRuntimeMountOptions {
110
110
  automaticPayment?: CheckoutRuntimeAutomaticPayment;
111
111
  }
112
+ /** The hide list mount option, added in contract 2.5.0. */
113
+ export interface CheckoutRuntimeMountOptions {
114
+ /**
115
+ * Payment methods the runtime does not show, by method or group name, never by processor: the
116
+ * names the wrappers send, such as `card` (the card form), `apple_pay`, `google_pay` and `apms`
117
+ * (the other payment methods). An offered method is left out when its method or its group is
118
+ * listed, and `card` also leaves out either card surface. The runtime only removes methods the
119
+ * session offers; it never adds one, and a name that matches nothing hides nothing. Left out
120
+ * or empty, nothing is hidden. A new list is a new mount.
121
+ */
122
+ hiddenPaymentMethods?: readonly string[];
123
+ }
112
124
  /** Which setup a hosted setup mount runs (contract 2.4.0). Never inferred from an amount. */
113
125
  export type CheckoutRuntimeSetupKind = 'card' | 'payment_method';
114
126
  /**
@@ -0,0 +1,88 @@
1
+ import type { PayPalProviderObjectType, TelemetryAppFamily, TelemetryPopupCapability, TelemetryPresentationMode } from '@flopay/shared';
2
+ import type { CheckoutSession } from './session-gateways.js';
3
+ /**
4
+ * In-band payment-method CHANNEL for Flo-owned PayPal continuations.
5
+ *
6
+ * The payment-method type sent to `POST /v1/checkouts/sessions/{id}/intents`
7
+ * is the channel selector: requesting `paypal_vaulted` opts a single request
8
+ * into the Flo-owned channel (an Order for `intentKind: 'payment'`, a vault
9
+ * setup token for `intentKind: 'setup'`), while the legacy `paypal` type keeps
10
+ * the released provider-managed semantics byte-identical — even when the
11
+ * backend feature flag is on. Sessions advertise availability via
12
+ * `gateways.paypal.providerObjectType` and an informational `paypal_vaulted`
13
+ * entry in `gateways.paypal.enabledPaymentMethods`; there is no capability
14
+ * header and no version-gated routing.
15
+ */
16
+ export declare const PAYPAL_VAULTED_PAYMENT_METHOD_TYPE = "paypal_vaulted";
17
+ /** Buyer-safe recovery copy paired with {@link STORED_PAYMENT_METHOD_UNSUPPORTED_CODE}. */
18
+ export declare const STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE = "This saved payment method can\u2019t be used for this payment. Choose another payment method.";
19
+ /**
20
+ * Buyer-facing copy for `checkout_processing_timeout`. The SDK could not confirm
21
+ * the outcome in time and the payment may still complete, so the buyer must
22
+ * never be invited to pay again (TeamFloPay/sdk#395).
23
+ */
24
+ export declare const CHECKOUT_PROCESSING_TIMEOUT_MESSAGE = "We\u2019re still confirming your payment. Please don\u2019t pay again.";
25
+ /** Privacy-bounded browser context shared by PayPal presentation and telemetry. */
26
+ interface PayPalBrowserEnvironment {
27
+ inAppBrowser: boolean;
28
+ appFamily: TelemetryAppFamily;
29
+ popupCapability: TelemetryPopupCapability;
30
+ }
31
+ /**
32
+ * Classifies an in-app browser without retaining or returning its user agent.
33
+ *
34
+ * Static UA evidence cannot prove that a popup will open, so capability stays
35
+ * `unknown`; runtime lifecycle evidence is reported separately.
36
+ */
37
+ export declare function detectPayPalEnvironment(userAgent?: string): PayPalBrowserEnvironment;
38
+ /**
39
+ * Chooses a PayPal presentation without ever hiding PayPal. Deterministic
40
+ * non-popup modes are limited to one-time Orders in an in-app browser and
41
+ * require the backend's advertisement.
42
+ */
43
+ export declare function resolvePayPalPresentationMode(environment: PayPalBrowserEnvironment, advertisedCapability: TelemetryPresentationMode | undefined, providerObjectType: PayPalProviderObjectType): TelemetryPresentationMode;
44
+ /** One buyer-copy contract shared by wallets and both PayPal integrations. */
45
+ export declare function buildExternalMethodRecoveryMessage(displayName: string, popupBlocked: boolean, inAppBrowser: boolean): string;
46
+ /**
47
+ * The key of the gateway that takes the session's cards, exactly as the API
48
+ * names it: the server-side card gateway when there is one, else the
49
+ * browser-side card provider when the session has it, else `undefined`.
50
+ */
51
+ export declare function cardGatewayName(session: Pick<CheckoutSession, 'gateways'> | null | undefined): string | undefined;
52
+ /**
53
+ * Whether the session can route cards to a gateway the billing API processes
54
+ * entirely server-side behind the hosted vault form (see
55
+ * {@link serverSideCardGatewayName}). Such a gateway has no browser runtime or
56
+ * credentials, and its payment references are not Stripe objects.
57
+ */
58
+ export declare function hasServerSideCardGateway(session: CheckoutSession | null | undefined): boolean;
59
+ /**
60
+ * Whether an open session can recover its hosted card form from
61
+ * `/vault/capture` when the read omitted the embedded block. A server-side
62
+ * card gateway is the explicit card capability; a terminal session has no
63
+ * form left to recover.
64
+ */
65
+ export declare function canRecoverHostedCardForm(session: CheckoutSession | null | undefined): boolean;
66
+ interface StripePayPalResumeContinuation<TAccount = unknown> {
67
+ clientSecret?: string;
68
+ sessionId?: string;
69
+ nonce?: string;
70
+ accountPatch?: TAccount;
71
+ }
72
+ /** `[payment_intent, payment_intent_client_secret, redirect_status]` from the current URL. */
73
+ export declare function readStripeRedirectParams(): [string | null, string | null, string | null];
74
+ /** The current URL without Stripe's redirect parameters (the PayPal `return_url`). */
75
+ export declare function stripeRedirectReturnUrl(): string;
76
+ /**
77
+ * The saved continuation, only when it belongs to `clientSecret`, so a stale
78
+ * payload from a prior attempt can't replay against a different PaymentIntent.
79
+ */
80
+ export declare function readMatchingStripePayPalContinuation<TAccount = unknown>(clientSecret: string | null): StripePayPalResumeContinuation<TAccount> | null;
81
+ /**
82
+ * Saves the continuation, or removes it when called without one. Returns
83
+ * whether storage accepted the change (a redirect must not start without it).
84
+ */
85
+ export declare function writeStripePayPalContinuation(continuation?: StripePayPalResumeContinuation): boolean;
86
+ /** Consumes the continuation and strips Stripe's redirect parameters from the URL. */
87
+ export declare function clearStripePayPalReturn(): void;
88
+ export {};
@@ -0,0 +1,183 @@
1
+ import type { BillingProvider, CheckoutAccount, CheckoutMetadata, CheckoutModeKind, CheckoutProcessError, CheckoutProcessingPending, GatewayEnvironment, PayPalApprovalPresentation, PayPalProviderObjectType, CheckoutSession as PublicCheckoutSessionRead } from '@flopay/shared';
2
+ /** Per-gateway configuration returned by the billing API. */
3
+ interface CheckoutGateway {
4
+ /** Public client identifier (e.g. Stripe publishable key, PayPal client id). */
5
+ publishableKey?: string | null;
6
+ /** Sandbox or live mode for the gateway credentials. */
7
+ environment?: GatewayEnvironment;
8
+ /**
9
+ * Optional Stripe PaymentIntent client secret exposed by the billing API
10
+ * when additional authentication is required for a saved payment method.
11
+ * Stripe-specific.
12
+ */
13
+ stripeClientSecret?: string | null;
14
+ /**
15
+ * Optional publishable key for a dedicated Stripe sub-account that renders
16
+ * PayPal via Stripe Elements. Stripe-specific. Distinct from
17
+ * `gateways.paypal.publishableKey`, which is a PayPal client id used by the
18
+ * direct PayPal SDK.
19
+ */
20
+ paypalPublishableKey?: string | null;
21
+ /**
22
+ * Per-session list of payment method type identifiers that the gateway has
23
+ * enabled for this consumer (e.g. `['apple_pay', 'google_pay', 'cashapp',
24
+ * 'klarna']`). Populated by the billing API after looking up the gateway's
25
+ * Payment Method Configurations. The SDK partitions this list against
26
+ * {@link STRIPE_EXPRESS_METHODS} to decide which methods render in the
27
+ * `ExpressCheckoutElement` row (Apple Pay / Google Pay / PayPal / Link /
28
+ * Amazon Pay / Klarna) vs the `PaymentElement` accordion (Cash App Pay /
29
+ * Affirm / iDEAL / Bancontact / …). `card` is never rendered by Stripe:
30
+ * starting with SDK 1.4.9, its presence explicitly advertises that the
31
+ * provider-neutral hosted card form can be recovered from
32
+ * `POST /v1/checkouts/sessions/{id}/vault/capture` when no embedded
33
+ * {@link CheckoutSession.vault} block is present. Absent on legacy backends.
34
+ * `SplitCardForm` uses this list to scope the retained wallet/APM surfaces.
35
+ * When a buyer selects one, the SDK requests a session-scoped intent for
36
+ * that explicit method. Card checkout uses the hosted vault.
37
+ */
38
+ enabledPaymentMethods?: string[];
39
+ /**
40
+ * Per-method buyer-country gate (uppercase ISO 3166-1 alpha-2), keyed by the
41
+ * same method strings as {@link enabledPaymentMethods}. A method absent here
42
+ * has no country restriction. The SDK filters the rendered tile row by the
43
+ * buyer's *live* country (which can change via AVS after the session is
44
+ * created) against this map — so per-method country eligibility lives in one
45
+ * place (the backend) rather than a hardcoded SDK table. Absent on legacy
46
+ * backends (the SDK then falls back to its built-in table).
47
+ */
48
+ enabledPaymentMethodCountries?: Record<string, string[]>;
49
+ /**
50
+ * PayPal object the backend selected for this checkout continuation — which
51
+ * PayPal JS flow the session needs. New backends advertise `'order'` or
52
+ * `'setup_token'` (legacy provider-managed subscriptions are expressed by
53
+ * omission, though `'subscription'` remains accepted for robustness). Absent
54
+ * → released fallback: `isSubscription ? 'subscription' : 'order'`. The
55
+ * backend suppresses this advertisement for `x-flo-sdk-version` readers
56
+ * older than 1.6.0 (header-less direct integrations always see it);
57
+ * advertisement only — routing follows the payment-method type the client
58
+ * requests. On `gateways.paypal`, {@link enabledPaymentMethods} may also
59
+ * carry an informational `'paypal_vaulted'` entry when the Flo-owned
60
+ * channel is available.
61
+ */
62
+ providerObjectType?: PayPalProviderObjectType;
63
+ /**
64
+ * Backend-advertised approval presentation for a one-time PayPal Order.
65
+ * Return URLs and resume capabilities remain backend-owned.
66
+ */
67
+ approvalPresentation?: PayPalApprovalPresentation;
68
+ }
69
+ /**
70
+ * Map of gateways attached to a session, keyed by gateway code. A session can
71
+ * advertise multiple gateways concurrently — e.g. `gateways.stripe` for card
72
+ * + wallets and `gateways.paypal` for direct PayPal rendering. A session
73
+ * created with the Worldpay capability may also carry
74
+ * `gateways.worldpayCorporateGateway` (TeamFloPay/backend#1563): a card
75
+ * gateway the billing API processes entirely server-side behind the hosted
76
+ * vault form, with no browser credentials or methods.
77
+ */
78
+ export interface CheckoutGateways {
79
+ stripe?: CheckoutGateway;
80
+ paypal?: CheckoutGateway;
81
+ [key: string]: CheckoutGateway | undefined;
82
+ }
83
+ /** Represents a FloPay checkout session, with the gateways the billing API advertised for it. */
84
+ export interface CheckoutSession extends PublicCheckoutSessionRead {
85
+ /**
86
+ * Per-gateway configuration. A session can advertise multiple concurrent
87
+ * gateways — read `gateways.stripe` for card/wallets, `gateways.paypal` for
88
+ * direct PayPal, and so on.
89
+ */
90
+ gateways?: CheckoutGateways;
91
+ }
92
+ /**
93
+ * Provider-agnostic normalized checkout session. Backend may attach multiple
94
+ * gateways per session — read each from `data.<gatewayCode>`.
95
+ */
96
+ export interface NormalizedCheckoutSession {
97
+ /** Gateway codes advertised by the backend for this session, for diagnostics. */
98
+ providers: BillingProvider[];
99
+ mode: CheckoutModeKind;
100
+ autoProcessingError?: CheckoutProcessError;
101
+ autoProcessingAttempted?: boolean;
102
+ autoProcessingPending?: CheckoutProcessingPending;
103
+ /** Immutable client context returned by the FloPay checkout-session API. */
104
+ checkoutMetadata?: CheckoutMetadata;
105
+ data: {
106
+ hostedUrl?: string;
107
+ clientToken?: string;
108
+ session?: CheckoutSession;
109
+ stripe?: {
110
+ clientSecret?: string;
111
+ publishableKey?: string;
112
+ /**
113
+ * Optional dedicated Stripe sub-account publishable key for rendering
114
+ * PayPal via Stripe Elements. When present and distinct, the saved-PM
115
+ * resume flow loads a separate FloPay instance for the PayPal PI.
116
+ */
117
+ paypalPublishableKey?: string;
118
+ environment?: GatewayEnvironment;
119
+ /**
120
+ * Mirrors {@link CheckoutGateway.enabledPaymentMethods}. Drives dynamic
121
+ * `ExpressCheckoutElement` / `PaymentElement` rendering inside
122
+ * `SplitCardForm` instead of the historic hardcoded Apple/Google/PayPal
123
+ * set. Absent on backends that have not yet adopted the field.
124
+ */
125
+ enabledPaymentMethods?: string[];
126
+ /** Mirrors {@link CheckoutGateway.enabledPaymentMethodCountries}. */
127
+ enabledPaymentMethodCountries?: Record<string, string[]>;
128
+ };
129
+ /**
130
+ * Direct PayPal gateway configuration. Present only when the backend has
131
+ * configured a dedicated PayPal gateway for the consumer; absent means the
132
+ * Stripe-rendered PayPal fallback should be used (if Stripe is configured).
133
+ */
134
+ paypal?: {
135
+ publishableKey?: string;
136
+ environment?: GatewayEnvironment;
137
+ providerObjectType?: PayPalProviderObjectType;
138
+ approvalPresentation?: PayPalApprovalPresentation;
139
+ };
140
+ };
141
+ raw?: unknown;
142
+ }
143
+ /**
144
+ * Two-phase result of a **detached** checkout-session create
145
+ * (TeamFloPay/backend#1099).
146
+ *
147
+ * `shell` resolves first, from a create that ran no catalog validation and took
148
+ * no buyer-identity advisory locks. It already carries the session id, nonce,
149
+ * routed `gateways` and the hosted `vault` block, so the card form can mount
150
+ * from it. It does **not** carry products, coupons, buyer identity or cart
151
+ * totals — those arrive with `claimed`.
152
+ *
153
+ * `claimed` starts immediately and resolves when
154
+ * `PATCH /v1/checkouts/sessions/{id}/claim` attaches the catalog. A draft with
155
+ * email uses a combined catalog+buyer claim; an email-less draft omits
156
+ * `accountData` and resolves with a fully-populated anonymous session whose
157
+ * `buyerIdentified` marker is false. Nothing may be charged until it settles:
158
+ * the billing API rejects process / intent / decline calls on an unclaimed
159
+ * session with `409 checkout_session_data_attachment_required`, and its vault
160
+ * webhook holds an unclaimed charge with a `503` until the claim lands.
161
+ */
162
+ export interface DetachedCheckoutSession {
163
+ /** Lightweight shell — mountable card form, no cart or buyer data yet. */
164
+ shell: NormalizedCheckoutSession;
165
+ /** Session id of the shell, available before `claimed` settles. */
166
+ sessionId: string;
167
+ /** Session-bound checkout token, required by the claim and every later call. */
168
+ nonce: string;
169
+ /** Resolves with the catalog-attached session once the initial claim lands. */
170
+ claimed: Promise<NormalizedCheckoutSession>;
171
+ /**
172
+ * Attach buyer identity collected after an email-less session's catalog was
173
+ * attached. Sessions created with an email return `claimed` from this method.
174
+ *
175
+ * Once a claim has actually started, repeated calls return the same
176
+ * replay-safe claim promise. A call rejected by *local* validation (e.g. a
177
+ * missing or malformed email) does not consume the operation: it returns a
178
+ * fresh rejected promise, so a later call with a valid email can still start
179
+ * buyer attachment. Blank/null identity fields are omitted from the request.
180
+ */
181
+ claim(account?: Partial<CheckoutAccount>): Promise<NormalizedCheckoutSession>;
182
+ }
183
+ export {};
@@ -1,7 +1,7 @@
1
1
  import type { PaymentMethodGroupLayout } from '@flopay/shared';
2
2
  import { FloPayError } from '@flopay/shared';
3
3
  import type { CheckoutRuntimeEvent, CheckoutRuntimeLayout } from './checkout-runtime/contract.js';
4
- import type { DescriptorRead } from './checkout-runtime/method-descriptors.js';
4
+ import type { DescriptorRead, PaymentMethodDescriptor } from './checkout-runtime/method-descriptors.js';
5
5
  import type { JsonRecord } from './checkout-runtime/provider-kit.js';
6
6
  export declare function isCompleteStatus(status: unknown): boolean;
7
7
  /**
@@ -72,6 +72,19 @@ export declare function settleProviderReturn(found: ProviderReturn, context: {
72
72
  outcomes: Outcomes;
73
73
  active: () => boolean;
74
74
  }): void;
75
+ /**
76
+ * The merchant's hide list (contract 2.5.0) as the runtime applies it: the names in it, so a value
77
+ * that is not a list hides nothing.
78
+ */
79
+ export declare function readHiddenPaymentMethods(value: unknown): ReadonlySet<string>;
80
+ /**
81
+ * Whether the merchant hid this offered method: it is hidden when its method or its group is
82
+ * listed, and `card` hides either card surface. The wrappers list `card`, the PayPal method, the
83
+ * two wallet methods and `apms`, so a wallet is hidden on its own while the other stays. The rule
84
+ * reads only the method and the group, never the provider, and only removes what the session
85
+ * offers.
86
+ */
87
+ export declare function isHiddenMethod(descriptor: PaymentMethodDescriptor, hidden: ReadonlySet<string>): boolean;
75
88
  /**
76
89
  * Whether Flo's hosted card form is the session's card surface: for a 1.x answer, and for an
77
90
  * advertisement that selects `hosted-card` or names no card surface at all. A `provider-frame`
@@ -93,6 +106,8 @@ export interface PaymentMethodsContext {
93
106
  /** The resolved layout, when the API has already answered. */
94
107
  initialLayout?: PaymentMethodGroupLayout;
95
108
  strings: () => Record<string, string> | undefined;
109
+ /** The methods the merchant hid (contract 2.5.0), read by `readHiddenPaymentMethods`. */
110
+ hidden?: ReadonlySet<string>;
96
111
  }
97
112
  export interface PaymentMethodsSurface {
98
113
  setLayout(layout: PaymentMethodGroupLayout): void;