@flopay/js 1.20.12 → 1.20.13

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.
@@ -0,0 +1 @@
1
+ var lt="flopay_session_display:";var z=new Map;function H(n){return`${lt}${n}`}function Z(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function ee(n,e,t){if(!n)return;let r=t?.ttlMs??36e5,i={data:e,expiresAt:Date.now()+r},s=Z();if(s)try{s.setItem(H(n),JSON.stringify(i));return}catch{}z.set(n,i)}function he(n){if(!n)return null;let e=Z();if(e)try{let r=e.getItem(H(n));if(r){let i=JSON.parse(r);if(i&&typeof i.expiresAt=="number"&&i.expiresAt>Date.now())return i.data;e.removeItem(H(n))}}catch{}let t=z.get(n);if(t){if(t.expiresAt>Date.now())return t.data;z.delete(n)}return null}function me(n){if(!n)return;z.delete(n);let e=Z();if(e)try{e.removeItem(H(n))}catch{}}import{ASYNC_AUTO_CHECKOUT_CAPABILITY as Et,assertCaptureMethodEligible as Me,buildProductPayload as oe,CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as kt,CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED as Mt,classifyPaymentRejection as It,classifyTelemetryFailure as L,FLO_SDK_CAPABILITIES_HEADER as Ie,FLO_SDK_VERSION_HEADER as U,FloPayError as f,foldIntoProducts as re,IDEMPOTENCY_IN_PROGRESS_CODE as Pt,IDEMPOTENCY_KEY_HEADER as Pe,isCardHolderNamePlaceholder as ae,isDetachedSessionEligible as Dt,isUuidV4 as De,isValidEmail as Fe,markSessionResponseReceived as q,normalizeCheckoutFailureOutcome as Oe,normalizePaymentMethodLayout as Ft,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as ne,randomUuidV4 as Ot,readTelemetryHttpDiagnostics as xt,resolveIdempotencyKey as Lt,resolveSessionCurrency as ie,SDK_VERSION as E,STORED_PAYMENT_METHOD_UNSUPPORTED_CODE as xe,STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE as Le,telemetryStatusClass as M,withTelemetryHttpDiagnostics as $e}from"@flopay/shared";function pe(n){return typeof n=="string"&&n.trim()?n:void 0}function ye(n){if(typeof n=="string")return n.trim()?n:void 0;if(Array.isArray(n))return n.filter(t=>typeof t=="string"&&t.trim().length>0).join("; ")||void 0}function P(n=12e3){let e=Number.isFinite(n)&&n>=0?n:12e3,t=new AbortController,r=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function dt(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function j(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",l),l=()=>{o!==void 0&&clearTimeout(o),a(),s(dt())};if(e.aborted){l();return}o=setTimeout(()=>{a(),i()},r),e.addEventListener("abort",l,{once:!0})})}import{buildTelemetryErrorEvent as Re,buildTelemetryLogEvent as Se,buildTelemetryPerformanceEvent as yt,buildTelemetryTerminalEvent as gt,serializeTelemetryBatch as ft,TELEMETRY_MAX_BATCH_BYTES as vt}from"@flopay/shared";import{isThreeDsChallengeAttemptId as fe}from"@flopay/shared";var ct=32,ge=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function ut(){let n=globalThis,e=n[ge];if(e instanceof Map)return e;let t=new Map;try{Object.defineProperty(n,ge,{configurable:!0,enumerable:!1,writable:!1,value:t})}catch{}return t}function ht(n,e){let t=ut(),r=t.get(n);if(r)return r;for(;t.size>=ct;){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 mt=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),pt=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function ve(n,e={}){let t=fe(e.attemptId)?e.attemptId.toLowerCase():n.newAttemptId(),r=()=>{try{let a=n.now();return Number.isFinite(a)?a:0}catch{return 0}},i=ht(t,r());(e.provider==="stripe"||e.provider==="worldpay")&&(i.provider=e.provider);let s=i.provider,o=(a,l)=>{if(i.terminated&&!pt.has(a))return;let d={attemptId:t,phase:a,attemptSequence:i.nextSequence,elapsedMs:Math.max(0,r()-i.startedAt),provider:s};i.nextSequence+=1,l.reason!==void 0&&(d.reason=l.reason),l.evidenceBasis!==void 0&&(d.evidenceBasis=l.evidenceBasis),l.terminalSource!==void 0&&(d.terminalSource=l.terminalSource),l.providerOutcome!==void 0&&(d.providerOutcome=l.providerOutcome);try{n.emit(d,mt.has(a))}catch{}};return{attemptId:t,record(a,l={}){a==="browser_terminal"||a==="provider_reconciled"||o(a,{reason:l.reason,evidenceBasis:l.evidenceBasis})},terminal(a,l={}){i.terminated||(o("browser_terminal",{terminalSource:a,reason:l.reason,evidenceBasis:l.evidenceBasis}),i.terminated=!0)},reconcile(a){i.reconciled.has(a)||(i.reconciled.add(a),o("provider_reconciled",{providerOutcome:a,evidenceBasis:"provider_fact"}))}}}function Ce(n){let e=null;try{e=fe(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 Jr(n){return n==="buyer_cancel"||n==="component_unmount"||n==="navigation"?n:"unspecified"}function Te(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 be(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 _e(n){try{return te(n)==="valid"?new URL(n).origin:null}catch{return null}}var Ct="/v1/sdk-telemetry/events",G=16,Ae=64,Tt=1500,we=1e3,bt=64,_t="00000000-0000-4000-8000-000000000000",Rt={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},St=48;function A(){try{return globalThis.crypto.randomUUID()}catch{let n=new Uint8Array(16);try{globalThis.crypto.getRandomValues(n)}catch{for(let t=0;t<n.length;t+=1)n[t]=Math.floor(Math.random()*256)}n[6]=(n[6]??0)&15|64,n[8]=(n[8]??0)&63|128;let e=[...n].map(t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}}function At(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function wt(n){return JSON.stringify([n.code,n.failureCategory,n.reason,n.stage,n.provider,n.attempt,n.statusClass,n.requestCategory,n.paymentMethodCategory,n.walletType,n.operationOutcome,n.checkoutMode,n.layout,n.inAppBrowser,n.appFamily,n.popupCapability,n.presentationMode,n.terminalReason])}function _(){return globalThis.performance?.now()??0}var w=class{constructor(e){this.ingestionDisabled=!1;this.queue=[];this.sequence=0;this.threeDsChallengeCount=0;this.flushTimer=null;this.flushInFlight=null;this.reportedFailures=new Map;this.checkoutContext={};this.checkoutStartedAt=null;this.destroyed=!1;this.observers=new Set;this.pageExitHandler=()=>{this.drainQueue()};this.visibilityHandler=()=>{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(/\/+$/,"")}${Ct}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=A(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??_,this.browserTransportAvailable=typeof window<"u"&&typeof document<"u",this.browserTransportAvailable&&(window.addEventListener("pagehide",this.pageExitHandler),document.addEventListener("visibilitychange",this.visibilityHandler))}log(e){this.notify({...e,class:"lifecycle"}),this.canCollect()&&this.enqueue(Se({...this.checkoutContext,...e,eventId:A(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=Re({...this.checkoutContext,...e,eventId:_t,sequence:0}),r=wt(t),i=this.now();this.pruneReportedFailures(i);let s=this.reportedFailures.get(r);if(s!==void 0&&i>=s&&i-s<we){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(Re({...this.checkoutContext,...e,eventId:A(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue(yt({...this.checkoutContext,...e,eventId:A(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue(gt({...this.checkoutContext,...e,eventId:A(),sequence:this.sequence++})),e.outcome!=="action_required"&&this.checkoutStartedAt!==null)){let t=this.checkoutStartedAt;this.checkoutStartedAt=null,this.performance({...e,stage:"total_journey",durationMs:Math.max(0,this.now()-t),durationMode:"total"})}}beginThreeDsChallenge(e={}){return ve({now:()=>this.now(),newAttemptId:A,emit:(t,r)=>this.recordThreeDsChallenge(t,r)},e)}recordThreeDsChallenge(e,t){if(!this.canCollect()||this.threeDsChallengeCount>=St)return;let r=Se({...this.checkoutContext,...e,name:"three_ds.challenge",stage:"three_ds_handoff",eventId:A(),sequence:this.sequence++});if(!(this.queue.length>=Ae)){if(this.threeDsChallengeCount+=1,this.queue.push(r),t){this.drainQueue();return}if(this.queue.length>=G){this.flush();return}this.scheduleFlush()}}now(){try{return this.clock()}catch{return _()}}subscribe(e){return this.destroyed?()=>{}:(this.observers.add(e),()=>this.observers.delete(e))}notify(e){if(!this.destroyed)for(let t of this.observers)try{t(e)}catch{}}pruneReportedFailures(e){for(let[t,r]of this.reportedFailures)(e<r||e-r>=we)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=bt;){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>=Ae||this.eventCounts[e.class]>=Rt[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=G){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,G);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,G);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=ft(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:A()});if(At(t)>vt)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 l=>{if(l.status!==202)return null;let d=null;try{d=await l.json()}catch{}return d?.status==="disabled"?"disabled":null}).catch(()=>null),o=new Promise(l=>{i=setTimeout(()=>{r?.abort(),l(null)},Tt)});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)}},Ee=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),ke=globalThis;ke[Ee]===void 0&&Object.defineProperty(ke,Ee,{configurable:!0,enumerable:!1,writable:!1,value:n=>new w(n)});function Ut(n){return n==="on_session"||n==="off_session"}function qt(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function Nt(n){let e=n.vaultOutcome;if(!(!e||e.code!==Mt))return typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0}var Vt="x-flopay-process-result-source",Bt="status",Ye=new WeakSet;function zt(n,e){let t=new f(n,"api_error",{code:e,statusCode:500});return Ye.add(t),t}function Ht(n){return typeof n=="object"&&n!==null&&Ye.has(n)}function Ue(n){return n?.result==="DECLINE"||n?.result==="ERROR"}var jt=50,I=new Map;function Gt(n,e){return I.get(n)?.has(e)===!0}function Kt(n,e){let t=I.get(n)??new Set;if(t.add(e),I.delete(n),I.set(n,t),I.size>jt){let r=I.keys().next().value;r!==void 0&&I.delete(r)}}function $t(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 qe=0,Ne=500,K=15e3,Ve=15e3,Yt=3e3,Wt=1e4,Jt=1e4;function N(n){return typeof n=="object"&&n!==null}function k(n,e){return pe(n?.[e])}function Be(n,e){return ye(n?.[e])}function Qt(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Y(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 se(n){return n instanceof Error&&n.name==="AbortError"}function b(){return new f(kt,"api_error",{code:"checkout_processing_timeout"})}async function S(n,e){let t=await n.json().catch(()=>null),r=N(t?.error)?t.error:null,i=Be(t,"message")??Be(r,"message")??e,s=k(t,"code")??k(t,"gatewayErrorCode")??k(r,"code")??`http_${n.status}`;return $e(new f(i,"api_error",{code:s,statusCode:n.status}),n)}async function Xt(n){if(n.status!==403)return!1;let e=await n.clone().json().catch(()=>null),t=N(e?.error)?e.error:null;return(k(e,"code")??k(t,"code"))==="verification_required"}function Zt(n){if(!(!N(n)||typeof n.required!="boolean"))return{required:n.required,provider:"turnstile"}}async function er(n){let e=n.status===400?await n.clone().json().catch(()=>null):null;return It(n.status,e)}function ze(n){return n===400||n===422}var W=2;async function $(n,e,t=W,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 Y(150*2**o,e?.signal??void 0)}}var tr=2e3,rr=1e4,nr=150;async function ir(n){try{let t=(await n.json())?.data?.status;return t==="closed"||t==="not_open"?t:"failed"}catch{return"failed"}}async function He(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")},rr)});try{let a=await Promise.race([fetch(n,{...e,signal:r.signal}),o]);return a==="timeout"?"failed":a.status>=500?"retry":a.ok?await ir(a):"failed"}catch{return r.signal.aborted?"failed":"retry"}finally{clearTimeout(s),t?.removeEventListener("abort",i)}}function sr(n,e){return new Promise(t=>{let r=setTimeout(t,e);n.then(()=>{clearTimeout(r),t()},()=>{clearTimeout(r),t()})})}var je="stripe-account-switch-v1",or=Symbol.for("@flopay/js.session-create.telemetry.v1");function ar(n){return n[or]}function lr(n){return"now"in n||"onFirstByte"in n||"onSessionCreateFailure"in n||"onRetry"in n}function We(n){let e=ae(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 Je(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 Ge(n){if(typeof n!="string")return;let e=n.trim();return e.length>0?e:void 0}function dr(n){let e={};if(n.country&&(e.country=n.country),!ae(n.firstName,n.lastName)){let t=Ge(n.firstName),r=Ge(n.lastName);t&&(e.firstName=t),r&&(e.lastName=r)}return Object.keys(e).length>0?e:void 0}function cr(n,e,t){let r={clientId:n.clientId,checkoutVersion:E,successUrl:n.successUrl,cancelUrl:n.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};n.captureMethod==="manual"&&(r.captureMethod=n.captureMethod);let i=dr(n.account);i&&(r.accountData=i),Je(r,n);let s=ur(t);return s&&(r.routingProducts=s),r}function ur(n){let e=new Set;for(let t of n){let r=[t.code,t.providerItemId,t.providerPlanId].map(i=>typeof i=="string"?i.trim():"").find(i=>i.length>0);r&&e.add(r)}return e.size>0?Array.from(e,t=>({code:t})):void 0}function Ke(n,e,t){return{currency:e,products:t.map(r=>oe(r,e)),couponCodes:n.couponCodes??[],accountData:We(n.account)}}function hr(n,e,t){return{currency:e,products:t.map(r=>oe(r,e)),couponCodes:n.couponCodes??[]}}function mr(n){let e={},t=ae(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 pr(n){return typeof n=="string"?{expiresAt:n}:n===null?{expiresAt:null}:{}}var R=class R{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=lr(t);this.telemetryHooks=r?t:void 0,this.stripeAccountSwitch=!r&&t.stripeAccountSwitch===!0,this.directTelemetry=r||t.telemetry===!1?void 0:new w({billingApiUrl:this.baseUrl,sdkVersion:E})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,i,s="unknown"){let o=L(e,t);this.directTelemetry?.error({...o,...Ht(e)?{reason:"capture_failed"}:{},stage:r,requestCategory:i,paymentMethodCategory:s})}reportAccountSnapshotFailure(e,t){let r=L(e,"NETWORK_REQUEST_FAILED");if(t==="best_effort"&&r.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...r,stage:"processing",requestCategory:"account_snapshot",paymentMethodCategory:"unknown"})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??_()}catch{return _()}}beginDirectTelemetryCheckout(e){!this.directTelemetry||this.directTelemetryCheckoutId===e||(this.directTelemetryCheckoutId=e,this.directTelemetry.beginCheckout())}beginDirectTelemetryOperation(){this.directTelemetry&&(this.directTelemetryCheckoutId=void 0,this.directTelemetry.beginCheckout())}adoptDirectTelemetryCheckout(e){e&&(this.directTelemetryCheckoutId=e)}async getCheckoutSession(e,t){return this.fetchCheckoutSession(e,t)}async fetchCheckoutSession(e,t,r=!0,i){this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp(),o=s,a=0;this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let l={[U]:E};t&&(l["x-checkout-session-token"]=t);let d=!1;try{let c=await $(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:l,signal:i,cache:"no-store"},W,u=>{this.telemetryHooks?.onRetry?.("session_read",u),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:u})},u=>{a=u,o=this.telemetryTimestamp()});d=!0;let p=Math.max(0,this.telemetryTimestamp()-o);try{this.telemetryHooks?.onFirstByte?.(p,a)}catch{}let h=`${Math.floor(c.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:h,attempt:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:p,durationMode:"machine",requestCategory:"session_read",statusClass:h,attempt:a}),!c.ok)throw await S(c,"Failed to get checkout session");let m=await c.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:h}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"session_read",statusClass:h}),{...m,data:this.mergeCachedDisplayData(m.data)}}catch(c){throw d&&q(c),r&&this.directTelemetry?.error({...L(c,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),c}}cacheSessionDisplayData(e,t,r){ee(e,t,r)}clearSessionDisplayData(e){me(e)}async getVaultCapture(e,t){let r=`${this.baseUrl}\0${e}\0${t??""}`,i=R.activeVaultCaptureRequests.get(r);if(i!==void 0)return i;let s=R.pendingThreeDsAbandonReports.get(e),o=s===void 0?this.requestVaultCapture(e,t):sr(s,tr).then(()=>this.requestVaultCapture(e,t));R.activeVaultCaptureRequests.set(r,o);try{return await o}finally{R.activeVaultCaptureRequests.get(r)===o&&R.activeVaultCaptureRequests.delete(r)}}async requestVaultCapture(e,t){let r=new AbortController,i=setTimeout(()=>r.abort(),Jt);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 $(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:o,signal:r.signal,cache:"no-store"},W,d=>{this.telemetryHooks?.onRetry?.("vault_capture",d),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:d})});if(await Xt(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 S(a,"Failed to load the secure card form");let l=await a.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(l)}catch(a){let l=r.signal.aborted?new f("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(l,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),l}finally{clearTimeout(i)}}async getUnifiedCheckoutSession(e,t){let 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 q(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 f("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:i});let{nonce:o,paymentMethodCategory:a,...l}=t,d=$t(t.tokenizedData),c,p;try{c=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":o},body:JSON.stringify(l)}),p=c}catch(h){if(se(h))throw this.reportDirectFailure(h,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),h;c=await this.reconcileProcessPayment(t.sessionId,{...r,nonce:o,paymentMethodCategory:i,submittedIntentId:d})}if(!c.ok&&c.status!==202){let h=await er(c);return h?this.directTelemetry?.terminal({outcome:h,stage:"processing",requestCategory:"process_payment",statusClass:"4xx",paymentMethodCategory:i}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:M(c.status),failureCategory:c.status>=500?"server_error":void 0,paymentMethodCategory:i,...xt(p)}),c}try{let h=await this.resolveProcessResponse(c,t.sessionId,{...r,nonce:o,paymentMethodCategory:i,submittedIntentId:d});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:M(h.status),paymentMethodCategory:i}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"process_payment",statusClass:M(h.status),paymentMethodCategory:i}),h}catch(h){throw h instanceof f&&h.code==="checkout_processing_timeout"||this.reportDirectFailure(h,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),h}}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??Wt,a=new AbortController,l=()=>a.abort();i?.signal&&(i.signal.aborted?a.abort():i.signal.addEventListener("abort",l,{once:!0}));let d=setTimeout(()=>a.abort(),o);try{let c;try{c=await $(`${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},W,p=>{this.telemetryHooks?.onRetry?.("account_snapshot",p),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:p})})}finally{clearTimeout(d),i?.signal?.removeEventListener("abort",l)}if(!c.ok)throw await S(c,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(c){throw this.reportAccountSnapshotFailure(c,i?.telemetryMode??"blocking"),c}}async createSessionIntent(e,t,r,i){if(!t)throw new f("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",l=typeof o=="string"&&o.length>0&&!a&&(typeof s.paymentMethodId=="string"||s.paymentMethodId===null),d=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(s.intentKind==="payment"||s.intentKind==="setup"),c=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodId===null&&(s.paymentMethodType==="paypal"&&s.intentKind==="payment"||s.paymentMethodType===ne&&(s.intentKind==="payment"||s.intentKind==="setup"));if(!l||!d&&!c)throw new f("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let p=s.authorizationAttemptId;if(p!==void 0&&!De(p))throw new f("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let h=De(p)?p:Ot();this.beginDirectTelemetryCheckout(e);let m=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let u={"Content-Type":"application/json","x-checkout-session-token":t,[Pe]:i?.idempotencyKey||h},y=!1;try{let C=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:u,body:JSON.stringify({...r,authorizationAttemptId:h}),signal:i?.signal});if(!C.ok){y=!0;let X=await S(C,"Failed to create checkout intent"),at=L(X,"PAYMENT_PROCESSING_FAILED");throw ze(X.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...at,stage:"processing",requestCategory:"intent_create"}),X}let v=await C.json();if(C.status===202&&N(v)&&v.type==="checkout_processing")return y=!0,await this.settleProcessingSessionIntent(v,C,e,t,r);let T=v.data;if(!T||typeof T!="object")throw new f("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let g=T,ue=g.paymentMethodType,nt=(g.paymentMethodCategory==="wallet"||g.paymentMethodCategory==="apm")&&typeof ue=="string"&&ue.trim().toLowerCase()!=="card"&&(typeof g.paymentMethodId=="string"||g.paymentMethodId===null)&&typeof g.providerObjectId=="string",it=g.provider==="stripe"&&(g.intentKind==="payment"||g.intentKind==="setup")&&typeof g.clientSecret=="string",st=g.provider==="paypal"&&g.paymentMethodCategory==="wallet"&&g.paymentMethodId===null&&(g.paymentMethodType==="paypal"&&g.intentKind==="payment"&&(g.providerObjectType==="order"||g.providerObjectType==="subscription")||g.paymentMethodType===ne&&g.intentKind==="payment"&&g.providerObjectType==="order"||g.paymentMethodType===ne&&g.intentKind==="setup"&&g.providerObjectType==="setup_token")&&g.clientSecret===null,ot=g.provider===r.provider&&g.paymentMethodCategory===r.paymentMethodCategory&&g.paymentMethodType===r.paymentMethodType&&g.paymentMethodId===r.paymentMethodId&&g.intentKind===r.intentKind;if(!nt||!it&&!st||!ot)throw new f("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:M(C.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-m),durationMode:"machine",requestCategory:"intent_create",statusClass:M(C.status)}),g}catch(C){throw y||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 f&&a.code==="checkout_processing_timeout"?new f(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=R.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 He(s,o,i);if(a!=="retry")return a;if(i?.aborted)return"failed";await Y(nr,i);let l=await He(s,o,i);return l==="retry"?"failed":l}catch{return"failed"}}async reportSessionIntentDecline(e,t,r,i){if(!t)throw new f("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=r,o=s.providerDeclineReason,a=s.paymentMethodType,l=s.providerIntentId,d=typeof o=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(o)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(o),c=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&d,p=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(l===void 0||typeof l=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(l)),h=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodType==="paypal"&&l===void 0;if(!c||!p&&!h)throw new f("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let m=h?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:o}:{provider:"stripe",paymentMethodCategory:s.paymentMethodCategory,paymentMethodType:s.paymentMethodType,providerDeclineReason:o,...typeof l=="string"?{providerIntentId:l}:{}},u=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents/decline`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(m),signal:i?.signal});if(!u.ok)throw await S(u,"Failed to report checkout decline")}async resolvePaymentMethodLayout(e,t,r,i){if(!t)throw new f("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,[U]:E},body:JSON.stringify(r),signal:i?.signal});if(s.status===404||s.status===405)return null;if(!s.ok)throw await S(s,"Failed to resolve the payment method layout");let o=await s.json();return Ft(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 $e(new f("Failed to fetch payments","api_error",{statusCode:a.status}),a);let l=await a.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),l}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if(Dt(e)){let s=e.account.email?.trim();if(s&&!Fe(s))throw new f("Buyer email must be valid when supplied.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"});return(await this.createDetachedSession(e)).claimed}this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=P(e.timeoutMs??12e3),i={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let s=await this.createAndFetchSessionRequest(e,r.signal,i);return this.adoptDirectTelemetryCheckout(s.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:i.statusClass}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:i.statusClass,attempt:i.attempt}),s}catch(s){throw this.reportSessionCreateFailure(s,t,i),s}finally{r.clear()}}async createAndFetchSessionRequest(e,t,r){let i=e.products??re(e.items,e.subscriptions);Me({captureMethod:e.captureMethod,products:i});let s=ie(e.currency,e.items,e.subscriptions,i);if(!s)throw new f("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let o={clientId:e.clientId,checkoutVersion:E,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:s,checkoutMode:e.checkoutMode??"full",products:i.map(d=>oe(d,s)),accountData:We(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(o.captureMethod=e.captureMethod),e.tokenizedData&&(o.tokenizedData=e.tokenizedData),Je(o,e);let a=await this.postCheckoutSessionCreate(o,e,t,r),l=!1;try{let d=await a.json();if(d.data&&"gateways"in d.data){this.autoCacheDisplayData(d.data.uuid,e);let h=this.mergeCachedDisplayData(d.data),m=this.normalizeRawSession(h);return d.vault&&m.data.session&&(m.data.session.vault=this.toVaultBlock(d.vault)),{...m,autoProcessingError:d.autoProcessingError,autoProcessingAttempted:d.autoProcessingAttempted,autoProcessingPending:d.autoProcessingPending}}let c=d.data?.uuid;if(!c)throw new f("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(c,e),this.adoptDirectTelemetryCheckout(c),l=!0,{...await this.getUnifiedCheckoutSession(c),autoProcessingError:d.autoProcessingError,autoProcessingAttempted:d.autoProcessingAttempted,autoProcessingPending:d.autoProcessingPending}}catch(d){throw l?d:q(d)}}async postCheckoutSessionCreate(e,t,r,i){let s={"Content-Type":"application/json",[U]:E},o=Lt(t.idempotencyKey);o&&(s[Pe]=o);let a=[];t.checkoutMode==="auto"&&a.push(Et),this.stripeAccountSwitch&&e.deferDataAttachment===!0&&a.push(je),a.length>0&&(s[Ie]=a.join(", "));let l,d=!1,c=ar(t),p=(m,u,y)=>{d||(d=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:y,attempt:m}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-u),durationMode:"machine",requestCategory:"session_create",statusClass:y,attempt:m}))},h=m=>{try{this.telemetryHooks?.onRetry?.("session_create",m),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:m})}catch{}};for(let m=0;m<3;m++){i.attempt=m;let u=this.telemetryTimestamp();try{c?.onAttempt?.(m)}catch{}try{l=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:s,body:JSON.stringify(e),signal:r})}catch(v){if(i.statusClass=r.aborted||v instanceof Error&&v.name==="AbortError"?"timeout":"network_error",r.aborted||v instanceof Error&&v.name==="AbortError"||m>=2)throw v;let T=m+1;h(T),await j(m,r);continue}let y=M(l.status);if(i.statusClass=y,l.status===204)throw p(m,u,y),new f("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(l.ok){p(m,u,y);break}let C=await S(l,"Failed to create checkout session");if(C.code===Pt&&m<2){h(m+1),await j(m,r);continue}throw p(m,u,y),C}if(!l)throw new TypeError("Checkout-session creation exhausted its retry budget.");return l}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),r=P(e.timeoutMs??12e3),i={attempt:0,statusClass:"unknown"};this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});let s=e.products??re(e.items,e.subscriptions);try{Me({captureMethod:e.captureMethod,products:s})}catch(v){throw r.clear(),this.reportSessionCreateFailure(v,t,i),v}let o=ie(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 f("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});try{Ke(e,o,s)}catch(v){throw r.clear(),this.reportSessionCreateFailure(v,t,i),v}let a,l,d=!1;try{let v=await this.postCheckoutSessionCreate(cr(e,o,s),e,r.signal,i);if(d=!0,l=await v.json(),!l.data||!("gateways"in l.data))throw new f("The billing API returned no session shell for a detached create. It must support `deferDataAttachment` (TeamFloPay/backend#1099).","api_error",{code:"InvalidCheckoutSessionResponse"});a=this.normalizeRawSession(this.mergeCachedDisplayData(l.data)),l.vault&&a.data.session&&(a.data.session.vault=this.toVaultBlock(l.vault))}catch(v){throw r.clear(),d&&q(v),this.reportSessionCreateFailure(v,t,i),v}let c=a.data.session?.id??l.data.uuid??"",p=a.data.session?.clientSecret??l.data.nonce??"";if(!c||!p){r.clear();let v=new f("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(c),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 h=!e.account.email?.trim(),m=P(e.timeoutMs??12e3),u=this.claimCheckoutSession(c,p,h?hr(e,o,s):Ke(e,o,s),{params:e,startedAt:t,deadline:m,createAttempt:i.attempt}),y=h?void 0:u,C=(v={})=>{if(y!==void 0)return y;let T={...e,account:{...e.account,...v,email:v.email?.trim()||e.account.email?.trim()}};return Fe(T.account.email)?(y=u.then(()=>{let g=this.telemetryTimestamp();return this.claimCheckoutSession(c,p,mr(T.account),{params:T,startedAt:g,deadline:P(e.timeoutMs??12e3),createAttempt:0})}),y.catch(()=>{}),y):Promise.reject(new f("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return u.catch(()=>{}),{shell:a,sessionId:c,nonce:p,claimed:u,claim:C}}async claimCheckoutSession(e,t,r,i){let s=i?.startedAt??this.telemetryTimestamp(),o=this.telemetryTimestamp(),a=i?.deadline??P(12e3),l=JSON.stringify(r),d="unknown",c=0,p=!1;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let h;for(c=0;c<3;c++){try{h=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[U]:E,...this.stripeAccountSwitch?{[Ie]:je}:{}},body:l,signal:a.signal})}catch(y){let C=a.signal.aborted||y instanceof Error&&y.name==="AbortError";if(d=C?"timeout":"network_error",C||c>=2)throw y;try{this.telemetryHooks?.onRetry?.("session_claim",c+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:c+1})}catch{}await j(c,a.signal);continue}if(d=M(h.status),h.ok)break;throw await S(h,"Failed to attach checkout session data")}if(!h)throw new TypeError("Checkout-session claim exhausted its retry budget.");p=!0;let m=await h.json();if(!m.data?.gateways)throw new f("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});i?.params&&this.autoCacheDisplayData(m.data.uuid??e,i.params);let u=this.normalizeRawSession(this.mergeCachedDisplayData(m.data));return m.vault&&u.data.session&&(u.data.session.vault=this.toVaultBlock(m.vault)),this.directTelemetry?.log({name:"session.claim.completed",stage:"session_claim",requestCategory:"session_claim",statusClass:d}),this.directTelemetry?.performance({stage:"session_claim",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"session_claim",statusClass:d,attempt:c}),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:d}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"session_create",statusClass:d,attempt:i?.createAttempt??c}),u}catch(h){throw p&&q(h),this.reportSessionCreateFailure(h,o,{attempt:c,statusClass:d},"session_claim"),h}finally{a.clear()}}reportSessionCreateFailure(e,t,r,i="session_create"){if(!(e instanceof f&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let s=L(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 f&&e.type==="validation_error"||e instanceof f&&ze(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 f&&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??K,o=Date.now()+s,a=new AbortController,l=!1,d,c=setTimeout(()=>{d=setTimeout(()=>{l=!0,a.abort()},Ve)},s),p=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?p():t?.signal?.addEventListener("abort",p,{once:!0});let h=this.clampRetryAfterMs(t?.initialDelayMs??qe),m=0;try{if(t?.statusUrl){let u=await this.waitForCheckoutStatus(e,{initialDelayMs:h,timeoutMs:s,nonce:t.nonce,statusUrl:t.statusUrl,pollAfterAction:t.continueAfterActionRequired,signal:a.signal});if(u){let y=await this.resolveCheckoutSessionStatus(e,u,t.nonce,a.signal,()=>l);return this.reportRecoveryCompleted(r,i,t.challengeAttemptId),y}}for(;;){let u=o-Date.now();if(u<=0)throw b();if(h>0){try{m+=1,this.telemetryHooks?.onRetry?.("session_read",m),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:i,attempt:m})}catch{}if(await Y(Math.min(h,u),a.signal),Date.now()>=o)throw b()}let y=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,a.signal),C=y.data.session?.status;if(C==="authorized"||C==="complete"||C==="expired")return this.reportRecoveryCompleted(r,i,t?.challengeAttemptId),y;if(Date.now()>=o)throw b();h=this.clampRetryAfterMs(Math.max(h*2,Ne))}}catch(u){let y=l&&se(u)?b():u;throw this.reportDirectFailure(y,"RECOVERY_FAILED","recovery","session_read",i),y}finally{clearTimeout(c),clearTimeout(d),t?.signal?.removeEventListener("abort",p)}}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 d=o.code===xe;throw new f(d?Le:"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 zt("Payment could not be completed. Please try again.",o?.code??"payment_processing_error");let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,r,i)}catch(d){if(!s?.()||!se(d))throw d;a={providers:[],mode:"tokenize",data:{},raw:t}}let l=a.data.session;return l&&o?.result==="SUCCESS"?{...a,data:{...a.data,session:{...l,status:"complete"}}}:l&&o?.result==="AUTHORIZED"?{...a,data:{...a.data,session:{...l,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:l&&t.status==="completed"?{...a,data:{...a.data,session:{...l,status:"complete"}}}:l&&t.status==="authorized"?{...a,data:{...a.data,session:{...l,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:l&&t.status==="expired"?{...a,data:{...a.data,session:{...l,status:"expired"}}}:o?.result!=="ACTION_REQUIRED"?a:o.gateway==="paypal"&&o.providerIntentId?{...a,autoProcessingError:{type:"paypal_direct_required",message:"PayPal authorization required",orderId:o.providerIntentId,checkoutMethod:"paypal"}}:o.nextActionRedirectUrl?{...a,autoProcessingError:{type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:o.nextActionRedirectUrl}}:a}async waitForCheckoutStatus(e,t){let r=t.timeoutMs??K,i=Date.now()+r,s=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let o=i-Date.now();if(o<=0||s>0&&(await Y(Math.min(s,o),t.signal),Date.now()>=i))throw b();let a=i-Date.now();if(a<=0)throw b();let l=new AbortController,d,c=t.signal?new Promise((T,g)=>{d=g}):null,p=()=>{l.abort(t.signal?.reason),d?.(t.signal?.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))};t.signal?.aborted?p():t.signal?.addEventListener("abort",p,{once:!0});let h,m=t.signal?null:new Promise((T,g)=>{h=setTimeout(()=>{g(b()),l.abort()},a+Ve)}),u;try{let T=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,l.signal);u=await Promise.race([T,m,c].filter(g=>g!==null))}finally{h!==void 0&&clearTimeout(h),t.signal?.removeEventListener("abort",p)}if(!u)return null;let y=Ue(u.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,u,t.submittedIntentId);if(u.status==="completed"||u.status==="authorized"||u.status==="expired"||u.status==="voided")return y?{...u,latestTransactionAttempt:null}:u;let C=u.latestTransactionAttempt?.result,v=t.pollAfterAction===!0&&C==="ACTION_REQUIRED";if(!y&&C!==void 0&&C!=="PENDING"&&!v)return u;s=this.clampRetryAfterMs(Math.max(s*2,Ne))}}isOwnFailedAttempt(e,t,r){let i=t.latestTransactionAttempt?.providerIntentId??null;return r!==void 0?i===r:i===null?!0:!Gt(t.uuid||e,i)}rememberReportedFailure(e,t){let r=t.latestTransactionAttempt;!Ue(r)||!r.providerIntentId||Kt(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 c=new URL(r,`${this.baseUrl}/`),p=new URL(s);c.origin===p.origin&&(o=c.toString())}catch{}let a={[U]:E};t&&(a["x-checkout-session-token"]=t);let l=await $(o,{headers:a,signal:i});if(l.status===404||l.status===405)return null;if(!l.ok)throw await S(l,"Failed to get checkout session status");let d=await l.json();return N(d.data)&&"latestTransactionAttempt"in d.data?d.data:null}normalizeRawSession(e){let t=e.gateways??{},r=[],i={session:this.toCheckoutSession(e)},s=t.stripe;if(s?.publishableKey){r.push("stripe");let l=[e.stripeClientSecret,s.stripeClientSecret].find(d=>typeof d=="string"&&d.length>0);i.stripe={clientSecret:l??"",publishableKey:s.publishableKey??void 0,paypalPublishableKey:s.paypalPublishableKey??void 0,environment:s.environment,enabledPaymentMethods:Array.isArray(s.enabledPaymentMethods)?s.enabledPaymentMethods.filter(d=>typeof d=="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((d,c)=>d+(c.overrideAmount??c.totalAmount??0),0),s=r?e.totalAmount:i,o=Math.round(s*100),a=e.currency??t[0]?.currency??"USD",l="payment";return e.checkoutMode==="setup"?l="setup":t.some(d=>d.type==="subscription")&&(l="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:l,status:this.toCheckoutSessionStatus(e.status),amount:o,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:Oe(e.outcome)??Oe(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}:{},...Ut(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(qt)}:{},buyerIdentified:e.buyerIdentified,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(d=>({...d,totalAmount:typeof d.totalAmount=="number"?d.totalAmount:void 0,overrideAmount:typeof d.overrideAmount=="number"?d.overrideAmount:null,currency:typeof d.currency=="string"?d.currency:void 0,metadata:d.metadata??null})),successUrl:e.successUrl,cancelUrl:e.cancelUrl,coupons:e.coupons,subtotalAmount:e.subtotalAmount,discountAmount:e.discountAmount,totalAmount:e.totalAmount,createdAt:e.createdAt,gateways:e.gateways,accountData:e.accountData,tagsData:e.tagsData}}toVaultBlock(e){let t=Zt(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,...pr(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??K,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={[Vt]:Bt},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,l=a?.code===xe,d=a?.declineReason??void 0;return new Response(JSON.stringify({type:d??"authorization_declined",message:l?Le:"Payment was declined. Please choose another payment method.",code:a?.code??d??"authorization_declined",...d?{declineCode:d}:{}}),{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:Nt(e)??"Payment could not be completed. Please try again."}),{status:500,headers:o});throw b()}async reconcileProcessPayment(e,t){let r=t?.pollTimeoutMs??K,i=Date.now()+r,s=null;try{s=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:r,nonce:t?.nonce,submittedIntentId:t?.submittedIntentId})}catch(l){if(this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),l instanceof f&&l.code==="checkout_processing_timeout")throw l}if(s)return this.toProcessResponseFromStatus(s,e,t?.nonce);let o=i-Date.now();if(o<=0)throw b();let a=await this.waitForCheckoutSessionCompletion(e,{initialDelayMs:0,timeoutMs:o,nonce:t?.nonce,paymentMethodCategory:t?.paymentMethodCategory});return this.toProcessResponseFromSession(a,e)}toProcessResponseFromSession(e,t){if(e.data.session?.status==="complete")return new Response(null,{status:204,statusText:"No Content"});if(e.data.session?.status==="authorized"){let r=e.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:r.paymentId,sessionId:r.id||t,authorizationExpiresAt:r.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(e.data.session?.status==="expired"){let r=e.data.session.failureOutcome==="authorization_expired"||e.data.session.captureMethod==="manual";throw new f(r?"Authorization has expired.":"Checkout session has expired.","api_error",{code:r?"authorization_expired":"checkout_session_expired"})}throw b()}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:k(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs(Qt(e,"retryAfterMs")??o??qe),statusUrl:k(e,"statusUrl"),sessionUrl:k(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,Yt))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??re(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let i=t.products!==void 0,s=ie(t.currency,i?void 0:t.items,i?void 0:t.subscriptions,r);ee(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=he(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),l=a?r.get(a):void 0;return{...o,name:o.name??l?.name??null,totalAmount:o.totalAmount??l?.totalAmount,overrideAmount:o.overrideAmount??l?.overrideAmount,currency:o.currency??l?.currency}});return{...e,currency:e.currency??t?.currency,products:s}}};R.activeVaultCaptureRequests=new Map,R.pendingThreeDsAbandonReports=new Map;var D=R;function an(n,e){let t=D;return new t(n,e)}import{buildCardFieldLabelsPayload as fr,buildTelemetryErrorEvent as vr,buildTelemetryLogEvent as Cr,buildTelemetryTerminalEvent as et,FloPayError as Xe,resolveBillingApiUrl as V,resolveVaultMountOptions as Tr,SDK_VERSION as Ze,THREE_DS_CHALLENGE_WINDOW_MS as br}from"@flopay/shared";import{invokeMerchantCallback as yr,resolveCardFieldsTimeoutMs as gr}from"@flopay/shared";function Qe(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 J=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=gr(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=Qe(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=Qe(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))yr(()=>t(e))}};var _r=4,Q="flopay-vault",Rr=3e4,Sr=br+Rr,Ar="Card authentication timed out.",le=2,wr=6e4;function Er(n){if(!n)return!1;let e=Date.parse(n);return Number.isNaN(e)?!1:e-Date.now()<wr}function kr(n){if(!n)return!1;let e=Date.parse(n);return Number.isFinite(e)&&e>Date.now()}var tt={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 Mr(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:Mr(n),data:e})}catch{}}function B(n,e){return Cr({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var Ir=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function Pr(n){return typeof n=="string"&&Ir.has(n)?n:"unknown"}var Dr=new Set(["verification_failed","verification_expired"]);function Fr(n){return n==null?!0:typeof n=="string"&&Dr.has(n)}var Or="vault_mount";function xr(n){return n.failureStage===Or}function de(n,e){return n&&!xr(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:Pr(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function rt(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 Lr(n,e,t,r="checkout"){let{type:i}=n;if(i==="complete"||i==="decline")return et({eventId:"22222222-2222-4222-8222-222222222222",outcome:rt(n,t,r),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(i==="error"){let a=de(e,n);return vr({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[s,o]=tt[i];return B(s,o)}function Ur(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===Q&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function qr(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 Nr(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 Vr(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===Q&&e.type==="validation"&&Array.isArray(e.messages)}function Br(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===Q&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}function zr(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===Q&&e.type==="fields_interactive"}function Hr(n){let e=n.capabilities;return Array.isArray(e)&&e.includes("fields_interactive")}var jr=["number","expiry","cvv","name"];function Gr(n){if(n===null||typeof n!="object")return;let e=n,t={};for(let r of jr){let i=e[r];typeof i=="string"&&(t[r]=i)}return t}var ce=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 J({timeoutMs:e.cardFieldsTimeoutMs,now:()=>this.telemetryReporter?.now?.()??_(),report:r=>this.reportCardFields(r)}),this.ownsTelemetryReporter=!t&&e.telemetry!==!1,this.telemetryReporter=t?.reporter??(this.ownsTelemetryReporter?new w({billingApiUrl:V(e.billingApiUrl),sdkVersion:Ze}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new w({billingApiUrl:V(this.config.billingApiUrl),sdkVersion:Ze}));let r=this.telemetryReporter;if(this.config.operation==="card_setup"&&r&&this.setupTelemetryReporter!==r){this.setupTelemetryReporter=r;try{r.beginCheckout({checkoutMode:"setup"})}catch{}}if(this.mountStartedAt=this.telemetryReporter?.now?.()??_(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,this.cardFields.begin(),typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),new Xe("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 Xe("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(B("vault.widget.mounted","vault_mount")),this.telemetryReporter?.log({name:"vault.widget.mounted",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?.performance?.({stage:"vault_mount",durationMs:Math.max(0,(this.telemetryReporter.now?.()??_())-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),this.emit("ready",{sessionId:this.config.sessionId}),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>=le?(this.emitRemint("form_unavailable","capped"),!1):(this.beginRemint("form_unavailable"),!0)}considerRemint(e){if(!(this.remintBlocked()||!this.canRemint()||this.remintTask!==null)&&Er(this.captureExpiresAt)){if(this.remintPosts>=le){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 D(V(this.config.billingApiUrl),{telemetry:!1}),o=!1;for(;this.remintPosts<le&&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||!kr(this.captureExpiresAt))&&this.showRemintLoadError()}adoptFreshBlock(e,t,r){if(!this.container)return;let i=Tr(e,{billingApiUrl:V(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(Br(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(Vr(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let d=r.messages.filter(c=>typeof c=="string"&&c.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:d||void 0});return}if(zr(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let d=typeof r.sessionId=="string"?r.sessionId:void 0;if(this.config.sessionId&&d&&d!==this.config.sessionId)return;this.cardFields.ready(),this.remintPosts=0;return}if(!Ur(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=Nr(r.paymentMethod),a=qr(r.vaultOutcome),l={...r.sessionId??this.config.sessionId?{sessionId:r.sessionId??this.config.sessionId}:{},...r.outcome?{outcome:r.outcome}:{},...r.paymentId?{paymentId:r.paymentId}:{},...r.authorizationExpiresAt?{authorizationExpiresAt:r.authorizationExpiresAt}:{},...r.failureOutcome?{failureOutcome:r.failureOutcome}:{},...r.intentId?{intentId:r.intentId}:{},...r.declineReason?{declineReason:r.declineReason}:{},...r.message?{message:r.message}:{},...a?{vaultOutcome:a}:{},...o?{paymentMethod:o}:{}};r.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??_(),this.chargeInFlight=!0,this.remintGeneration+=1,this.remintTask=null),(r.type==="complete"||r.type==="decline"||r.type==="error")&&(this.chargeInFlight=!1),this.isVerificationStateError(r)?(F(B("operation.state_transition","vault_mount")),this.telemetryReporter?.log({name:"operation.state_transition",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})):(F(Lr(r,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(r),r.type==="error"&&de(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(),Hr(r)||this.cardFields.ready()),r.type==="action_required"&&r.nextActionRedirectUrl&&(this.showActionRequiredOverlay(r.nextActionRedirectUrl),this.actionOverlay&&typeof r.intentId=="string"&&r.intentId&&(this.actionChallengeIntentId=r.intentId)),(r.type==="complete"||r.type==="decline"||r.type==="error"||r.type==="submitting")&&(this.endActionChallengeFromWidget(r.type),this.hideActionRequiredOverlay()),r.type!=="action_required"&&this.emit(r.type,l)};this.messageHandler=e,window.addEventListener("message",e)}isVerificationStateError(e){return e.type==="error"&&this.verificationRequired&&!this.submissionStarted&&Fr(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:rt(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(r==="error"){let o=de(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]=tt[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=fr(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=Gr(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 u=this.actionOverlay.querySelector("iframe");u instanceof HTMLIFrameElement&&u.src!==e&&(u.src=e),this.armActionRequiredTimeout();return}this.actionOverlayPreviousFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;let t=Ce(this.beginActionChallengeAttempt()),r=_e(e),i=!1,s=u=>{if(i)return;let y=be(u,r);y&&(i=!0,t.record("policy_violation",{reason:y,evidenceBasis:"parent_csp_event"}))},o=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},a={telemetry:t,loaded:!1,detach:()=>{document.removeEventListener("securitypolicyviolation",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 l=document.createElement("div");l.setAttribute("data-flopay-action-required","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let d=document.createElement("iframe");d.setAttribute("title","Card authentication"),d.setAttribute("allow","payment"),d.tabIndex=0,d.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),d.addEventListener("load",()=>{a.loaded||(a.loaded=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"}))}),d.src=e,l.appendChild(d);let c=document.createElement("button");c.type="button",c.setAttribute("aria-label","Close card authentication"),c.textContent="\xD7",c.style.cssText=["position:fixed","top:20px","right:20px","width:40px","height:40px","border:0","border-radius:9999px","background:#fff","color:#0f172a","font-size:28px","line-height:40px","cursor:pointer","box-shadow:0 4px 14px rgba(0,0,0,0.25)"].join(";"),c.addEventListener("click",()=>this.abandonActionRequiredOverlay()),l.appendChild(c),l.addEventListener("click",u=>{u.target===l&&this.abandonActionRequiredOverlay()});let p=0,h=u=>{let y=u.data,C=!!y&&typeof y=="object"&&y.source==="flopay-vault-3ds-return";if(u.source!==d.contentWindow){C&&p<_r&&(p+=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(B("vault.three_ds.returned","three_ds_return")),this.telemetryReporter?.log({name:"vault.three_ds.returned",stage:"three_ds_return",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay())};window.addEventListener("message",h),this.threeDsReturnHandler=h,t.record("render_attempted");try{document.body.appendChild(l)}catch(u){throw t.record("render_failed"),this.hideActionRequiredOverlay(),this.actionOverlayPreviousFocus=null,u}t.record("container_attached"),t.record("navigation_assigned");let m=Te(l);m&&t.record("container_visibility",{reason:m,evidenceBasis:"parent_computed_style"}),this.actionOverlay=l,d.focus(),this.armActionRequiredTimeout(),F(B("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},Sr)}reportChallengeAbandoned(){F(et({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:Ar})}abandonActionRequiredOverlay(){if(this.actionOverlay){if(this.actionChallenge){let{telemetry:e}=this.actionChallenge;e.record("cancel_requested",{reason:"buyer_cancel",evidenceBasis:"signal_reason"}),e.terminal("cancel",{reason:"buyer_cancel",evidenceBasis:"signal_reason"})}this.reportChallengeAbandoned(),this.closeAbandonedChallenge(),this.hideActionRequiredOverlay(),this.emit("challenge_dismissed",{...this.config.sessionId?{sessionId:this.config.sessionId}:{}})}}closeAbandonedChallenge(){let e=this.actionChallengeIntentId;this.actionChallengeIntentId=null;let{sessionId:t,sessionToken:r}=this.config;if(!(!e||!t||!r))try{new D(V(this.config.billingApiUrl),{telemetry:!1}).closeThreeDsChallenge(t,r,e).catch(()=>{})}catch{}}beginActionChallengeAttempt(){try{return this.telemetryReporter?.beginThreeDsChallenge?.()}catch{return}}endActionChallengeFromWidget(e){let t=this.actionChallenge,r=t?.telemetry??this.lastChallengeTelemetry;if(this.lastChallengeTelemetry=null,!!r){if(e==="submitting"){if(!t)return;r.record("abort_observed",{reason:"unspecified",evidenceBasis:"signal_reason"}),r.terminal("abort",{reason:"unspecified",evidenceBasis:"signal_reason"});return}t&&r.terminal("status_poll",{evidenceBasis:"server_status"}),e==="complete"&&r.reconcile("succeeded"),e==="decline"&&r.reconcile("declined")}}hideActionRequiredOverlay(){if(this.actionChallengeIntentId=null,this.actionChallenge){let t=this.actionChallenge;this.actionChallenge=null;try{t.detach()}catch{}t.telemetry.record("teardown")}if(this.actionOverlayTimer&&(clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=null),this.threeDsReturnHandler&&(window.removeEventListener("message",this.threeDsReturnHandler),this.threeDsReturnHandler=null),!this.actionOverlay)return;this.actionOverlay.parentNode?.removeChild(this.actionOverlay),this.actionOverlay=null;let e=this.actionOverlayPreviousFocus;this.actionOverlayPreviousFocus=null,e?.isConnected&&e.focus()}applyHeight(e){let t=this.container?.querySelector("iframe");if(!t)return;let r=Math.max(0,Math.min(Math.ceil(e),2e3));t.style.height=`${r}px`}};function gn(n,e){let t=ce;return new t(n,{reporter:e})}export{pe as a,ye as b,P as c,j as d,ee as e,he as f,me as g,Ce as h,te as i,Jr as j,Te as k,be as l,_e as m,_ as n,w as o,or as p,D as q,an as r,ce as s,gn as t};