@flopay/js 1.18.1 → 1.19.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.
- package/README.md +16 -1
- package/dist/card-setup.cjs +1 -1
- package/dist/card-setup.mjs +1 -1
- package/dist/chunk-SM2BLO3P.mjs +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/pci-vault-card-capture.d.ts +30 -1
- package/package.json +2 -2
- package/dist/chunk-GJQVTUPW.mjs +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as Y,b as G,c as J,d as ne,e as Q,f as Oe,g as Ue,h as X,i as ie,j as se,k as ae,l as le,m as ce,n as z,o as E,p as Le,q as Be,r as de,s as Z,t as ue}from"./chunk-GJQVTUPW.mjs";import{dropThirdPartyOnlyError as Kt}from"@flopay/shared";import{assertCaptureMethodEligible as Ne,buildProductPayload as qe,classifyTelemetryFailure as ze,FloPayError as O,foldIntoProducts as je,IDEMPOTENCY_IN_PROGRESS_CODE as Ve,IDEMPOTENCY_KEY_HEADER as $e,resolveIdempotencyKey as me,resolveSessionCurrency as Ke,SDK_VERSION as pe,telemetryStatusClass as ye,withTelemetryHttpDiagnostics as He}from"@flopay/shared";var te=5,fe=new WeakSet;function We(e){(typeof e=="object"&&e!==null||typeof e=="function")&&fe.add(e)}function Ye(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&fe.has(e)}function Ge(e,t){let r=t?.error,o=Y(t?.code)??Y(r?.code)??`http_${e}`,a=G(t?.message)??G(r?.message)??Je(o,e);return new O(a,"api_error",{code:o,statusCode:e})}function Je(e,t){switch(e){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${te}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${t}).`}}async function ge(e,t,r){let{billingApiUrl:o,checkoutBaseUrl:a,items:i=[],subscriptions:d=[],products:s,account:c,successUrl:n,cancelUrl:l,checkoutMode:m="confirm",captureMethod:h,couponCodes:w=[],checkoutMetadata:p,tagsData:g,redirectParams:I={},setCookie:f=!0,clientId:x,currency:k,utmMetadata:R,idempotencyKey:U}=e,F=me(U);if(w.length>te)throw new O(`Too many coupon codes \u2014 a checkout session accepts at most ${te}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let S=s??je(i,d);Ne({captureMethod:h,products:S});let _=Ke(k,i,d,S);if(!_)throw new O("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let C={clientId:x,checkoutVersion:pe,successUrl:n,cancelUrl:l,currency:_,checkoutMode:m,products:S.map(v=>qe(v,_)),accountData:{userId:c.userId,firstName:c.firstName??null,lastName:c.lastName??null,email:c.email,country:c.country??null,gender:c.gender??null,city:c.city??null,state:c.state??null,zip:c.zip??null,addressLine1:c.addressLine1??null,addressLine2:c.addressLine2??null},couponCodes:w};h==="manual"&&(C.captureMethod=h),p!==void 0&&(C.checkoutMetadata=p),g&&(C.tagsData=g),R&&R.length>0&&(C.utmMetadata=R);let q=`${o.replace(/\/+$/,"")}/v1/checkouts/sessions`,L={"Content-Type":"application/json"};F&&(L[$e]=F);let b,T,B={method:"POST",headers:L,body:JSON.stringify(C),signal:t},P;try{r?.startAttempt(),P=await fetch(q,B)}catch(v){throw We(v),v}try{r?.record(P.status)}catch{}b=P.status;try{T=await P.json()}catch{}if(b>=400)throw He(Ge(b,T),P);if(b===201){let v=T?.data?.uuid,D=T?.data?.nonce;if(!v)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!D)throw new O("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(S.length>0||_)&&Q(v,{currency:_,products:S.map(u=>({code:u.code??u.providerItemId??u.providerPlanId,type:u.type,name:u.name??u.itemName??u.providerItemName??u.subscriptionName??u.providerPlanName??null,totalAmount:u.totalAmount,overrideAmount:u.overrideAmount,currency:u.currency??_}))});let y=new URL(`${a.replace(/\/+$/,"")}/secure`);y.searchParams.set("id",v);for(let[u,A]of Object.entries(I))y.searchParams.set(u,A);if(f&&typeof window<"u"&&typeof document<"u"){let u=JSON.stringify({origin_url:l}),A=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(u)}; domain=.${A}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(D)}; domain=.${A}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=y.toString()),{status:201,redirectUrl:y.toString(),nonce:D}}return b===204?(typeof window<"u"&&(window.location.href=n),{status:204}):{status:b}}async function Qe(e){let t=Ce(e),r=he(t),o=J(e.timeoutMs);try{let a=await ge(e,o.signal,r);return r.commit(),ve(t,a),a}catch(a){throw r.commit(),j(t,a),a}finally{o.clear(),M(t.reporter)}}function he(e){let t=!1,r=e.startedAt,o;return{startAttempt(){r=e.reporter.now()},record(a){o={status:a,durationMs:Math.max(0,e.reporter.now()-r),attempt:e.attempt}},commit(){if(t||!o)return;t=!0;let a=ye(o.status);e.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:a,attempt:o.attempt}),e.reporter.performance({stage:"session_first_byte",durationMs:o.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:a,attempt:o.attempt})}}}function Ce(e){let t=new E({billingApiUrl:e.billingApiUrl,sdkVersion:pe,enabled:e.telemetry!==!1}),r=t.now();return t.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:t,startedAt:r,attempt:0}}function ve(e,t){let r=ye(t.status);e.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:r}),e.reporter.performance({stage:"session_create",durationMs:e.reporter.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:e.attempt})}function j(e,t){let{reporter:r}=e,o=ze(t,"CHECKOUT_SESSION_CREATE_FAILED");if(r.performance({stage:"session_create",durationMs:r.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:e.attempt}),t instanceof O&&t.type==="validation_error"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(o.statusClass==="4xx"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}r.error({...o,stage:"session_create",requestCategory:"session_create"})}function M(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}async function Xe(e){let{maxRetries:t=2,...r}=e,o=Ce(e),a=he(o);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0||t>=3)throw o.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),M(o.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let i={...r,idempotencyKey:me(r.idempotencyKey)},d=J(r.timeoutMs),s;for(let c=0;c<=t;c++){o.attempt=c;try{let n=await ge(i,d.signal,a);return a.commit(),ve(o,n),d.clear(),M(o.reporter),n}catch(n){s=n;let l=n instanceof Error&&n.name==="AbortError",m=Ye(n),h=n instanceof O&&n.code===Ve;if((l||m||h)&&!d.signal.aborted&&c<t){o.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:c+1});try{await ne(c,d.signal)}catch(w){throw a.commit(),j(o,w),d.clear(),M(o.reporter),w}continue}throw a.commit(),j(o,n),d.clear(),M(o.reporter),n}}throw a.commit(),j(o,s),d.clear(),M(o.reporter),s??new Error("Unknown error during checkout session creation")}import{classifyTelemetryFailure as Ze,FloPayError as V,resolveBillingApiUrl as Se,SDK_VERSION as et}from"@flopay/shared";var we=Symbol.for("@flopay/js.telemetry.bridge.v1");function _e(e,t,r){let o=()=>t?.now()??r();Object.defineProperty(e,we,{configurable:!1,enumerable:!1,writable:!1,value:{error:i=>t?.error(i),log:i=>t?.log(i),performance:i=>t?.performance(i),terminal:i=>t?.terminal(i),now:o,elapsed:i=>Math.max(0,o()-i),setCheckoutContext:i=>t?.setCheckoutContext(i),beginCheckout:(i={})=>t?.beginCheckout(i)??o(),disable:()=>t?.disable(),subscribe:i=>t?.subscribe(i)??(()=>{}),flush:()=>t?.flush()??Promise.resolve()}})}function be(e){return e[we]}var $=class{now(){return this.telemetryReporter?.now?.()??z()}constructor(t,r,o){this.provider=t,this.config=r,this.telemetryReporter=o??new E({billingApiUrl:Se(r.billingApiUrl),sdkVersion:et,enabled:r.telemetry!==!1}),_e(this,this.telemetryReporter,z)}cardCapture(t){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?ue({sessionId:t?.sessionId,captureMethod:t?.captureMethod,cardFieldsTimeoutMs:t?.cardFieldsTimeoutMs},this.telemetryReporter):new Z({sessionId:t?.sessionId,captureMethod:t?.captureMethod,cardFieldsTimeoutMs:t?.cardFieldsTimeoutMs,telemetry:!1})}async retrieveSession(t,r){if(!t)throw new V("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let o=await this.retrieveUnifiedSession(t,r);if(!o.data.session)throw new V("Session not found","api_error");return o.data.session}async retrieveUnifiedSession(t,r){if(!t)throw new V("sessionId is required.","validation_error",{param:"sessionId"});let o=Se(r??this.config.billingApiUrl),a=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let i,d,s=n=>{if(i===void 0)return;let l=i,m=d;i=void 0,d=void 0,this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:n,attempt:m}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:l,durationMode:"machine",requestCategory:"session_read",statusClass:n,attempt:m})},c=de(o,{now:()=>this.telemetryReporter?.now()??z(),onFirstByte:(n,l)=>{i=n,d=l},onRetry:(n,l)=>{this.telemetryReporter?.log({name:"operation.retry",stage:n==="session_read"?"session_read":"processing",requestCategory:n,attempt:l})}});try{let n=await c.getUnifiedCheckoutSession(t);return s("2xx"),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-a,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),n}catch(n){let l=Ze(n,n instanceof V&&n.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw s(l.statusClass),this.telemetryReporter?.error({...l,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-a,durationMode:"machine",requestCategory:"session_read",statusClass:l.statusClass}),n}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.provider.destroy()}};function Pe(e,t,r){let o=$;return new o(e,t,r)}import{FloPayError as nt,resolveBillingApiUrl as re,SDK_VERSION as Te}from"@flopay/shared";import{FloPayError as Ae}from"@flopay/shared";import{loadStripe as tt}from"@stripe/stripe-js";import{toStripeAppearance as rt,toStripeAppearanceTheme as ot}from"@flopay/shared";var ke=new WeakSet;function Re(e){return e instanceof Ae&&ke.has(e)}var N=class{constructor(){this.name="stripe";this.stripe=null}async initialize(t){if(typeof window>"u")return;let r=await tt(t.publishableKey,{locale:t.locale??"auto"});if(!r){let o=new Ae("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw ke.add(o),o}this.stripe=r}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var Ee=new Map;function oe(e){return Array.isArray(e)?e.map(oe):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,oe(r)])):e}function it(e,t){return JSON.stringify([e,re(t?.billingApiUrl),t?.telemetry!==!1,t?.locale??"auto",t?.apiVersion??null,oe(t?.appearance??null)])}var K=new Map;async function st(e,t){if(!e){let s=new E({billingApiUrl:re(t?.billingApiUrl),sdkVersion:Te,enabled:t?.telemetry!==!1});throw s.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),s.flush().catch(()=>{}).finally(()=>s.destroy()),new nt("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let r=it(e,t),o=Ee.get(r);if(o)return t?.telemetry!==!1&&be(o)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),o;let a=K.get(r);if(a)return a;let i={...t,publishableKey:e},d=(async()=>{let s=new E({billingApiUrl:re(i.billingApiUrl),sdkVersion:Te,enabled:i.telemetry!==!1}),c=s.now();s.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),s.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),s.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let n=new N,l=s.now();try{await n.initialize(i)}catch(w){throw s.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:Re(w)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),s.destroy(),w}let m=s.now();s.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),s.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),s.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),s.performance({stage:"sdk_initialize",durationMs:m-c,durationMode:"machine",provider:"stripe"}),s.performance({stage:"provider_ready",durationMs:m-l,durationMode:"machine",provider:"stripe"});let h=Pe(n,i,s);return Ee.set(r,h),h})();K.set(r,d);try{return await d}finally{K.get(r)===d&&K.delete(r)}}import{FloPayError as W,THREE_DS_CHALLENGE_WINDOW_MS as xe}from"@flopay/shared";var at=4,lt=1e3,ct=1e3,dt=15e3;function ut(e){let t=!!e?.gateways?.stripe,r=!!e?.gateways?.worldpayCorporateGateway;return t===r?"unknown":t?"stripe":"worldpay"}function mt(e,t,r){try{return typeof e?.beginThreeDsChallenge!="function"?void 0:e.beginThreeDsChallenge(t,{provider:ut(r)})}catch{return}}function H(e){return new W("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Fe(){return new W("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function De(e){return e.replace(/\/+$/,"")}function pt(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}function yt(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",r=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":case"authorized":case"pending":case"timeout":return{status:t,providerIntentId:r};case"declined":return{status:"declined",providerIntentId:r,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:r,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}async function Me(e){if(typeof document>"u"||typeof window>"u")throw new W("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});let t=X(e.telemetry);t.record("handoff_planned");let r=ie(e.nextActionRedirectUrl);r==="missing"?t.record("action_missing",{reason:"missing_url"}):r==="invalid"&&t.record("action_invalid",{reason:"invalid_url"});let o=p=>{let g=se(p);if(g==="buyer_cancel"){t.record("cancel_requested",{reason:g,evidenceBasis:"signal_reason"}),t.terminal("cancel",{reason:g,evidenceBasis:"signal_reason"});return}t.record("abort_observed",{reason:g,evidenceBasis:"signal_reason"}),t.terminal("abort",{reason:g,evidenceBasis:"signal_reason"})},a=p=>{(p.status==="succeeded"||p.status==="authorized"||p.status==="declined"||p.status==="timeout")&&t.reconcile(p.status)};if(e.signal?.aborted)throw o(e.signal.reason),H();let i=`${De(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,d=async()=>{let p=new AbortController,g=()=>p.abort();e.signal?.aborted?p.abort():e.signal?.addEventListener("abort",g);let I=window.setTimeout(()=>p.abort(),dt);try{let f=await fetch(i,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json",...t.attemptId?{"x-flopay-challenge-attempt":t.attemptId}:{}},body:"{}",signal:p.signal});if(!f.ok)return{status:"unknown"};let x=await f.json().catch(()=>null),k=yt(x);return a(k),k}catch{return{status:"unknown"}}finally{window.clearTimeout(I),e.signal?.removeEventListener("abort",g)}},s,c=()=>e.pollCompletionEndpoint!==!1?d():(s??(s=d()),s),n=document.activeElement instanceof HTMLElement?document.activeElement:null,l=document.createElement("div");l.setAttribute("data-flopay-auto-3ds-overlay","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let m=document.createElement("iframe");m.setAttribute("title","Card authentication"),m.setAttribute("allow","payment"),m.tabIndex=0,m.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let h=null;try{h=new URL(e.billingApiUrl,window.location.href).origin}catch{h=null}let w=ce(e.nextActionRedirectUrl);try{let p=await new Promise((g,I)=>{let f=!1,x=0,k=0,R=0,U=!1,F=!1,S=!1,_=0,C=()=>{window.clearTimeout(x),window.clearInterval(k),window.clearTimeout(R),window.removeEventListener("message",v),window.removeEventListener("pagehide",L),document.removeEventListener("securitypolicyviolation",b),m.removeEventListener("load",T),e.signal?.removeEventListener("abort",B)},q=async()=>{if(!(f||U)){U=!0;try{let y=await c();if(f||!pt(y))return;f=!0,C(),t.terminal("status_poll",{evidenceBasis:"server_status"}),g(y)}finally{U=!1}}},L=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},b=y=>{if(S)return;let u=le(y,w);u&&(S=!0,t.record("policy_violation",{reason:u,evidenceBasis:"parent_csp_event"}))},T=()=>{F||(F=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"})),e.pollCompletionEndpoint!==!1&&(window.clearTimeout(R),R=window.setTimeout(()=>{q()},250))},B=()=>{f||(f=!0,C(),o(e.signal?.reason),I(H()))},P=y=>{f||_>=at||(_+=1,t.record("return_rejected",{reason:y,evidenceBasis:"message_origin_check"}))},v=y=>{let u=y.data,A=!!u&&typeof u=="object"&&u.source==="flopay-vault-3ds-return";if(y.source!==m.contentWindow){A&&P("untrusted_source");return}if(h&&y.origin!==h){A&&P("untrusted_origin");return}A&&(f||(f=!0,C(),t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),g(null)))};x=window.setTimeout(()=>{f||(f=!0,C(),F||t.record("load_unconfirmed",{evidenceBasis:"no_load_signal"}),t.record("timer_expired",{reason:"window_elapsed",evidenceBasis:"timer"}),t.terminal("timer",{reason:"window_elapsed",evidenceBasis:"timer"}),I(Fe()))},xe),e.pollCompletionEndpoint!==!1&&(k=window.setInterval(()=>{q()},ct)),m.addEventListener("load",T),window.addEventListener("message",v),window.addEventListener("pagehide",L),document.addEventListener("securitypolicyviolation",b),e.signal?.addEventListener("abort",B),m.src=e.nextActionRedirectUrl,t.record("render_attempted");try{l.appendChild(m),document.body.appendChild(l)}catch(y){throw f=!0,C(),t.record("render_failed"),y}t.record("container_attached"),t.record("navigation_assigned");let D=ae(l);D&&t.record("container_visibility",{reason:D,evidenceBasis:"parent_computed_style"}),m.focus(),e.signal?.aborted&&B()});return p||await c()}finally{l.parentNode?.removeChild(l),t.record("teardown"),n?.isConnected&&n.focus()}}function Ie(e,t){try{let r=t.data.session?.status;r==="complete"?e.reconcile("succeeded"):r==="authorized"&&e.reconcile("authorized")}catch{}}function ft(e){return new W("Card was declined.","api_error",{code:e.declineReason??"authorization_declined",...e.gatewayDeclineReason?{declineCode:e.gatewayDeclineReason}:{}})}async function gt(e,t){let r=`${De(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/status`,o=new AbortController,a=new AbortController,i=()=>{o.abort(e.signal?.reason),a.abort(e.signal?.reason)};e.signal?.aborted?i():e.signal?.addEventListener("abort",i,{once:!0});let d=X(e.telemetry),s=Me({billingApiUrl:e.billingApiUrl,sessionId:e.sessionId,nonce:e.nonce,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o.signal,pollCompletionEndpoint:!1,...e.telemetry?{telemetry:e.telemetry}:{}}),c=t.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:lt,nonce:e.nonce,statusUrl:r,continueAfterActionRequired:!0,timeoutMs:xe+15e3,signal:a.signal,...d.attemptId?{challengeAttemptId:d.attemptId}:{}});c.catch(()=>{}),s.catch(()=>{});try{let n=await Promise.race([s,c]);if("data"in n)return d.terminal("status_poll",{evidenceBasis:"server_status"}),Ie(d,n),n;if(n.status==="declined")throw(e.createDeclineError??ft)(n);if(n.status==="timeout")throw Fe();let l=await c;return Ie(d,l),l}catch(n){throw e.signal?.aborted||n instanceof Error&&n.name==="AbortError"?H(n):n}finally{e.signal?.removeEventListener("abort",i),o.abort(),a.abort()}}export{$ as FloPay,Be as PaymentAPI,Z as PciVaultCardCapture,Le as SESSION_CREATE_TELEMETRY,N as StripeAdapter,mt as beginSavedCardChallengeTelemetry,Q as cacheSessionDisplayData,Ue as clearSessionDisplayData,gt as completeSavedCardNextAction,Qe as createCheckoutSession,Xe as createCheckoutSessionWithRetries,H as createSavedCardActionAbortedError,Kt as dropThirdPartyOnlyError,Oe as getSessionDisplayData,st as loadFloPay,Me as runSavedCardChallenge,rt as toStripeAppearance,ot as toStripeAppearanceTheme};
|
|
1
|
+
import{a as Y,b as G,c as J,d as ne,e as Q,f as Oe,g as Ue,h as X,i as ie,j as se,k as ae,l as le,m as ce,n as z,o as E,p as Le,q as Be,r as de,s as Z,t as ue}from"./chunk-SM2BLO3P.mjs";import{dropThirdPartyOnlyError as Kt}from"@flopay/shared";import{assertCaptureMethodEligible as Ne,buildProductPayload as qe,classifyTelemetryFailure as ze,FloPayError as O,foldIntoProducts as je,IDEMPOTENCY_IN_PROGRESS_CODE as Ve,IDEMPOTENCY_KEY_HEADER as $e,resolveIdempotencyKey as me,resolveSessionCurrency as Ke,SDK_VERSION as pe,telemetryStatusClass as ye,withTelemetryHttpDiagnostics as He}from"@flopay/shared";var te=5,fe=new WeakSet;function We(e){(typeof e=="object"&&e!==null||typeof e=="function")&&fe.add(e)}function Ye(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&fe.has(e)}function Ge(e,t){let r=t?.error,o=Y(t?.code)??Y(r?.code)??`http_${e}`,a=G(t?.message)??G(r?.message)??Je(o,e);return new O(a,"api_error",{code:o,statusCode:e})}function Je(e,t){switch(e){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${te}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${t}).`}}async function ge(e,t,r){let{billingApiUrl:o,checkoutBaseUrl:a,items:i=[],subscriptions:d=[],products:s,account:c,successUrl:n,cancelUrl:l,checkoutMode:m="confirm",captureMethod:h,couponCodes:w=[],checkoutMetadata:p,tagsData:g,redirectParams:I={},setCookie:f=!0,clientId:x,currency:k,utmMetadata:R,idempotencyKey:U}=e,F=me(U);if(w.length>te)throw new O(`Too many coupon codes \u2014 a checkout session accepts at most ${te}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let S=s??je(i,d);Ne({captureMethod:h,products:S});let _=Ke(k,i,d,S);if(!_)throw new O("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let C={clientId:x,checkoutVersion:pe,successUrl:n,cancelUrl:l,currency:_,checkoutMode:m,products:S.map(v=>qe(v,_)),accountData:{userId:c.userId,firstName:c.firstName??null,lastName:c.lastName??null,email:c.email,country:c.country??null,gender:c.gender??null,city:c.city??null,state:c.state??null,zip:c.zip??null,addressLine1:c.addressLine1??null,addressLine2:c.addressLine2??null},couponCodes:w};h==="manual"&&(C.captureMethod=h),p!==void 0&&(C.checkoutMetadata=p),g&&(C.tagsData=g),R&&R.length>0&&(C.utmMetadata=R);let q=`${o.replace(/\/+$/,"")}/v1/checkouts/sessions`,L={"Content-Type":"application/json"};F&&(L[$e]=F);let b,T,B={method:"POST",headers:L,body:JSON.stringify(C),signal:t},P;try{r?.startAttempt(),P=await fetch(q,B)}catch(v){throw We(v),v}try{r?.record(P.status)}catch{}b=P.status;try{T=await P.json()}catch{}if(b>=400)throw He(Ge(b,T),P);if(b===201){let v=T?.data?.uuid,D=T?.data?.nonce;if(!v)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!D)throw new O("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(S.length>0||_)&&Q(v,{currency:_,products:S.map(u=>({code:u.code??u.providerItemId??u.providerPlanId,type:u.type,name:u.name??u.itemName??u.providerItemName??u.subscriptionName??u.providerPlanName??null,totalAmount:u.totalAmount,overrideAmount:u.overrideAmount,currency:u.currency??_}))});let y=new URL(`${a.replace(/\/+$/,"")}/secure`);y.searchParams.set("id",v);for(let[u,A]of Object.entries(I))y.searchParams.set(u,A);if(f&&typeof window<"u"&&typeof document<"u"){let u=JSON.stringify({origin_url:l}),A=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(u)}; domain=.${A}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(D)}; domain=.${A}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=y.toString()),{status:201,redirectUrl:y.toString(),nonce:D}}return b===204?(typeof window<"u"&&(window.location.href=n),{status:204}):{status:b}}async function Qe(e){let t=Ce(e),r=he(t),o=J(e.timeoutMs);try{let a=await ge(e,o.signal,r);return r.commit(),ve(t,a),a}catch(a){throw r.commit(),j(t,a),a}finally{o.clear(),M(t.reporter)}}function he(e){let t=!1,r=e.startedAt,o;return{startAttempt(){r=e.reporter.now()},record(a){o={status:a,durationMs:Math.max(0,e.reporter.now()-r),attempt:e.attempt}},commit(){if(t||!o)return;t=!0;let a=ye(o.status);e.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:a,attempt:o.attempt}),e.reporter.performance({stage:"session_first_byte",durationMs:o.durationMs,durationMode:"machine",requestCategory:"session_create",statusClass:a,attempt:o.attempt})}}}function Ce(e){let t=new E({billingApiUrl:e.billingApiUrl,sdkVersion:pe,enabled:e.telemetry!==!1}),r=t.now();return t.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:t,startedAt:r,attempt:0}}function ve(e,t){let r=ye(t.status);e.reporter.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:r}),e.reporter.performance({stage:"session_create",durationMs:e.reporter.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r,attempt:e.attempt})}function j(e,t){let{reporter:r}=e,o=ze(t,"CHECKOUT_SESSION_CREATE_FAILED");if(r.performance({stage:"session_create",durationMs:r.now()-e.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:o.statusClass,attempt:e.attempt}),t instanceof O&&t.type==="validation_error"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}if(o.statusClass==="4xx"){r.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create",statusClass:"4xx"});return}r.error({...o,stage:"session_create",requestCategory:"session_create"})}function M(e){e.flush().catch(()=>{}).finally(()=>e.destroy())}async function Xe(e){let{maxRetries:t=2,...r}=e,o=Ce(e),a=he(o);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0||t>=3)throw o.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),M(o.reporter),new Error(`Number of retries must be an integer between 0 and ${2}`);let i={...r,idempotencyKey:me(r.idempotencyKey)},d=J(r.timeoutMs),s;for(let c=0;c<=t;c++){o.attempt=c;try{let n=await ge(i,d.signal,a);return a.commit(),ve(o,n),d.clear(),M(o.reporter),n}catch(n){s=n;let l=n instanceof Error&&n.name==="AbortError",m=Ye(n),h=n instanceof O&&n.code===Ve;if((l||m||h)&&!d.signal.aborted&&c<t){o.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:c+1});try{await ne(c,d.signal)}catch(w){throw a.commit(),j(o,w),d.clear(),M(o.reporter),w}continue}throw a.commit(),j(o,n),d.clear(),M(o.reporter),n}}throw a.commit(),j(o,s),d.clear(),M(o.reporter),s??new Error("Unknown error during checkout session creation")}import{classifyTelemetryFailure as Ze,FloPayError as V,resolveBillingApiUrl as Se,SDK_VERSION as et}from"@flopay/shared";var we=Symbol.for("@flopay/js.telemetry.bridge.v1");function _e(e,t,r){let o=()=>t?.now()??r();Object.defineProperty(e,we,{configurable:!1,enumerable:!1,writable:!1,value:{error:i=>t?.error(i),log:i=>t?.log(i),performance:i=>t?.performance(i),terminal:i=>t?.terminal(i),now:o,elapsed:i=>Math.max(0,o()-i),setCheckoutContext:i=>t?.setCheckoutContext(i),beginCheckout:(i={})=>t?.beginCheckout(i)??o(),disable:()=>t?.disable(),subscribe:i=>t?.subscribe(i)??(()=>{}),flush:()=>t?.flush()??Promise.resolve()}})}function be(e){return e[we]}var $=class{now(){return this.telemetryReporter?.now?.()??z()}constructor(t,r,o){this.provider=t,this.config=r,this.telemetryReporter=o??new E({billingApiUrl:Se(r.billingApiUrl),sdkVersion:et,enabled:r.telemetry!==!1}),_e(this,this.telemetryReporter,z)}cardCapture(t){return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?ue({sessionId:t?.sessionId,captureMethod:t?.captureMethod,cardFieldsTimeoutMs:t?.cardFieldsTimeoutMs},this.telemetryReporter):new Z({sessionId:t?.sessionId,captureMethod:t?.captureMethod,cardFieldsTimeoutMs:t?.cardFieldsTimeoutMs,telemetry:!1})}async retrieveSession(t,r){if(!t)throw new V("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let o=await this.retrieveUnifiedSession(t,r);if(!o.data.session)throw new V("Session not found","api_error");return o.data.session}async retrieveUnifiedSession(t,r){if(!t)throw new V("sessionId is required.","validation_error",{param:"sessionId"});let o=Se(r??this.config.billingApiUrl),a=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let i,d,s=n=>{if(i===void 0)return;let l=i,m=d;i=void 0,d=void 0,this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:n,attempt:m}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:l,durationMode:"machine",requestCategory:"session_read",statusClass:n,attempt:m})},c=de(o,{now:()=>this.telemetryReporter?.now()??z(),onFirstByte:(n,l)=>{i=n,d=l},onRetry:(n,l)=>{this.telemetryReporter?.log({name:"operation.retry",stage:n==="session_read"?"session_read":"processing",requestCategory:n,attempt:l})}});try{let n=await c.getUnifiedCheckoutSession(t);return s("2xx"),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-a,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),n}catch(n){let l=Ze(n,n instanceof V&&n.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED");throw s(l.statusClass),this.telemetryReporter?.error({...l,stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-a,durationMode:"machine",requestCategory:"session_read",statusClass:l.statusClass}),n}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.provider.destroy()}};function Pe(e,t,r){let o=$;return new o(e,t,r)}import{FloPayError as nt,resolveBillingApiUrl as re,SDK_VERSION as Te}from"@flopay/shared";import{FloPayError as Ae}from"@flopay/shared";import{loadStripe as tt}from"@stripe/stripe-js";import{toStripeAppearance as rt,toStripeAppearanceTheme as ot}from"@flopay/shared";var ke=new WeakSet;function Re(e){return e instanceof Ae&&ke.has(e)}var N=class{constructor(){this.name="stripe";this.stripe=null}async initialize(t){if(typeof window>"u")return;let r=await tt(t.publishableKey,{locale:t.locale??"auto"});if(!r){let o=new Ae("Failed to initialize Stripe. Check your publishable key.","authentication_error");throw ke.add(o),o}this.stripe=r}getRawProvider(){return this.stripe}destroy(){this.stripe=null}};var Ee=new Map;function oe(e){return Array.isArray(e)?e.map(oe):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,oe(r)])):e}function it(e,t){return JSON.stringify([e,re(t?.billingApiUrl),t?.telemetry!==!1,t?.locale??"auto",t?.apiVersion??null,oe(t?.appearance??null)])}var K=new Map;async function st(e,t){if(!e){let s=new E({billingApiUrl:re(t?.billingApiUrl),sdkVersion:Te,enabled:t?.telemetry!==!1});throw s.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),s.flush().catch(()=>{}).finally(()=>s.destroy()),new nt("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let r=it(e,t),o=Ee.get(r);if(o)return t?.telemetry!==!1&&be(o)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),o;let a=K.get(r);if(a)return a;let i={...t,publishableKey:e},d=(async()=>{let s=new E({billingApiUrl:re(i.billingApiUrl),sdkVersion:Te,enabled:i.telemetry!==!1}),c=s.now();s.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),s.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),s.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let n=new N,l=s.now();try{await n.initialize(i)}catch(w){throw s.error({errorCode:"PROVIDER_LOAD_FAILED",failureCategory:Re(w)?"invalid_response":"provider_runtime",stage:"provider_load",provider:"stripe",requestCategory:"provider_sdk",paymentMethodCategory:"unknown"}),s.destroy(),w}let m=s.now();s.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),s.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),s.log({name:"sdk.initialize.ready",stage:"sdk_initialize"}),s.performance({stage:"sdk_initialize",durationMs:m-c,durationMode:"machine",provider:"stripe"}),s.performance({stage:"provider_ready",durationMs:m-l,durationMode:"machine",provider:"stripe"});let h=Pe(n,i,s);return Ee.set(r,h),h})();K.set(r,d);try{return await d}finally{K.get(r)===d&&K.delete(r)}}import{FloPayError as W,THREE_DS_CHALLENGE_WINDOW_MS as xe}from"@flopay/shared";var at=4,lt=1e3,ct=1e3,dt=15e3;function ut(e){let t=!!e?.gateways?.stripe,r=!!e?.gateways?.worldpayCorporateGateway;return t===r?"unknown":t?"stripe":"worldpay"}function mt(e,t,r){try{return typeof e?.beginThreeDsChallenge!="function"?void 0:e.beginThreeDsChallenge(t,{provider:ut(r)})}catch{return}}function H(e){return new W("Card authentication was cancelled.","api_error",{code:"three_ds_aborted",cause:e})}function Fe(){return new W("Card authentication timed out.","api_error",{code:"three_ds_timeout"})}function De(e){return e.replace(/\/+$/,"")}function pt(e){return e.status==="succeeded"||e.status==="authorized"||e.status==="declined"}function yt(e){if(!e||typeof e!="object")return{status:"unknown"};let t=typeof e.status=="string"?e.status:"unknown",r=typeof e.providerIntentId=="string"?e.providerIntentId:null;switch(t){case"succeeded":case"authorized":case"pending":case"timeout":return{status:t,providerIntentId:r};case"declined":return{status:"declined",providerIntentId:r,declineReason:typeof e.declineReason=="string"?e.declineReason:null,gatewayDeclineReason:typeof e.gatewayDeclineReason=="string"?e.gatewayDeclineReason:null};case"requires_action":return{status:"requires_action",providerIntentId:r,nextActionRedirectUrl:typeof e.nextActionRedirectUrl=="string"?e.nextActionRedirectUrl:null};case"no_attempt":return{status:"no_attempt"};default:return{status:"unknown"}}}async function Me(e){if(typeof document>"u"||typeof window>"u")throw new W("3DS challenge requires a browser environment.","api_error",{code:"three_ds_no_window"});let t=X(e.telemetry);t.record("handoff_planned");let r=ie(e.nextActionRedirectUrl);r==="missing"?t.record("action_missing",{reason:"missing_url"}):r==="invalid"&&t.record("action_invalid",{reason:"invalid_url"});let o=p=>{let g=se(p);if(g==="buyer_cancel"){t.record("cancel_requested",{reason:g,evidenceBasis:"signal_reason"}),t.terminal("cancel",{reason:g,evidenceBasis:"signal_reason"});return}t.record("abort_observed",{reason:g,evidenceBasis:"signal_reason"}),t.terminal("abort",{reason:g,evidenceBasis:"signal_reason"})},a=p=>{(p.status==="succeeded"||p.status==="authorized"||p.status==="declined"||p.status==="timeout")&&t.reconcile(p.status)};if(e.signal?.aborted)throw o(e.signal.reason),H();let i=`${De(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/3ds/complete`,d=async()=>{let p=new AbortController,g=()=>p.abort();e.signal?.aborted?p.abort():e.signal?.addEventListener("abort",g);let I=window.setTimeout(()=>p.abort(),dt);try{let f=await fetch(i,{method:"POST",headers:{"x-checkout-session-token":e.nonce,"content-type":"application/json",...t.attemptId?{"x-flopay-challenge-attempt":t.attemptId}:{}},body:"{}",signal:p.signal});if(!f.ok)return{status:"unknown"};let x=await f.json().catch(()=>null),k=yt(x);return a(k),k}catch{return{status:"unknown"}}finally{window.clearTimeout(I),e.signal?.removeEventListener("abort",g)}},s,c=()=>e.pollCompletionEndpoint!==!1?d():(s??(s=d()),s),n=document.activeElement instanceof HTMLElement?document.activeElement:null,l=document.createElement("div");l.setAttribute("data-flopay-auto-3ds-overlay","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let m=document.createElement("iframe");m.setAttribute("title","Card authentication"),m.setAttribute("allow","payment"),m.tabIndex=0,m.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";");let h=null;try{h=new URL(e.billingApiUrl,window.location.href).origin}catch{h=null}let w=ce(e.nextActionRedirectUrl);try{let p=await new Promise((g,I)=>{let f=!1,x=0,k=0,R=0,U=!1,F=!1,S=!1,_=0,C=()=>{window.clearTimeout(x),window.clearInterval(k),window.clearTimeout(R),window.removeEventListener("message",v),window.removeEventListener("pagehide",L),document.removeEventListener("securitypolicyviolation",b),m.removeEventListener("load",T),e.signal?.removeEventListener("abort",B)},q=async()=>{if(!(f||U)){U=!0;try{let y=await c();if(f||!pt(y))return;f=!0,C(),t.terminal("status_poll",{evidenceBasis:"server_status"}),g(y)}finally{U=!1}}},L=()=>{t.record("pagehide_observed",{evidenceBasis:"page_lifecycle_event"})},b=y=>{if(S)return;let u=le(y,w);u&&(S=!0,t.record("policy_violation",{reason:u,evidenceBasis:"parent_csp_event"}))},T=()=>{F||(F=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"})),e.pollCompletionEndpoint!==!1&&(window.clearTimeout(R),R=window.setTimeout(()=>{q()},250))},B=()=>{f||(f=!0,C(),o(e.signal?.reason),I(H()))},P=y=>{f||_>=at||(_+=1,t.record("return_rejected",{reason:y,evidenceBasis:"message_origin_check"}))},v=y=>{let u=y.data,A=!!u&&typeof u=="object"&&u.source==="flopay-vault-3ds-return";if(y.source!==m.contentWindow){A&&P("untrusted_source");return}if(h&&y.origin!==h){A&&P("untrusted_origin");return}A&&(f||(f=!0,C(),t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),g(null)))};x=window.setTimeout(()=>{f||(f=!0,C(),F||t.record("load_unconfirmed",{evidenceBasis:"no_load_signal"}),t.record("timer_expired",{reason:"window_elapsed",evidenceBasis:"timer"}),t.terminal("timer",{reason:"window_elapsed",evidenceBasis:"timer"}),I(Fe()))},xe),e.pollCompletionEndpoint!==!1&&(k=window.setInterval(()=>{q()},ct)),m.addEventListener("load",T),window.addEventListener("message",v),window.addEventListener("pagehide",L),document.addEventListener("securitypolicyviolation",b),e.signal?.addEventListener("abort",B),m.src=e.nextActionRedirectUrl,t.record("render_attempted");try{l.appendChild(m),document.body.appendChild(l)}catch(y){throw f=!0,C(),t.record("render_failed"),y}t.record("container_attached"),t.record("navigation_assigned");let D=ae(l);D&&t.record("container_visibility",{reason:D,evidenceBasis:"parent_computed_style"}),m.focus(),e.signal?.aborted&&B()});return p||await c()}finally{l.parentNode?.removeChild(l),t.record("teardown"),n?.isConnected&&n.focus()}}function Ie(e,t){try{let r=t.data.session?.status;r==="complete"?e.reconcile("succeeded"):r==="authorized"&&e.reconcile("authorized")}catch{}}function ft(e){return new W("Card was declined.","api_error",{code:e.declineReason??"authorization_declined",...e.gatewayDeclineReason?{declineCode:e.gatewayDeclineReason}:{}})}async function gt(e,t){let r=`${De(e.billingApiUrl)}/v1/checkouts/sessions/${encodeURIComponent(e.sessionId)}/status`,o=new AbortController,a=new AbortController,i=()=>{o.abort(e.signal?.reason),a.abort(e.signal?.reason)};e.signal?.aborted?i():e.signal?.addEventListener("abort",i,{once:!0});let d=X(e.telemetry),s=Me({billingApiUrl:e.billingApiUrl,sessionId:e.sessionId,nonce:e.nonce,nextActionRedirectUrl:e.nextActionRedirectUrl,signal:o.signal,pollCompletionEndpoint:!1,...e.telemetry?{telemetry:e.telemetry}:{}}),c=t.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:lt,nonce:e.nonce,statusUrl:r,continueAfterActionRequired:!0,timeoutMs:xe+15e3,signal:a.signal,...d.attemptId?{challengeAttemptId:d.attemptId}:{}});c.catch(()=>{}),s.catch(()=>{});try{let n=await Promise.race([s,c]);if("data"in n)return d.terminal("status_poll",{evidenceBasis:"server_status"}),Ie(d,n),n;if(n.status==="declined")throw(e.createDeclineError??ft)(n);if(n.status==="timeout")throw Fe();let l=await c;return Ie(d,l),l}catch(n){throw e.signal?.aborted||n instanceof Error&&n.name==="AbortError"?H(n):n}finally{e.signal?.removeEventListener("abort",i),o.abort(),a.abort()}}export{$ as FloPay,Be as PaymentAPI,Z as PciVaultCardCapture,Le as SESSION_CREATE_TELEMETRY,N as StripeAdapter,mt as beginSavedCardChallengeTelemetry,Q as cacheSessionDisplayData,Ue as clearSessionDisplayData,gt as completeSavedCardNextAction,Qe as createCheckoutSession,Xe as createCheckoutSessionWithRetries,H as createSavedCardActionAbortedError,Kt as dropThirdPartyOnlyError,Oe as getSessionDisplayData,st as loadFloPay,Me as runSavedCardChallenge,rt as toStripeAppearance,ot as toStripeAppearanceTheme};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { CaptureMethod, CardCaptureAdapter, CardCaptureEventType, CardCaptureMountOptions, CardCaptureOutcomeEvent, CardCaptureProviderId, CardFieldPlaceholders, CardFieldsEvent, VaultCardFieldKey, VaultCardThemeColors } from '@flopay/shared';
|
|
1
|
+
import type { CaptureMethod, CardCaptureAdapter, CardCaptureEventType, CardCaptureMountOptions, CardCaptureOutcomeEvent, CardCaptureProviderId, CardFieldLabels, CardFieldPlaceholders, CardFieldsEvent, VaultCardFieldKey, VaultCardThemeColors } from '@flopay/shared';
|
|
2
2
|
import { TelemetryReporter } from './telemetry-reporter.js';
|
|
3
3
|
/** Browser operation hosted by the PCIVault card-capture adapter. */
|
|
4
4
|
export type CardCaptureOperation = 'checkout' | 'card_setup';
|
|
@@ -98,6 +98,13 @@ export declare class PciVaultCardCapture implements CardCaptureAdapter {
|
|
|
98
98
|
* Discover icons. Off by default; only `true` turns them on.
|
|
99
99
|
*/
|
|
100
100
|
private cardBrandIcons;
|
|
101
|
+
/**
|
|
102
|
+
* Latest card field label settings: whether the labels show, and their text
|
|
103
|
+
* (only the fields that were set). Each stays `undefined` until the host sets
|
|
104
|
+
* it, so a host that never does posts no label message at all.
|
|
105
|
+
*/
|
|
106
|
+
private showCardFieldLabels;
|
|
107
|
+
private cardFieldLabels;
|
|
101
108
|
/**
|
|
102
109
|
* Latest merchant submit wording: a label, `null` for the explicit reset to
|
|
103
110
|
* the hosted session default, or `undefined` when the host has never set
|
|
@@ -189,6 +196,28 @@ export declare class PciVaultCardCapture implements CardCaptureAdapter {
|
|
|
189
196
|
* `ready` re-pushes it; an older hosted form ignores the directive.
|
|
190
197
|
*/
|
|
191
198
|
setCardBrandIcons(show: boolean): void;
|
|
199
|
+
/**
|
|
200
|
+
* Show or hide the visible labels above the hosted card fields (live, no
|
|
201
|
+
* remount). Only `true` shows them. Stored so `ready` re-pushes it; an older
|
|
202
|
+
* hosted form ignores the directive.
|
|
203
|
+
*/
|
|
204
|
+
setShowCardFieldLabels(show: boolean): void;
|
|
205
|
+
/**
|
|
206
|
+
* Replace the text of the hosted card field labels (live, no remount). Only
|
|
207
|
+
* the string text of `number`, `expiry`, `cvv` and `name` is sent, verbatim:
|
|
208
|
+
* the hosted form shows it literally. `null` clears the text, so the hosted
|
|
209
|
+
* form falls back to its defaults. Stored so `ready` re-pushes it.
|
|
210
|
+
*/
|
|
211
|
+
setCardFieldLabels(labels: CardFieldLabels | null): void;
|
|
212
|
+
/**
|
|
213
|
+
* postMessage the retained card field label settings to the widget's
|
|
214
|
+
* document: `show` once the host set it, `labels` once the host set them.
|
|
215
|
+
* Nothing is posted while the host has set neither. Like the submit label,
|
|
216
|
+
* the label text is merchant text drawn inside the card form, so it is sent
|
|
217
|
+
* only with the session + message-token binding the hosted form checks, and
|
|
218
|
+
* only to the vault block's exact origin — never to `'*'`.
|
|
219
|
+
*/
|
|
220
|
+
private postCardFieldLabels;
|
|
192
221
|
/**
|
|
193
222
|
* Set the placeholder text of the hosted card number, expiry, CVV and name
|
|
194
223
|
* fields (live, no remount). Only the fields given are sent; the hosted form
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@flopay/js",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.19.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"publishConfig": {
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"dist"
|
|
32
32
|
],
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@flopay/shared": "1.
|
|
34
|
+
"@flopay/shared": "1.19.0",
|
|
35
35
|
"@stripe/stripe-js": "^10.3.0"
|
|
36
36
|
},
|
|
37
37
|
"devDependencies": {
|
package/dist/chunk-GJQVTUPW.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var it="flopay_session_display:";var V=new Map;function B(r){return`${it}${r}`}function J(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function Q(r,e,t){if(!r)return;let n=t?.ttlMs??36e5,i={data:e,expiresAt:Date.now()+n},s=J();if(s)try{s.setItem(B(r),JSON.stringify(i));return}catch{}V.set(r,i)}function de(r){if(!r)return null;let e=J();if(e)try{let n=e.getItem(B(r));if(n){let i=JSON.parse(n);if(i&&typeof i.expiresAt=="number"&&i.expiresAt>Date.now())return i.data;e.removeItem(B(r))}}catch{}let t=V.get(r);if(t){if(t.expiresAt>Date.now())return t.data;V.delete(r)}return null}function ue(r){if(!r)return;V.delete(r);let e=J();if(e)try{e.removeItem(B(r))}catch{}}import{ASYNC_AUTO_CHECKOUT_CAPABILITY as St,assertCaptureMethodEligible as ke,buildProductPayload as se,CHECKOUT_PROCESSING_TIMEOUT_MESSAGE as Rt,CHECKOUT_SESSION_BUYER_EMAIL_REQUIRED as At,classifyPaymentRejection as Et,classifyTelemetryFailure as x,FLO_SDK_CAPABILITIES_HEADER as kt,FLO_SDK_VERSION_HEADER as U,FloPayError as v,foldIntoProducts as Z,IDEMPOTENCY_IN_PROGRESS_CODE as wt,IDEMPOTENCY_KEY_HEADER as we,isCardHolderNamePlaceholder as oe,isDetachedSessionEligible as Mt,isUuidV4 as Me,isValidEmail as Ie,markSessionResponseReceived as q,normalizeCheckoutFailureOutcome as Pe,normalizePaymentMethodLayout as It,PAYPAL_VAULTED_PAYMENT_METHOD_TYPE as ee,randomUuidV4 as Pt,readTelemetryHttpDiagnostics as Dt,resolveIdempotencyKey as Ft,resolveSessionCurrency as te,SDK_VERSION as E,STORED_PAYMENT_METHOD_UNSUPPORTED_CODE as De,STORED_PAYMENT_METHOD_UNSUPPORTED_MESSAGE as Fe,telemetryStatusClass as w,withTelemetryHttpDiagnostics as ze}from"@flopay/shared";function he(r){return typeof r=="string"&&r.trim()?r:void 0}function me(r){if(typeof r=="string")return r.trim()?r:void 0;if(Array.isArray(r))return r.filter(t=>typeof t=="string"&&t.trim().length>0).join("; ")||void 0}function P(r=12e3){let e=Number.isFinite(r)&&r>=0?r:12e3,t=new AbortController,n=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(n)}}function st(){return Object.assign(new Error("The operation was aborted."),{name:"AbortError"})}function z(r,e){let t=150*2**r,n=Math.round(t*(.75+Math.random()*.5));return new Promise((i,s)=>{let o,a=()=>e.removeEventListener("abort",l),l=()=>{o!==void 0&&clearTimeout(o),a(),s(st())};if(e.aborted){l();return}o=setTimeout(()=>{a(),i()},n),e.addEventListener("abort",l,{once:!0})})}import{buildTelemetryErrorEvent as be,buildTelemetryLogEvent as _e,buildTelemetryPerformanceEvent as ut,buildTelemetryTerminalEvent as ht,serializeTelemetryBatch as mt,TELEMETRY_MAX_BATCH_BYTES as pt}from"@flopay/shared";import{isThreeDsChallengeAttemptId as ye}from"@flopay/shared";var ot=32,pe=Symbol.for("@flopay/js.three-ds-challenge.attempts.v1");function at(){let r=globalThis,e=r[pe];if(e instanceof Map)return e;let t=new Map;try{Object.defineProperty(r,pe,{configurable:!0,enumerable:!1,writable:!1,value:t})}catch{}return t}function lt(r,e){let t=at(),n=t.get(r);if(n)return n;for(;t.size>=ot;){let s=t.keys().next();if(s.done)break;t.delete(s.value)}let i={nextSequence:0,startedAt:e,terminated:!1,reconciled:new Set,provider:"unknown"};return t.set(r,i),i}var ct=new Set(["pagehide_observed","cancel_requested","abort_observed","browser_terminal"]),dt=new Set(["teardown","recovery_read_completed","provider_reconciled"]);function ge(r,e={}){let t=ye(e.attemptId)?e.attemptId.toLowerCase():r.newAttemptId(),n=()=>{try{let a=r.now();return Number.isFinite(a)?a:0}catch{return 0}},i=lt(t,n());(e.provider==="stripe"||e.provider==="worldpay")&&(i.provider=e.provider);let s=i.provider,o=(a,l)=>{if(i.terminated&&!dt.has(a))return;let c={attemptId:t,phase:a,attemptSequence:i.nextSequence,elapsedMs:Math.max(0,n()-i.startedAt),provider:s};i.nextSequence+=1,l.reason!==void 0&&(c.reason=l.reason),l.evidenceBasis!==void 0&&(c.evidenceBasis=l.evidenceBasis),l.terminalSource!==void 0&&(c.terminalSource=l.terminalSource),l.providerOutcome!==void 0&&(c.providerOutcome=l.providerOutcome);try{r.emit(c,ct.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 fe(r){let e=null;try{e=ye(r?.attemptId)?r?.attemptId??null:null}catch{e=null}return{attemptId:e,record(t,n){try{r?.record(t,n)}catch{}},terminal(t,n){try{r?.terminal(t,n)}catch{}},reconcile(t){try{r?.reconcile(t)}catch{}}}}function X(r){if(typeof r!="string"||r.trim()==="")return"missing";try{let e=new URL(r);return e.protocol==="https:"||e.protocol==="http:"?"valid":"invalid"}catch{return"invalid"}}function xr(r){return r==="buyer_cancel"||r==="component_unmount"||r==="navigation"?r:"unspecified"}function ve(r){try{if(typeof window>"u"||typeof window.getComputedStyle!="function")return null;for(let e=r;e;e=e.parentElement){let t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||t.visibility==="collapse"||t.opacity==="0")return"hidden"}return"visible"}catch{return null}}function Ce(r,e){if(!e)return null;try{let t=r,n=String(t.effectiveDirective||t.violatedDirective||"").trim().split(/\s+/)[0],i=null;return n==="frame-src"&&(i="frame_src"),n==="child-src"&&(i="child_src"),!i||typeof t.blockedURI!="string"?null:new URL(t.blockedURI).origin===e?i:null}catch{return null}}function Te(r){try{return X(r)==="valid"?new URL(r).origin:null}catch{return null}}var yt="/v1/sdk-telemetry/events",H=16,Se=64,gt=1500,Re=1e3,ft=64,vt="00000000-0000-4000-8000-000000000000",Ct={technical_error:8,lifecycle:32,expected_outcome:32,performance:24},Tt=48;function R(){try{return globalThis.crypto.randomUUID()}catch{let r=new Uint8Array(16);try{globalThis.crypto.getRandomValues(r)}catch{for(let t=0;t<r.length;t+=1)r[t]=Math.floor(Math.random()*256)}r[6]=(r[6]??0)&15|64,r[8]=(r[8]??0)&63|128;let e=[...r].map(t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}}function bt(r){try{return new TextEncoder().encode(r).byteLength}catch{return r.length}}function _t(r){return JSON.stringify([r.code,r.failureCategory,r.reason,r.stage,r.provider,r.attempt,r.statusClass,r.requestCategory,r.paymentMethodCategory,r.walletType,r.operationOutcome,r.checkoutMode,r.layout,r.inAppBrowser,r.appFamily,r.popupCapability,r.presentationMode,r.terminalReason])}function _(){return globalThis.performance?.now()??0}var A=class{constructor(e){this.ingestionDisabled=!1;this.queue=[];this.sequence=0;this.threeDsChallengeCount=0;this.flushTimer=null;this.flushInFlight=null;this.reportedFailures=new Map;this.checkoutContext={};this.checkoutStartedAt=null;this.destroyed=!1;this.observers=new Set;this.pageExitHandler=()=>{this.drainQueue()};this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.flush()};this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0};this.endpoint=`${e.billingApiUrl.replace(/\/+$/,"")}${yt}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=R(),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(_e({...this.checkoutContext,...e,eventId:R(),sequence:this.sequence++}))}error(e){if(this.notify({...e,class:"technical_error"}),!this.canCollect())return;let t=be({...this.checkoutContext,...e,eventId:vt,sequence:0}),n=_t(t),i=this.now();this.pruneReportedFailures(i);let s=this.reportedFailures.get(n);if(s!==void 0&&i>=s&&i-s<Re){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt,inAppBrowser:e.inAppBrowser,appFamily:e.appFamily,popupCapability:e.popupCapability,presentationMode:e.presentationMode,terminalReason:e.terminalReason});return}this.rememberReportedFailure(n,i),this.enqueue(be({...this.checkoutContext,...e,eventId:R(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue(ut({...this.checkoutContext,...e,eventId:R(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue(ht({...this.checkoutContext,...e,eventId:R(),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 ge({now:()=>this.now(),newAttemptId:R,emit:(t,n)=>this.recordThreeDsChallenge(t,n)},e)}recordThreeDsChallenge(e,t){if(!this.canCollect()||this.threeDsChallengeCount>=Tt)return;let n=_e({...this.checkoutContext,...e,name:"three_ds.challenge",stage:"three_ds_handoff",eventId:R(),sequence:this.sequence++});if(!(this.queue.length>=Se)){if(this.threeDsChallengeCount+=1,this.queue.push(n),t){this.drainQueue();return}if(this.queue.length>=H){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,n]of this.reportedFailures)(e<n||e-n>=Re)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=ft;){let n=this.reportedFailures.keys().next();if(n.done)break;this.reportedFailures.delete(n.value)}this.reportedFailures.set(e,t)}setCheckoutContext(e){this.checkoutContext={checkoutMode:e.checkoutMode,layout:e.layout}}beginCheckout(e={}){return this.canCollect()?(this.drainQueue(),this.setCheckoutContext(e),this.sequence=0,this.threeDsChallengeCount=0,this.reportedFailures.clear(),this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0},this.checkoutStartedAt=this.now(),this.checkoutStartedAt):0}enqueue(e){if(this.canCollect()&&!(this.queue.length>=Se||this.eventCounts[e.class]>=Ct[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=H){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,H);return this.flushInFlight=this.sendBatch(e).finally(()=>{this.flushInFlight=null,this.queue.length>0&&this.scheduleFlush()}),this.flushInFlight}destroy(){this.destroyed||(this.drainQueue(),this.destroyed=!0,this.clearFlushTimer(),this.browserTransportAvailable&&(window.removeEventListener("pagehide",this.pageExitHandler),document.removeEventListener("visibilitychange",this.visibilityHandler)),this.queue.splice(0),this.reportedFailures.clear(),this.observers.clear())}disable(){this.merchantEnabled=!1,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}drainQueue(){if(!(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0))for(this.clearFlushTimer();this.queue.length>0;){let e=this.queue.splice(0,H);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=mt(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:R()});if(bt(t)>pt)return;let n=typeof AbortController>"u"?null:new AbortController,i=null;try{let s=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:n?.signal}).then(async l=>{if(l.status!==202)return null;let c=null;try{c=await l.json()}catch{}return c?.status==="disabled"?"disabled":null}).catch(()=>null),o=new Promise(l=>{i=setTimeout(()=>{n?.abort(),l(null)},gt)});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)}},Ae=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),Ee=globalThis;Ee[Ae]===void 0&&Object.defineProperty(Ee,Ae,{configurable:!0,enumerable:!1,writable:!1,value:r=>new A(r)});function Ot(r){return r==="on_session"||r==="off_session"}function xt(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.paymentMethodType=="string"&&typeof e.reason=="string"}function Ut(r){let e=r.vaultOutcome;if(!(!e||e.code!==At))return typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0}var qt="x-flopay-process-result-source",Lt="status",He=new WeakSet;function Nt(r,e){let t=new v(r,"api_error",{code:e,statusCode:500});return He.add(t),t}function Vt(r){return typeof r=="object"&&r!==null&&He.has(r)}function Oe(r){return r?.result==="DECLINE"||r?.result==="ERROR"}var Bt=50,M=new Map;function zt(r,e){return M.get(r)?.has(e)===!0}function Ht(r,e){let t=M.get(r)??new Set;if(t.add(e),M.delete(r),M.set(r,t),M.size>Bt){let n=M.keys().next().value;n!==void 0&&M.delete(n)}}function jt(r){let e=r?.threeDSecureActionResultTokenId;if(typeof e=="string"&&e.length>0)return e;if(r?.gateway==="paypal"&&r.type!=="paypal_setup_token"&&typeof r.id=="string"&&r.id.length>0)return r.id}var xe=0,Ue=500,j=15e3,qe=15e3,Kt=3e3,Gt=1e4,$t=1e4;function L(r){return typeof r=="object"&&r!==null}function k(r,e){return he(r?.[e])}function Le(r,e){return me(r?.[e])}function Yt(r,e){let t=r?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function ne(r,e){return e?new Promise((t,n)=>{let i=()=>{clearTimeout(s),n(e.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))},s=setTimeout(()=>{e.removeEventListener("abort",i),t()},r);e.aborted?i():e.addEventListener("abort",i,{once:!0})}):new Promise(t=>setTimeout(t,r))}function re(r){return r instanceof Error&&r.name==="AbortError"}function b(){return new v(Rt,"api_error",{code:"checkout_processing_timeout"})}async function S(r,e){let t=await r.json().catch(()=>null),n=L(t?.error)?t.error:null,i=Le(t,"message")??Le(n,"message")??e,s=k(t,"code")??k(t,"gatewayErrorCode")??k(n,"code")??`http_${r.status}`;return ze(new v(i,"api_error",{code:s,statusCode:r.status}),r)}async function Wt(r){if(r.status!==403)return!1;let e=await r.clone().json().catch(()=>null),t=L(e?.error)?e.error:null;return(k(e,"code")??k(t,"code"))==="verification_required"}function Jt(r){if(!(!L(r)||typeof r.required!="boolean"))return{required:r.required,provider:"turnstile"}}async function Qt(r){let e=r.status===400?await r.clone().json().catch(()=>null):null;return Et(r.status,e)}function Ne(r){return r===400||r===422}var G=2;async function K(r,e,t=G,n,i){let s;for(let o=0;;o++)try{return i?.(o),await fetch(r,e)}catch(a){if(e?.signal?.aborted||a instanceof Error&&a.name==="AbortError")throw a;if(s=a,o>=t)throw s;try{n?.(o+1)}catch{}await ne(150*2**o,e?.signal??void 0)}}var Xt=Symbol.for("@flopay/js.session-create.telemetry.v1");function Zt(r){return r[Xt]}function er(r){return"now"in r||"onFirstByte"in r||"onSessionCreateFailure"in r||"onRetry"in r}function je(r){let e=oe(r.firstName,r.lastName);return{userId:r.userId,firstName:e?null:r.firstName??null,lastName:e?null:r.lastName??null,email:r.email,country:r.country??null,gender:r.gender??null,city:r.city??null,state:r.state??null,zip:r.zip??null,addressLine1:r.addressLine1??null,addressLine2:r.addressLine2??null}}function Ke(r,e){e.checkoutMetadata!==void 0&&(r.checkoutMetadata=e.checkoutMetadata),e.tagsData&&(r.tagsData=e.tagsData),e.utmMetadata&&e.utmMetadata.length>0&&(r.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(r.avsCheck=e.avsCheck),e.checkoutType&&(r.checkoutType=e.checkoutType),e.checkoutLayout&&(r.checkoutLayout=e.checkoutLayout),e.avsConfig&&(r.avsConfig=e.avsConfig)}function Ve(r){if(typeof r!="string")return;let e=r.trim();return e.length>0?e:void 0}function tr(r){let e={};if(r.country&&(e.country=r.country),!oe(r.firstName,r.lastName)){let t=Ve(r.firstName),n=Ve(r.lastName);t&&(e.firstName=t),n&&(e.lastName=n)}return Object.keys(e).length>0?e:void 0}function rr(r,e){let t={clientId:r.clientId,checkoutVersion:E,successUrl:r.successUrl,cancelUrl:r.cancelUrl,currency:e,checkoutMode:"full",deferDataAttachment:!0};r.captureMethod==="manual"&&(t.captureMethod=r.captureMethod);let n=tr(r.account);return n&&(t.accountData=n),Ke(t,r),t}function Be(r,e,t){return{currency:e,products:t.map(n=>se(n,e)),couponCodes:r.couponCodes??[],accountData:je(r.account)}}function nr(r,e,t){return{currency:e,products:t.map(n=>se(n,e)),couponCodes:r.couponCodes??[]}}function ir(r){let e={},t=oe(r.firstName,r.lastName);for(let[n,i]of Object.entries(r)){if(t&&n.endsWith("Name")||typeof i!="string")continue;let s=i.trim();s&&(e[n]=s)}return{accountData:e}}var I=class I{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let n=er(t);this.telemetryHooks=n?t:void 0,this.directTelemetry=n||t.telemetry===!1?void 0:new A({billingApiUrl:this.baseUrl,sdkVersion:E})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,n,i,s="unknown"){let o=x(e,t);this.directTelemetry?.error({...o,...Vt(e)?{reason:"capture_failed"}:{},stage:n,requestCategory:i,paymentMethodCategory:s})}reportAccountSnapshotFailure(e,t){let n=x(e,"NETWORK_REQUEST_FAILED");if(t==="best_effort"&&n.errorCode==="REQUEST_TIMEOUT"){this.directTelemetry?.log({name:"operation.fallback",stage:"processing",requestCategory:"account_snapshot",statusClass:"timeout"});return}this.directTelemetry?.error({...n,stage:"processing",requestCategory:"account_snapshot",paymentMethodCategory:"unknown"})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??_()}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,n=!0,i){this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp(),o=s,a=0;this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let l={[U]:E};t&&(l["x-checkout-session-token"]=t);let c=!1;try{let d=await K(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:l,signal:i},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 m=Math.max(0,this.telemetryTimestamp()-o);try{this.telemetryHooks?.onFirstByte?.(m,a)}catch{}let u=`${Math.floor(d.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:u,attempt:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:m,durationMode:"machine",requestCategory:"session_read",statusClass:u,attempt:a}),!d.ok)throw await S(d,"Failed to get checkout session");let g=await d.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:u}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"session_read",statusClass:u}),{...g,data:this.mergeCachedDisplayData(g.data)}}catch(d){throw c&&q(d),n&&this.directTelemetry?.error({...x(d,"NETWORK_REQUEST_FAILED"),stage:"session_read",requestCategory:"session_read"}),d}}cacheSessionDisplayData(e,t,n){Q(e,t,n)}clearSessionDisplayData(e){ue(e)}async getVaultCapture(e,t){let n=`${this.baseUrl}\0${e}\0${t??""}`,i=I.activeVaultCaptureRequests.get(n);if(i!==void 0)return i;let s=this.requestVaultCapture(e,t);I.activeVaultCaptureRequests.set(n,s);try{return await s}finally{I.activeVaultCaptureRequests.get(n)===s&&I.activeVaultCaptureRequests.delete(n)}}async requestVaultCapture(e,t){let n=new AbortController,i=setTimeout(()=>n.abort(),$t);this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let o={"Content-Type":"application/json"};t&&(o["x-checkout-session-token"]=t);try{let a=await K(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:o,signal:n.signal},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 Wt(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=n.signal.aborted?new v("Timed out while loading the secure card form. Please try again.","api_error",{code:"vault_capture_timeout"}):a;throw this.reportDirectFailure(l,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),l}finally{clearTimeout(i)}}async getUnifiedCheckoutSession(e,t){let n=await this.getCheckoutSession(e,t);return this.normalizeCheckoutSessionResponse(n)}async getUnifiedCheckoutSessionForRecovery(e,t,n){let i=await this.fetchCheckoutSession(e,t,!1,n);return this.normalizeCheckoutSessionResponse(i)}normalizeCheckoutSessionResponse(e){try{let t=this.normalizeRawSession(e.data),n=e.vault;return n&&t.data.session&&(t.data.session.vault=this.toVaultBlock(n)),t}catch(t){throw q(t)}}async processPayment(e,t,n){this.beginDirectTelemetryCheckout(t.sessionId);let i=t.paymentMethodCategory??"unknown";if(!t.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:i}),new v("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment",paymentMethodCategory:i});let{nonce:o,paymentMethodCategory:a,...l}=t,c=jt(t.tokenizedData),d,m;try{d=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)}),m=d}catch(u){if(re(u))throw this.reportDirectFailure(u,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),u;d=await this.reconcileProcessPayment(t.sessionId,{...n,nonce:o,paymentMethodCategory:i,submittedIntentId:c})}if(!d.ok&&d.status!==202){let u=await Qt(d);return u?this.directTelemetry?.terminal({outcome:u,stage:"processing",requestCategory:"process_payment",statusClass:"4xx",paymentMethodCategory:i}):this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:w(d.status),failureCategory:d.status>=500?"server_error":void 0,paymentMethodCategory:i,...Dt(m)}),d}try{let u=await this.resolveProcessResponse(d,t.sessionId,{...n,nonce:o,paymentMethodCategory:i,submittedIntentId:c});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:w(u.status),paymentMethodCategory:i}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"process_payment",statusClass:w(u.status),paymentMethodCategory:i}),u}catch(u){throw u instanceof v&&u.code==="checkout_processing_timeout"||this.reportDirectFailure(u,"PAYMENT_PROCESSING_FAILED","processing","process_payment",i),u}}async patchAccountSnapshot(e,t,n,i){this.beginDirectTelemetryCheckout(e);let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let o=i?.timeoutMs??Gt,a=new AbortController,l=()=>a.abort();i?.signal&&(i.signal.aborted?a.abort():i.signal.addEventListener("abort",l,{once:!0}));let c=setTimeout(()=>a.abort(),o);try{let d;try{d=await K(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(n),signal:a.signal},G,m=>{this.telemetryHooks?.onRetry?.("account_snapshot",m),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:m})})}finally{clearTimeout(c),i?.signal?.removeEventListener("abort",l)}if(!d.ok)throw await S(d,"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(d){throw this.reportAccountSnapshotFailure(d,i?.telemetryMode??"blocking"),d}}async createSessionIntent(e,t,n,i){if(!t)throw new v("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=n,o=s.paymentMethodType,a=typeof o=="string"&&o.trim().toLowerCase()==="card",l=typeof o=="string"&&o.length>0&&!a&&(typeof s.paymentMethodId=="string"||s.paymentMethodId===null),c=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(s.intentKind==="payment"||s.intentKind==="setup"),d=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodId===null&&(s.paymentMethodType==="paypal"&&s.intentKind==="payment"||s.paymentMethodType===ee&&(s.intentKind==="payment"||s.intentKind==="setup"));if(!l||!c&&!d)throw new v("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let m=s.authorizationAttemptId;if(m!==void 0&&!Me(m))throw new v("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let u=Me(m)?m:Pt();this.beginDirectTelemetryCheckout(e);let g=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,[we]:i?.idempotencyKey||u},y=!1;try{let f=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:h,body:JSON.stringify({...n,authorizationAttemptId:u}),signal:i?.signal});if(!f.ok){y=!0;let W=await S(f,"Failed to create checkout intent"),nt=x(W,"PAYMENT_PROCESSING_FAILED");throw Ne(W.statusCode)?this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"intent_create",statusClass:"4xx"}):this.directTelemetry?.error({...nt,stage:"processing",requestCategory:"intent_create"}),W}let C=await f.json();if(f.status===202&&L(C)&&C.type==="checkout_processing")return y=!0,await this.settleProcessingSessionIntent(C,f,e,t,n);let T=C.data;if(!T||typeof T!="object")throw new v("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let p=T,ce=p.paymentMethodType,Ze=(p.paymentMethodCategory==="wallet"||p.paymentMethodCategory==="apm")&&typeof ce=="string"&&ce.trim().toLowerCase()!=="card"&&(typeof p.paymentMethodId=="string"||p.paymentMethodId===null)&&typeof p.providerObjectId=="string",et=p.provider==="stripe"&&(p.intentKind==="payment"||p.intentKind==="setup")&&typeof p.clientSecret=="string",tt=p.provider==="paypal"&&p.paymentMethodCategory==="wallet"&&p.paymentMethodId===null&&(p.paymentMethodType==="paypal"&&p.intentKind==="payment"&&(p.providerObjectType==="order"||p.providerObjectType==="subscription")||p.paymentMethodType===ee&&p.intentKind==="payment"&&p.providerObjectType==="order"||p.paymentMethodType===ee&&p.intentKind==="setup"&&p.providerObjectType==="setup_token")&&p.clientSecret===null,rt=p.provider===n.provider&&p.paymentMethodCategory===n.paymentMethodCategory&&p.paymentMethodType===n.paymentMethodType&&p.paymentMethodId===n.paymentMethodId&&p.intentKind===n.intentKind;if(!Ze||!et&&!tt||!rt)throw new v("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:w(f.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-g),durationMode:"machine",requestCategory:"intent_create",statusClass:w(f.status)}),p}catch(f){throw y||this.reportDirectFailure(f,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),f}}async settleProcessingSessionIntent(e,t,n,i,s){let o=this.toCheckoutProcessingPending(e,t,n);try{return{settled:!0,response:await this.resolveCheckoutProcessing(o,n,{nonce:i,paymentMethodCategory:s.provider==="paypal"?"paypal":s.paymentMethodCategory})}}catch(a){throw a instanceof v&&a.code==="checkout_processing_timeout"?new v(a.message,a.type,{code:a.code,statusCode:202,sessionId:o.sessionId,cause:a}):a}}async reportSessionIntentDecline(e,t,n,i){if(!t)throw new v("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=n,o=s.providerDeclineReason,a=s.paymentMethodType,l=s.providerIntentId,c=typeof o=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(o)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(o),d=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&c,m=s.provider==="stripe"&&(s.paymentMethodCategory==="wallet"||s.paymentMethodCategory==="apm")&&(l===void 0||typeof l=="string"&&/^pi_[a-z0-9_]{1,252}$/i.test(l)),u=s.provider==="paypal"&&s.paymentMethodCategory==="wallet"&&s.paymentMethodType==="paypal"&&l===void 0;if(!d||!m&&!u)throw new v("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let g=u?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:o}:{provider:"stripe",paymentMethodCategory:s.paymentMethodCategory,paymentMethodType:s.paymentMethodType,providerDeclineReason:o,...typeof l=="string"?{providerIntentId:l}:{}},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(g),signal:i?.signal});if(!h.ok)throw await S(h,"Failed to report checkout decline")}async resolvePaymentMethodLayout(e,t,n,i){if(!t)throw new v("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(n),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 It(o?.data)}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let n=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let i=t?.page??1,s=t?.limit??1,o=new URLSearchParams({email:e,page:String(i),limit:String(s),sortField:"createdAt",sortDirection:"DESC"});try{let a=await fetch(`${this.baseUrl}/v1/payments?${o.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!a.ok)throw ze(new v("Failed to fetch payments","api_error",{statusCode:a.status}),a);let l=await a.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-n),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),l}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){if(Mt(e)){let s=e.account.email?.trim();if(s&&!Ie(s))throw new v("Buyer email must be valid when supplied.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"});return(await this.createDetachedSession(e)).claimed}this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),n=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,n.signal,i);return this.adoptDirectTelemetryCheckout(s.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_create",requestCategory:"session_create",statusClass:i.statusClass}),this.directTelemetry?.performance({stage:"session_create",durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:"session_create",statusClass:i.statusClass,attempt:i.attempt}),s}catch(s){throw this.reportSessionCreateFailure(s,t,i),s}finally{n.clear()}}async createAndFetchSessionRequest(e,t,n){let i=e.products??Z(e.items,e.subscriptions);ke({captureMethod:e.captureMethod,products:i});let s=te(e.currency,e.items,e.subscriptions,i);if(!s)throw new v("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(c=>se(c,s)),accountData:je(e.account),couponCodes:e.couponCodes??[]};e.captureMethod==="manual"&&(o.captureMethod=e.captureMethod),e.tokenizedData&&(o.tokenizedData=e.tokenizedData),Ke(o,e);let a=await this.postCheckoutSessionCreate(o,e,t,n),l=!1;try{let c=await a.json();if(c.data&&"gateways"in c.data){this.autoCacheDisplayData(c.data.uuid,e);let u=this.mergeCachedDisplayData(c.data),g=this.normalizeRawSession(u);return c.vault&&g.data.session&&(g.data.session.vault=this.toVaultBlock(c.vault)),{...g,autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}let d=c.data?.uuid;if(!d)throw new v("No session ID returned","api_error",{code:"InvalidCheckoutSessionResponse"});return this.autoCacheDisplayData(d,e),this.adoptDirectTelemetryCheckout(d),l=!0,{...await this.getUnifiedCheckoutSession(d),autoProcessingError:c.autoProcessingError,autoProcessingAttempted:c.autoProcessingAttempted,autoProcessingPending:c.autoProcessingPending}}catch(c){throw l?c:q(c)}}async postCheckoutSessionCreate(e,t,n,i){let s={"Content-Type":"application/json",[U]:E},o=Ft(t.idempotencyKey);o&&(s[we]=o),t.checkoutMode==="auto"&&(s[kt]=St);let a,l=!1,c=Zt(t),d=(u,g,h)=>{l||(l=!0,this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:h,attempt:u}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:Math.max(0,this.telemetryTimestamp()-g),durationMode:"machine",requestCategory:"session_create",statusClass:h,attempt:u}))},m=u=>{try{this.telemetryHooks?.onRetry?.("session_create",u),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:u})}catch{}};for(let u=0;u<3;u++){i.attempt=u;let g=this.telemetryTimestamp();try{c?.onAttempt?.(u)}catch{}try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:s,body:JSON.stringify(e),signal:n})}catch(f){if(i.statusClass=n.aborted||f instanceof Error&&f.name==="AbortError"?"timeout":"network_error",n.aborted||f instanceof Error&&f.name==="AbortError"||u>=2)throw f;let C=u+1;m(C),await z(u,n);continue}let h=w(a.status);if(i.statusClass=h,a.status===204)throw d(u,g,h),new v("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(a.ok){d(u,g,h);break}let y=await S(a,"Failed to create checkout session");if(y.code===wt&&u<2){m(u+1),await z(u,n);continue}throw d(u,g,h),y}if(!a)throw new TypeError("Checkout-session creation exhausted its retry budget.");return a}async createDetachedSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp(),n=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??Z(e.items,e.subscriptions);try{ke({captureMethod:e.captureMethod,products:s})}catch(C){throw n.clear(),this.reportSessionCreateFailure(C,t,i),C}let o=te(e.currency,e.items,e.subscriptions,s);if(!o)throw n.clear(),this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),new v("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{Be(e,o,s)}catch(C){throw n.clear(),this.reportSessionCreateFailure(C,t,i),C}let a,l,c=!1;try{let C=await this.postCheckoutSessionCreate(rr(e,o),e,n.signal,i);if(c=!0,l=await C.json(),!l.data||!("gateways"in l.data))throw new v("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(C){throw n.clear(),c&&q(C),this.reportSessionCreateFailure(C,t,i),C}let d=a.data.session?.id??l.data.uuid??"",m=a.data.session?.clientSecret??l.data.nonce??"";if(!d||!m){n.clear();let C=new v("Checkout session shell was created without a session id or nonce.","api_error",{code:"InvalidCheckoutSessionResponse"});throw this.reportSessionCreateFailure(C,t,i),C}n.clear(),this.adoptDirectTelemetryCheckout(d),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 u=!e.account.email?.trim(),g=P(e.timeoutMs??12e3),h=this.claimCheckoutSession(d,m,u?nr(e,o,s):Be(e,o,s),{params:e,startedAt:t,deadline:g,createAttempt:i.attempt}),y=u?void 0:h,f=(C={})=>{if(y!==void 0)return y;let T={...e,account:{...e.account,...C,email:C.email?.trim()||e.account.email?.trim()}};return Ie(T.account.email)?(y=h.then(()=>{let p=this.telemetryTimestamp();return this.claimCheckoutSession(d,m,ir(T.account),{params:T,startedAt:p,deadline:P(e.timeoutMs??12e3),createAttempt:0})}),y.catch(()=>{}),y):Promise.reject(new v("A valid buyer email is required before claiming checkout.","validation_error",{code:"BuyerEmailCollectionRequired",param:"account.email"}))};return h.catch(()=>{}),{shell:a,sessionId:d,nonce:m,claimed:h,claim:f}}async claimCheckoutSession(e,t,n,i){let s=i?.startedAt??this.telemetryTimestamp(),o=this.telemetryTimestamp(),a=i?.deadline??P(12e3),l=JSON.stringify(n),c="unknown",d=0,m=!1;this.directTelemetry?.log({name:"session.claim.started",stage:"session_claim",requestCategory:"session_claim"});try{let u;for(d=0;d<3;d++){try{u=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/claim`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t,[U]:E},body:l,signal:a.signal})}catch(y){let f=a.signal.aborted||y instanceof Error&&y.name==="AbortError";if(c=f?"timeout":"network_error",f||d>=2)throw y;try{this.telemetryHooks?.onRetry?.("session_claim",d+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_claim",requestCategory:"session_claim",attempt:d+1})}catch{}await z(d,a.signal);continue}if(c=w(u.status),u.ok)break;throw await S(u,"Failed to attach checkout session data")}if(!u)throw new TypeError("Checkout-session claim exhausted its retry budget.");m=!0;let g=await u.json();if(!g.data?.gateways)throw new v("The billing API returned no checkout session with gateways after claiming it.","api_error",{code:"InvalidCheckoutSessionResponse"});i?.params&&this.autoCacheDisplayData(g.data.uuid??e,i.params);let h=this.normalizeRawSession(this.mergeCachedDisplayData(g.data));return g.vault&&h.data.session&&(h.data.session.vault=this.toVaultBlock(g.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:d}),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??d}),h}catch(u){throw m&&q(u),this.reportSessionCreateFailure(u,o,{attempt:d,statusClass:c},"session_claim"),u}finally{a.clear()}}reportSessionCreateFailure(e,t,n,i="session_create"){if(!(e instanceof v&&e.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(e)}catch{}let s=x(e,"CHECKOUT_SESSION_CREATE_FAILED");if(this.directTelemetry?.performance({stage:i,durationMs:Math.max(0,this.telemetryTimestamp()-t),durationMode:"machine",requestCategory:i==="session_claim"?"session_claim":"session_create",statusClass:s.statusClass,attempt:n.attempt}),e instanceof v&&e.type==="validation_error"||e instanceof v&&Ne(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 v&&e.code==="session_auto_completed"||this.directTelemetry?.error({...s,stage:i,requestCategory:i==="session_claim"?"session_claim":"session_create"})}reportThreeDsAbandoned(e){this.beginDirectTelemetryCheckout(e),this.directTelemetry?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",paymentMethodCategory:"saved"})}beginThreeDsChallenge(e,t={}){try{return this.directTelemetry?(this.beginDirectTelemetryCheckout(e),this.directTelemetry.beginThreeDsChallenge(t)):void 0}catch{return}}async waitForCheckoutSessionCompletion(e,t){this.beginDirectTelemetryCheckout(e);let n=this.telemetryTimestamp(),i=t?.paymentMethodCategory??"saved";this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:i});let s=t?.timeoutMs??j,o=Date.now()+s,a=new AbortController,l=!1,c,d=setTimeout(()=>{c=setTimeout(()=>{l=!0,a.abort()},qe)},s),m=()=>a.abort(t?.signal?.reason);t?.signal?.aborted?m():t?.signal?.addEventListener("abort",m,{once:!0});let u=this.clampRetryAfterMs(t?.initialDelayMs??xe),g=0;try{if(t?.statusUrl){let h=await this.waitForCheckoutStatus(e,{initialDelayMs:u,timeoutMs:s,nonce:t.nonce,statusUrl:t.statusUrl,pollAfterAction:t.continueAfterActionRequired,signal:a.signal});if(h){let y=await this.resolveCheckoutSessionStatus(e,h,t.nonce,a.signal,()=>l);return this.reportRecoveryCompleted(n,i,t.challengeAttemptId),y}}for(;;){let h=o-Date.now();if(h<=0)throw b();if(u>0){try{g+=1,this.telemetryHooks?.onRetry?.("session_read",g),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:i,attempt:g})}catch{}if(await ne(Math.min(u,h),a.signal),Date.now()>=o)throw b()}let y=await this.getUnifiedCheckoutSessionForRecovery(e,t?.nonce,a.signal),f=y.data.session?.status;if(f==="authorized"||f==="complete"||f==="expired")return this.reportRecoveryCompleted(n,i,t?.challengeAttemptId),y;if(Date.now()>=o)throw b();u=this.clampRetryAfterMs(Math.max(u*2,Ue))}}catch(h){let y=l&&re(h)?b():h;throw this.reportDirectFailure(y,"RECOVERY_FAILED","recovery","session_read",i),y}finally{clearTimeout(d),clearTimeout(c),t?.signal?.removeEventListener("abort",m)}}reportRecoveryCompleted(e,t,n){let i={stage:"recovery",requestCategory:"session_read",paymentMethodCategory:t};if(this.directTelemetry?.log({name:"operation.recovery.completed",...i}),n)try{this.directTelemetry?.beginThreeDsChallenge({attemptId:n}).record("recovery_read_completed",{evidenceBasis:"server_status"})}catch{}this.directTelemetry?.performance({...i,durationMs:Math.max(0,this.telemetryTimestamp()-e),durationMode:"machine"})}async resolveCheckoutSessionStatus(e,t,n,i,s){let o=t.latestTransactionAttempt;if(this.rememberReportedFailure(e,t),o?.result==="DECLINE"){let c=o.code===De;throw new v(c?Fe:"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 Nt("Payment could not be completed. Please try again.",o?.code??"payment_processing_error");let a;try{a=await this.getUnifiedCheckoutSessionForRecovery(e,n,i)}catch(c){if(!s?.()||!re(c))throw c;a={providers:[],mode:"tokenize",data:{},raw:t}}let l=a.data.session;return l&&o?.result==="SUCCESS"?{...a,data:{...a.data,session:{...l,status:"complete"}}}:l&&o?.result==="AUTHORIZED"?{...a,data:{...a.data,session:{...l,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:l&&t.status==="completed"?{...a,data:{...a.data,session:{...l,status:"complete"}}}:l&&t.status==="authorized"?{...a,data:{...a.data,session:{...l,status:"authorized",paymentId:t.paymentId??void 0,authorizationExpiresAt:t.authorizationExpiresAt??void 0}}}:l&&t.status==="expired"?{...a,data:{...a.data,session:{...l,status:"expired"}}}:o?.result!=="ACTION_REQUIRED"?a:o.gateway==="paypal"&&o.providerIntentId?{...a,autoProcessingError:{type:"paypal_direct_required",message:"PayPal authorization required",orderId:o.providerIntentId,checkoutMethod:"paypal"}}:o.nextActionRedirectUrl?{...a,autoProcessingError:{type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:o.nextActionRedirectUrl}}:a}async waitForCheckoutStatus(e,t){let n=t.timeoutMs??j,i=Date.now()+n,s=this.clampRetryAfterMs(t.initialDelayMs);for(;;){let o=i-Date.now();if(o<=0||s>0&&(await ne(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,c,d=t.signal?new Promise((T,p)=>{c=p}):null,m=()=>{l.abort(t.signal?.reason),c?.(t.signal?.reason??Object.assign(new Error("The operation was aborted."),{name:"AbortError"}))};t.signal?.aborted?m():t.signal?.addEventListener("abort",m,{once:!0});let u,g=t.signal?null:new Promise((T,p)=>{u=setTimeout(()=>{p(b()),l.abort()},a+qe)}),h;try{let T=this.fetchCheckoutStatus(e,t.nonce,t.statusUrl,l.signal);h=await Promise.race([T,g,d].filter(p=>p!==null))}finally{u!==void 0&&clearTimeout(u),t.signal?.removeEventListener("abort",m)}if(!h)return null;let y=Oe(h.latestTransactionAttempt)&&!this.isOwnFailedAttempt(e,h,t.submittedIntentId);if(h.status==="completed"||h.status==="authorized"||h.status==="expired"||h.status==="voided")return y?{...h,latestTransactionAttempt:null}:h;let f=h.latestTransactionAttempt?.result,C=t.pollAfterAction===!0&&f==="ACTION_REQUIRED";if(!y&&f!==void 0&&f!=="PENDING"&&!C)return h;s=this.clampRetryAfterMs(Math.max(s*2,Ue))}}isOwnFailedAttempt(e,t,n){let i=t.latestTransactionAttempt?.providerIntentId??null;return n!==void 0?i===n:i===null?!0:!zt(t.uuid||e,i)}rememberReportedFailure(e,t){let n=t.latestTransactionAttempt;!Oe(n)||!n.providerIntentId||Ht(t.uuid||e,n.providerIntentId)}async fetchCheckoutStatus(e,t,n,i){let s=`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/status`,o=s;if(n)try{let d=new URL(n,`${this.baseUrl}/`),m=new URL(s);d.origin===m.origin&&(o=d.toString())}catch{}let a={[U]:E};t&&(a["x-checkout-session-token"]=t);let l=await K(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 c=await l.json();return L(c.data)&&"latestTransactionAttempt"in c.data?c.data:null}normalizeRawSession(e){let t=e.gateways??{},n=[],i={session:this.toCheckoutSession(e)},s=t.stripe;if(s?.publishableKey){n.push("stripe");let l=[e.stripeClientSecret,s.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);i.stripe={clientSecret:l??"",publishableKey:s.publishableKey??void 0,paypalPublishableKey:s.paypalPublishableKey??void 0,environment:s.environment,enabledPaymentMethods:Array.isArray(s.enabledPaymentMethods)?s.enabledPaymentMethods.filter(c=>typeof c=="string"):void 0}}let o=t.paypal;return o?.publishableKey&&(n.push("paypal"),i.paypal={publishableKey:o.publishableKey,environment:o.environment,providerObjectType:o.providerObjectType,approvalPresentation:o.approvalPresentation}),{providers:n,mode:"tokenize",...e.checkoutMetadata===void 0?{}:{checkoutMetadata:e.checkoutMetadata},data:i,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],n=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),i=t.reduce((c,d)=>c+(d.overrideAmount??d.totalAmount??0),0),s=n?e.totalAmount:i,o=Math.round(s*100),a=e.currency??t[0]?.currency??"USD",l="payment";return e.checkoutMode==="setup"?l="setup":t.some(c=>c.type==="subscription")&&(l="subscription"),{id:e.uuid,clientSecret:e.nonce,mode:l,status:this.toCheckoutSessionStatus(e.status),amount:o,currency:a,captureMethod:e.captureMethod,paymentId:e.paymentId,authorizationExpiresAt:e.authorizationExpiresAt,failureOutcome:Pe(e.outcome)??Pe(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}:{},...Ot(e.futureUse)?{futureUse:e.futureUse}:{},...Array.isArray(e.futureUseUnsupported)?{futureUseUnsupported:e.futureUseUnsupported.filter(xt)}:{},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=Jt(e.verification);return{html:typeof e.html=="string"?e.html:void 0,url:typeof e.url=="string"?e.url:void 0,messageToken:typeof e.messageToken=="string"?e.messageToken:void 0,expectedOrigin:typeof e.expectedOrigin=="string"?e.expectedOrigin:void 0,...t?{verification:t}:{}}}toCheckoutSessionStatus(e){return e==="completed"?"complete":e==="authorized"?"authorized":e==="expired"?"expired":"open"}async resolveProcessResponse(e,t,n){if(e.status!==202)return e;let i=await e.json().catch(()=>null),s=this.toCheckoutProcessingPending(i,e,t);return this.resolveCheckoutProcessing(s,t,n)}async resolveCheckoutProcessing(e,t,n){let i=n?.pollTimeoutMs??j,s=Date.now()+i;if(e.statusUrl){let a=await this.waitForCheckoutStatus(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:i,nonce:n?.nonce,statusUrl:e.statusUrl,submittedIntentId:n?.submittedIntentId});if(a)return this.toProcessResponseFromStatus(a,t,n?.nonce)}let o=await this.waitForCheckoutSessionCompletion(e.sessionId,{initialDelayMs:e.retryAfterMs,timeoutMs:s-Date.now(),nonce:n?.nonce,paymentMethodCategory:n?.paymentMethodCategory});return this.toProcessResponseFromSession(o,t)}async toProcessResponseFromStatus(e,t,n){let i=e.latestTransactionAttempt?.result,s={[qt]:Lt},o={"Content-Type":"application/json",...s};if(e.status==="completed"||i==="SUCCESS")return new Response(null,{status:204,statusText:"No Content",headers:s});if(e.status==="authorized"||i==="AUTHORIZED")return new Response(JSON.stringify({status:"authorized",paymentId:e.paymentId??void 0,sessionId:e.uuid||t,authorizationExpiresAt:e.authorizationExpiresAt??void 0}),{status:200,headers:o});if(e.status==="expired"){let a=await this.resolveCheckoutSessionStatus(t,e,n);return this.toProcessResponseFromSession(a,t)}if(this.rememberReportedFailure(t,e),i==="DECLINE"){let a=e.latestTransactionAttempt,l=a?.code===De,c=a?.declineReason??void 0;return new Response(JSON.stringify({type:c??"authorization_declined",message:l?Fe:"Payment was declined. Please choose another payment method.",code:a?.code??c??"authorization_declined",...c?{declineCode:c}:{}}),{status:400,headers:o})}if(i==="ACTION_REQUIRED"&&e.latestTransactionAttempt?.gateway==="paypal"&&e.latestTransactionAttempt.providerIntentId)return new Response(JSON.stringify({type:"paypal_direct_required",message:"PayPal authorization required",orderId:e.latestTransactionAttempt.providerIntentId}),{status:400,headers:o});if(i==="ACTION_REQUIRED"&&e.latestTransactionAttempt?.nextActionRedirectUrl)return new Response(JSON.stringify({type:"3ds_required",message:"Additional authentication is required.",nextActionRedirectUrl:e.latestTransactionAttempt.nextActionRedirectUrl}),{status:400,headers:o});if(i==="ERROR"||e.status==="voided")return new Response(JSON.stringify({type:"unknown",code:e.latestTransactionAttempt?.code??"payment_processing_error",message:Ut(e)??"Payment could not be completed. Please try again."}),{status:500,headers:o});throw b()}async reconcileProcessPayment(e,t){let n=t?.pollTimeoutMs??j,i=Date.now()+n,s=null;try{s=await this.waitForCheckoutStatus(e,{initialDelayMs:0,timeoutMs:n,nonce:t?.nonce,submittedIntentId:t?.submittedIntentId})}catch(l){if(this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","session_read",t?.paymentMethodCategory??"saved"),l instanceof v&&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 n=e.data.session;return new Response(JSON.stringify({status:"authorized",paymentId:n.paymentId,sessionId:n.id||t,authorizationExpiresAt:n.authorizationExpiresAt}),{status:200,headers:{"Content-Type":"application/json"}})}if(e.data.session?.status==="expired"){let n=e.data.session.failureOutcome==="authorization_expired"||e.data.session.captureMethod==="manual";throw new v(n?"Authorization has expired.":"Checkout session has expired.","api_error",{code:n?"authorization_expired":"checkout_session_expired"})}throw b()}toCheckoutProcessingPending(e,t,n){let i=t.headers.get("Retry-After"),s=i===null||i.trim()===""?void 0:Number(i),o=s!==void 0&&Number.isFinite(s)?s*1e3:void 0;return{type:"checkout_processing",sessionId:k(e,"sessionId")??n,retryAfterMs:this.clampRetryAfterMs(Yt(e,"retryAfterMs")??o??xe),statusUrl:k(e,"statusUrl"),sessionUrl:k(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,Kt))}autoCacheDisplayData(e,t){if(!e)return;let n=t.products??Z(t.items,t.subscriptions);if(n.length===0&&!t.currency)return;let i=t.products!==void 0,s=te(t.currency,i?void 0:t.items,i?void 0:t.subscriptions,n);Q(e,{currency:s??void 0,products:n.map(o=>({code:o.code??o.providerItemId??o.providerPlanId,type:o.type,name:o.name??o.itemName??o.providerItemName??o.subscriptionName??o.providerPlanName??null,totalAmount:o.totalAmount,overrideAmount:o.overrideAmount,currency:o.currency??s??void 0}))})}mergeCachedDisplayData(e){let t=de(e.uuid),n=new Map,i=o=>o?`code:${o}`:void 0;for(let o of t?.products??[]){let a=i(o.code);a&&n.set(a,o)}let s=(e.products??[]).map(o=>{let a=i(o.code),l=a?n.get(a):void 0;return{...o,name:o.name??l?.name??null,totalAmount:o.totalAmount??l?.totalAmount,overrideAmount:o.overrideAmount??l?.overrideAmount,currency:o.currency??l?.currency}});return{...e,currency:e.currency??t?.currency,products:s}}};I.activeVaultCaptureRequests=new Map;var ie=I;function Kr(r,e){let t=ie;return new t(r,e)}import{buildTelemetryErrorEvent as ar,buildTelemetryLogEvent as lr,buildTelemetryTerminalEvent as Je,FloPayError as $e,resolveBillingApiUrl as Ye,SDK_VERSION as We,THREE_DS_CHALLENGE_WINDOW_MS as cr}from"@flopay/shared";import{invokeMerchantCallback as sr,resolveCardFieldsTimeoutMs as or}from"@flopay/shared";function Ge(r){if(!r)return null;try{let e=new URL(r,window.location.href);return e.origin==="null"?null:e.origin}catch{return null}}var $=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=or(this.options.timeoutMs);this.timer=setTimeout(()=>{this.timer=null,this.reportFailure("timeout",e)},e)}watch(e){if(!this.active)return;this.detachWatchers();let t=new Set,n=[];for(let s of Array.from(e.querySelectorAll("script[src], iframe[src]"))){let o=Ge(s.getAttribute("src"));if(o&&t.add(o),s.tagName==="SCRIPT"){let a=()=>this.fail("load_error");s.addEventListener("error",a),n.push(()=>s.removeEventListener("error",a))}}let i=s=>{let o=Ge(s.blockedURI);o&&t.has(o)&&this.fail("blocked")};document.addEventListener("securitypolicyviolation",i),n.push(()=>document.removeEventListener("securitypolicyviolation",i)),this.detach=()=>{for(let s of n)s()}}ready(){!this.active||this.readyReported||(this.readyReported=!0,this.clearTimer(),this.detachWatchers(),this.dispatch({type:"card_fields_ready",elapsedMs:this.elapsed()}))}fail(e){this.reportFailure(e,0)}reportFailure(e,t){!this.active||this.readyReported||this.failureReported||(this.failureReported=!0,this.clearTimer(),this.dispatch({type:"card_fields_failed",reason:e,elapsedMs:Math.max(t,this.elapsed())}))}end(){this.active=!1,this.clearTimer(),this.detachWatchers()}elapsed(){return Math.max(0,Math.round(this.options.now()-this.startedAt))}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}detachWatchers(){this.detach?.(),this.detach=null}dispatch(e){try{this.options.report?.(e)}catch{}for(let t of Array.from(this.handlers))sr(()=>t(e))}};var dr=4,Y="flopay-vault",ur=3e4,hr=cr+ur,mr="Card authentication timed out.",Qe={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 pr(r){return r.class==="lifecycle"?r.name:r.class==="technical_error"?r.code:r.class==="expected_outcome"?r.outcome:"sdk.performance"}function D(r){let e={class:r.class,stage:r.stage};"code"in r&&(e.code=r.code),"provider"in r&&r.provider&&(e.provider=r.provider),"paymentMethodCategory"in r&&r.paymentMethodCategory&&(e.paymentMethodCategory=r.paymentMethodCategory),"outcome"in r&&(e.outcome=r.outcome),"durationMs"in r&&r.durationMs!==void 0&&(e.durationMs=r.durationMs),"durationMode"in r&&r.durationMode&&(e.durationMode=r.durationMode);try{globalThis.Sentry?.addBreadcrumb?.({category:"flopay.telemetry",level:r.class==="technical_error"?"error":"info",message:pr(r),data:e})}catch{}}function N(r,e){return lr({eventId:"11111111-1111-4111-8111-111111111111",name:r,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}var yr=new Set(["authorization_declined","authentication_required","authorization_expired","capture_failed"]);function gr(r){return typeof r=="string"&&yr.has(r)?r:"unknown"}var fr=new Set(["verification_failed","verification_expired"]);function vr(r){return r==null?!0:typeof r=="string"&&fr.has(r)}var Cr="vault_mount";function Tr(r){return r.failureStage===Cr}function ae(r,e){return r&&!Tr(e)?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit",failureCategory:"provider_runtime",reason:gr(e.failureOutcome)}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",failureCategory:"provider_runtime"}}function Xe(r,e,t="checkout"){return t==="card_setup"?r.type==="decline"?"card_setup_declined":"card_setup_succeeded":r.type==="decline"?"payment_declined":r.outcome==="authorized"||e==="manual"?"payment_authorized":"payment_succeeded"}function br(r,e,t,n="checkout"){let{type:i}=r;if(i==="complete"||i==="decline")return Je({eventId:"22222222-2222-4222-8222-222222222222",outcome:Xe(r,t,n),sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(i==="error"){let a=ae(e,r);return ar({eventId:"33333333-3333-4333-8333-333333333333",...a,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[s,o]=Qe[i];return N(s,o)}function _r(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Y&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function Sr(r){if(typeof r!="object"||r===null)return;let e=r;if(typeof e.code!="string"||e.code.trim()==="")return;let t=typeof e.message=="string"&&e.message.trim()!==""?e.message:void 0;return t?{code:e.code,message:t}:{code:e.code}}function Rr(r){if(typeof r!="object"||r===null)return;let e=r,t=e.status;if(!(typeof e.id!="string"||e.id.trim()===""||typeof e.brand!="string"||e.brand.trim()===""||typeof e.lastFour!="string"||!/^\d{4}$/.test(e.lastFour)||typeof e.expiryMonth!="number"||!Number.isInteger(e.expiryMonth)||e.expiryMonth<1||e.expiryMonth>12||typeof e.expiryYear!="number"||!Number.isInteger(e.expiryYear)||e.expiryYear<1970||e.expiryYear>9999||t!=="pending"&&t!=="active"&&t!=="deleted"))return{id:e.id,brand:e.brand,lastFour:e.lastFour,expiryMonth:e.expiryMonth,expiryYear:e.expiryYear,status:t}}function Ar(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Y&&e.type==="validation"&&Array.isArray(e.messages)}function Er(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Y&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}function kr(r){if(typeof r!="object"||r===null)return!1;let e=r;return e.source===Y&&e.type==="fields_interactive"}function wr(r){let e=r.capabilities;return Array.isArray(e)&&e.includes("fields_interactive")}var Mr=["number","expiry","cvv","name"];function Ir(r){if(r===null||typeof r!="object")return;let e=r,t={};for(let n of Mr){let i=e[n];typeof i=="string"&&(t[n]=i)}return t}var le=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.messageToken=null;this.expectedOrigin=null;this.theme=void 0;this.submitGateBlocked=!1;this.cardFieldOrder=null;this.cardAutoFocus=!0;this.cardBrandIcons=!1;this.submitLabel=void 0;this.cardFieldPlaceholders=void 0;this.mountStartedAt=0;this.vaultReadyReported=!1;this.verificationRequired=!1;this.submissionStarted=!1;this.submissionStartedAt=null;this.listeners=new Map;this.config=e,this.cardFields=new $({timeoutMs:e.cardFieldsTimeoutMs,now:()=>this.telemetryReporter?.now?.()??_(),report:n=>this.reportCardFields(n)}),this.ownsTelemetryReporter=!t&&e.telemetry!==!1,this.telemetryReporter=t?.reporter??(this.ownsTelemetryReporter?new A({billingApiUrl:Ye(e.billingApiUrl),sdkVersion:We}):void 0)}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new A({billingApiUrl:Ye(this.config.billingApiUrl),sdkVersion:We}));let n=this.telemetryReporter;if(this.config.operation==="card_setup"&&n&&this.setupTelemetryReporter!==n){this.setupTelemetryReporter=n;try{n.beginCheckout({checkoutMode:"setup"})}catch{}}if(this.mountStartedAt=this.telemetryReporter?.now?.()??_(),this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,this.cardFields.begin(),typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),new $e("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 $e("No vault capture widget HTML was provided to mount the secure card form.","api_error",{code:"card_capture_no_widget_html"});this.container=e,this.verificationRequired=t.verificationRequired===!0,this.messageToken=t.messageToken??null,this.expectedOrigin=t.expectedOrigin??this.config.expectedOrigin??null,this.theme=t.theme,t.submitLabel!==void 0&&(this.submitLabel=t.submitLabel);try{this.attachMessageListener(),this.injectWidget(e,t.html),this.cardFields.watch(e)}catch(i){throw this.reportVaultLoadFailure(),this.failCardFieldsMount(),i}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postCardBrandIcons(),this.postCardFieldPlaceholders(),this.postSubmitLabel(),D(N("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})}reportVaultLoadFailure(){this.telemetryReporter?.error({errorCode:"VAULT_LOAD_FAILED",failureCategory:"provider_runtime",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})}on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>{this.listeners.get(e)?.delete(t)}}onCardFields(e){return this.cardFields.subscribe(e)}failCardFieldsMount(){this.cardFields.fail("other"),this.cardFields.end()}reportCardFields(e){let t=e.type==="card_fields_ready",n=this.config.sessionId;this.telemetryReporter?.log({name:t?"vault.fields.ready":"vault.fields.failed",stage:t?"vault_ready":"vault_mount",provider:"pcivault",paymentMethodCategory:"card",elapsedMs:e.elapsedMs,...e.type==="card_fields_failed"?{loadFailureReason:e.reason}:{},...n?{checkoutSessionId:n}:{}})}unmount(){if(this.cardFields.end(),this.actionChallenge){let{telemetry:e}=this.actionChallenge;e.record("abort_observed",{reason:"component_unmount",evidenceBasis:"signal_reason"}),e.terminal("abort",{reason:"component_unmount",evidenceBasis:"signal_reason"})}this.lastChallengeTelemetry=null,this.hideActionRequiredOverlay(),this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.container&&(this.container.replaceChildren(),this.container=null),this.messageToken=null,this.expectedOrigin=null,this.ownsTelemetryReporter&&(this.telemetryReporter?.destroy(),this.telemetryReporter=void 0)}injectWidget(e,t){e.innerHTML=t;let n=Array.from(e.querySelectorAll("script"));for(let i of n){let s=document.createElement("script");for(let o of Array.from(i.attributes))s.setAttribute(o.name,o.value);s.text=i.text,i.replaceWith(s)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let n=t.data;if(Er(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;this.applyHeight(n.height);return}if(Ar(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let c=n.messages.filter(d=>typeof d=="string"&&d.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:c||void 0});return}if(kr(n)){if(this.messageToken&&n.messageToken!==this.messageToken)return;let c=typeof n.sessionId=="string"?n.sessionId:void 0;if(this.config.sessionId&&c&&c!==this.config.sessionId)return;this.cardFields.ready();return}if(!_r(n)||this.messageToken&&n.messageToken!==this.messageToken)return;let i=this.config.sessionId,s=typeof n.sessionId=="string"?n.sessionId:void 0;if(i&&s&&s!==i||(n.type==="complete"||n.type==="decline")&&i&&s!==i)return;let o=Rr(n.paymentMethod),a=Sr(n.vaultOutcome),l={...n.sessionId??this.config.sessionId?{sessionId:n.sessionId??this.config.sessionId}:{},...n.outcome?{outcome:n.outcome}:{},...n.paymentId?{paymentId:n.paymentId}:{},...n.authorizationExpiresAt?{authorizationExpiresAt:n.authorizationExpiresAt}:{},...n.failureOutcome?{failureOutcome:n.failureOutcome}:{},...n.intentId?{intentId:n.intentId}:{},...n.declineReason?{declineReason:n.declineReason}:{},...n.message?{message:n.message}:{},...a?{vaultOutcome:a}:{},...o?{paymentMethod:o}:{}};n.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??_()),this.isVerificationStateError(n)?(D(N("operation.state_transition","vault_mount")),this.telemetryReporter?.log({name:"operation.state_transition",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})):(D(br(n,this.submissionStarted,this.config.captureMethod,this.config.operation)),this.reportOutcome(n),n.type==="error"&&ae(this.submissionStarted,n).errorCode==="VAULT_LOAD_FAILED"&&this.cardFields.fail("load_error")),n.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),this.postCardBrandIcons(),this.postCardFieldPlaceholders(),this.postSubmitLabel(),wr(n)||this.cardFields.ready()),n.type==="action_required"&&n.nextActionRedirectUrl&&this.showActionRequiredOverlay(n.nextActionRedirectUrl),(n.type==="complete"||n.type==="decline"||n.type==="error"||n.type==="submitting")&&(this.endActionChallengeFromWidget(n.type),this.hideActionRequiredOverlay()),n.type!=="action_required"&&this.emit(n.type,l)};this.messageHandler=e,window.addEventListener("message",e)}isVerificationStateError(e){return e.type==="error"&&this.verificationRequired&&!this.submissionStarted&&vr(e.failureOutcome)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;let{type:n}=e;if(n==="ready"&&!this.vaultReadyReported&&(this.vaultReadyReported=!0,t.performance({stage:"vault_ready",durationMs:Math.max(0,t.now()-this.mountStartedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card",requestCategory:"provider_sdk"})),n==="complete"||n==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:Xe(e,this.config.captureMethod,this.config.operation),provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="error"){let o=ae(this.submissionStarted,e);t.log({name:"vault.terminal",stage:o.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...o,provider:"pcivault",paymentMethodCategory:"card"});return}if(n==="action_required"){t.log({name:"vault.action.required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),t.log({name:"vault.three_ds.handoff",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});let o=this.submissionStartedAt;this.submissionStartedAt=null,o!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-o),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[i,s]=Qe[n];t.log({name:i,stage:s,provider:"pcivault",paymentMethodCategory:"card"})}applyTheme(e){this.theme=e,this.postTheme()}postTheme(){this.theme!==void 0&&this.postToHostedWindow({source:"flopay-vault-host",type:"theme",theme:this.theme},this.directiveTargetOrigin())}setSubmitGate(e){this.submitGateBlocked=e,this.postSubmitGate()}postSubmitGate(){this.postToHostedWindow({source:"flopay-vault-host",type:"gate",blocked:this.submitGateBlocked},this.directiveTargetOrigin())}setCardFieldOrder(e,t){this.cardFieldOrder=e,this.cardAutoFocus=t,this.postCardFieldOrder()}postCardFieldOrder(){this.postToHostedWindow({source:"flopay-vault-host",type:"fieldOrder",order:this.cardFieldOrder,autoFocus:this.cardAutoFocus},this.directiveTargetOrigin())}setCardBrandIcons(e){this.cardBrandIcons=e===!0,this.postCardBrandIcons()}setCardFieldPlaceholders(e){let t=Ir(e),n=t===void 0&&this.cardFieldPlaceholders!==void 0;this.cardFieldPlaceholders=t,this.postCardFieldPlaceholders(n?{}:t)}postCardFieldPlaceholders(e=this.cardFieldPlaceholders){let t=this.config.sessionId,{messageToken:n,expectedOrigin:i}=this;e===void 0||!t||!n||!i||this.postToHostedWindow({source:"flopay-vault-host",type:"cardFieldPlaceholders",sessionId:t,messageToken:n,placeholders:{...e}},i)}postCardBrandIcons(){this.postToHostedWindow({source:"flopay-vault-host",type:"cardBrandIcons",show:this.cardBrandIcons},this.directiveTargetOrigin())}setSubmitLabel(e){this.submitLabel=e,this.postSubmitLabel()}postSubmitLabel(){let e=this.submitLabel,t=this.config.sessionId,{messageToken:n,expectedOrigin:i}=this;e===void 0||!t||!n||!i||this.postToHostedWindow({source:"flopay-vault-host",type:"submitLabel",sessionId:t,messageToken:n,label:e},i)}hostedWindow(){return this.container?.querySelector("iframe")?.contentWindow??null}postToHostedWindow(e,t){let n=this.hostedWindow();if(n)try{n.postMessage(e,t)}catch{}}directiveTargetOrigin(){return this.expectedOrigin??"*"}emit(e,t){for(let n of this.listeners.get(e)??[])n(t)}showActionRequiredOverlay(e){if(typeof document>"u")return;if(this.actionOverlay){let 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=fe(this.beginActionChallengeAttempt()),n=Te(e),i=!1,s=h=>{if(i)return;let y=Ce(h,n);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"),X(e)==="invalid"&&t.record("action_invalid",{reason:"invalid_url"}),document.addEventListener("securitypolicyviolation",s),window.addEventListener("pagehide",o);let l=document.createElement("div");l.setAttribute("data-flopay-action-required","1"),l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Card authentication"),l.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let c=document.createElement("iframe");c.setAttribute("title","Card authentication"),c.setAttribute("allow","payment"),c.tabIndex=0,c.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),c.addEventListener("load",()=>{a.loaded||(a.loaded=!0,t.record("iframe_load",{evidenceBasis:"iframe_load_event"}))}),c.src=e,l.appendChild(c);let d=document.createElement("button");d.type="button",d.setAttribute("aria-label","Close card authentication"),d.textContent="\xD7",d.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(";"),d.addEventListener("click",()=>this.abandonActionRequiredOverlay()),l.appendChild(d),l.addEventListener("click",h=>{h.target===l&&this.abandonActionRequiredOverlay()});let m=0,u=h=>{let y=h.data,f=!!y&&typeof y=="object"&&y.source==="flopay-vault-3ds-return";if(h.source!==c.contentWindow){f&&m<dr&&(m+=1,t.record("return_rejected",{reason:"untrusted_source",evidenceBasis:"message_origin_check"}));return}f&&(t.record("trusted_return",{evidenceBasis:"message_origin_check"}),t.terminal("trusted_return",{evidenceBasis:"message_origin_check"}),D(N("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",u),this.threeDsReturnHandler=u,t.record("render_attempted");try{document.body.appendChild(l)}catch(h){throw t.record("render_failed"),this.hideActionRequiredOverlay(),this.actionOverlayPreviousFocus=null,h}t.record("container_attached"),t.record("navigation_assigned");let g=ve(l);g&&t.record("container_visibility",{reason:g,evidenceBasis:"parent_computed_style"}),this.actionOverlay=l,c.focus(),this.armActionRequiredTimeout(),D(N("vault.three_ds.handoff","three_ds_handoff"))}armActionRequiredTimeout(){this.actionOverlayTimer&&clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=setTimeout(()=>{this.actionOverlayTimer=null,this.actionOverlay&&this.timeOutActionRequiredOverlay()},hr)}reportChallengeAbandoned(){D(Je({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.hideActionRequiredOverlay(),this.emit("error",{...this.config.sessionId?{sessionId:this.config.sessionId}:{},message:mr})}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.hideActionRequiredOverlay(),this.emit("challenge_dismissed",{...this.config.sessionId?{sessionId:this.config.sessionId}:{}})}}beginActionChallengeAttempt(){try{return this.telemetryReporter?.beginThreeDsChallenge?.()}catch{return}}endActionChallengeFromWidget(e){let t=this.actionChallenge,n=t?.telemetry??this.lastChallengeTelemetry;if(this.lastChallengeTelemetry=null,!!n){if(e==="submitting"){if(!t)return;n.record("abort_observed",{reason:"unspecified",evidenceBasis:"signal_reason"}),n.terminal("abort",{reason:"unspecified",evidenceBasis:"signal_reason"});return}t&&n.terminal("status_poll",{evidenceBasis:"server_status"}),e==="complete"&&n.reconcile("succeeded"),e==="decline"&&n.reconcile("declined")}}hideActionRequiredOverlay(){if(this.actionChallenge){let t=this.actionChallenge;this.actionChallenge=null;try{t.detach()}catch{}t.telemetry.record("teardown")}if(this.actionOverlayTimer&&(clearTimeout(this.actionOverlayTimer),this.actionOverlayTimer=null),this.threeDsReturnHandler&&(window.removeEventListener("message",this.threeDsReturnHandler),this.threeDsReturnHandler=null),!this.actionOverlay)return;this.actionOverlay.parentNode?.removeChild(this.actionOverlay),this.actionOverlay=null;let e=this.actionOverlayPreviousFocus;this.actionOverlayPreviousFocus=null,e?.isConnected&&e.focus()}applyHeight(e){let t=this.container?.querySelector("iframe");if(!t)return;let n=Math.max(0,Math.min(Math.ceil(e),2e3));t.style.height=`${n}px`}};function Zr(r,e){let t=le;return new t(r,{reporter:e})}export{he as a,me as b,P as c,z as d,Q as e,de as f,ue as g,fe as h,X as i,xr as j,ve as k,Ce as l,Te as m,_ as n,A as o,Xt as p,ie as q,Kr as r,le as s,Zr as t};
|