@facto-to/connect 0.0.1-beta.1 → 0.0.1-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,114 @@
1
+ declare const MANDATE_LIMIT_PERIOD_VALUES: readonly ["daily", "weekly", "monthly"];
2
+ type MandateLimitPeriod = (typeof MANDATE_LIMIT_PERIOD_VALUES)[number];
3
+ declare const MANDATE_USE_CASE_VALUES: readonly ["immediate", "recurring", "top_up", "metered"];
4
+ type MandateUseCase = (typeof MANDATE_USE_CASE_VALUES)[number];
5
+ interface CreateMandatePaymentRequest {
6
+ amount: string;
7
+ currency: string;
8
+ description?: string | null;
9
+ mandateId: string;
10
+ merchantPaymentRef: string;
11
+ metadata?: Record<string, string> | null;
12
+ paymentOptionId?: string | null;
13
+ /**
14
+ * The sub-merchant name to show on the consumer's billing line. Returned
15
+ * on authenticated payment reads; NOT included in webhook payloads.
16
+ * Rejects control, zero-width and bidi override characters.
17
+ */
18
+ subMerchantDisplayName?: string | null;
19
+ /**
20
+ * Your reconciliation anchor for the sub-merchant this payment was
21
+ * collected for. Echoed on every payment projection and included in
22
+ * payment webhooks. Display and reconciliation only — Facto never keys,
23
+ * joins or deduplicates on it.
24
+ */
25
+ subMerchantRef?: string | null;
26
+ useCase: MandateUseCase;
27
+ }
28
+ interface ExchangeLinkCodeResponse {
29
+ appId: string;
30
+ cardRef?: string | null;
31
+ factoServerWalletAddress?: string | null;
32
+ factoUserId?: string | null;
33
+ grantStatus: string;
34
+ pipelineReady: boolean;
35
+ scopes: string[];
36
+ /**
37
+ * Opaque public link handle (GA contract). Store this; the legacy
38
+ * factoUserId/factoServerWalletAddress fields remain for pre-GA callers.
39
+ */
40
+ userLinkRef: string;
41
+ }
42
+ declare const MANDATE_DECLINE_REASON_VALUES: readonly ["mandate_inactive", "mandate_revoked", "mandate_expired", "use_case_not_allowed", "mandate_limit_exceeded", "mandate_period_limit_exceeded", "user_limit_exceeded", "limit_check_unavailable", "payment_path_unavailable", "funding_source_not_authorized", "payment_option_not_pinned", "settlement_reverted", "idempotency_conflict"];
43
+ type MandateDeclineReason = (typeof MANDATE_DECLINE_REASON_VALUES)[number];
44
+ declare const MANDATE_PAYMENT_STATUS_VALUES: readonly ["accepted", "declined", "charging", "finalizing", "succeeded", "paid_via_coverage", "failed", "canceled"];
45
+ type MandatePaymentStatus = (typeof MANDATE_PAYMENT_STATUS_VALUES)[number];
46
+ declare const MANDATE_STATUS_VALUES: readonly ["pending", "active", "paused", "revoked", "expired", "suspended"];
47
+ type MandateStatus = (typeof MANDATE_STATUS_VALUES)[number];
48
+ declare const MANDATE_AUTHORIZATION_SESSION_STATUS_VALUES: readonly ["created", "authorized", "declined", "expired"];
49
+ type MandateAuthorizationSessionStatus = (typeof MANDATE_AUTHORIZATION_SESSION_STATUS_VALUES)[number];
50
+ interface MandatePayment {
51
+ amount: string;
52
+ /**
53
+ * Cumulative refunded amount — merchants compute the remaining
54
+ * refundable headroom as `amount - amountRefunded` without local
55
+ * bookkeeping (spec 012 FR-004).
56
+ */
57
+ amountRefunded: string;
58
+ chargeId?: string | null;
59
+ createdAt: string;
60
+ currency: string;
61
+ declineReason?: MandateDeclineReason | null;
62
+ finalityEtaSeconds?: number | null;
63
+ mandateId: string;
64
+ merchantPaymentRef: string;
65
+ paymentId: string;
66
+ status: MandatePaymentStatus;
67
+ /** The name shown on the consumer's billing line. */
68
+ subMerchantDisplayName?: string | null;
69
+ /**
70
+ * Echoed back so a PSP can reconcile without a local join. DISPLAY ONLY:
71
+ * no read path keys, matches, joins or deduplicates on it (migration 281's
72
+ * rule, inherited by 329).
73
+ */
74
+ subMerchantRef?: string | null;
75
+ /** When the payment reached a terminal status. Serialized as `terminalAt`. */
76
+ terminalAt?: string | null;
77
+ /**
78
+ * On-chain settlement tx hash of the linked charge, stamped by the settler
79
+ * once the payment reaches a terminal status. Serialized as `txHash`.
80
+ */
81
+ txHash?: string | null;
82
+ updatedAt?: string | null;
83
+ useCase: MandateUseCase;
84
+ }
85
+ /** Property bag shared by every `anyOf` branch of `PaymentCapabilityRequest`. */
86
+ interface PaymentCapabilityRequestProperties {
87
+ /** Legacy shape: merchant app id, sent together with `facto_server_wallet_address`. */
88
+ app_id?: string;
89
+ /** Legacy shape: Facto server wallet address of the linked user. */
90
+ facto_server_wallet_address?: string;
91
+ /** Optional merchant mandate. When present, readiness follows that mandate's pinned route. */
92
+ mandateId?: string;
93
+ /** GA shape: opaque user-link reference minted by the link-code exchange. */
94
+ userLinkRef?: string;
95
+ }
96
+ declare const PAYMENT_READINESS_NOT_READY_REASON_VALUES: readonly ["payment_route_not_provisioned", "protocol_config_incomplete"];
97
+ type PaymentReadinessNotReadyReason = (typeof PAYMENT_READINESS_NOT_READY_REASON_VALUES)[number];
98
+ declare const PAYMENT_READINESS_SCOPE_VALUES: readonly ["account_default", "mandate_pinned"];
99
+ type PaymentReadinessScope = (typeof PAYMENT_READINESS_SCOPE_VALUES)[number];
100
+ interface PaymentCapabilityResponse {
101
+ appId: string;
102
+ assetSymbol: string;
103
+ chainId: number;
104
+ factoServerWalletAddress?: string | null;
105
+ factoUserId?: string | null;
106
+ notReadyReason?: PaymentReadinessNotReadyReason | null;
107
+ pipelineReady: boolean;
108
+ protocolId: string;
109
+ readinessScope: PaymentReadinessScope;
110
+ spendMode: string;
111
+ userLinkRef: string;
112
+ }
113
+
114
+ export type { CreateMandatePaymentRequest as C, ExchangeLinkCodeResponse as E, MandatePayment as M, PaymentCapabilityRequestProperties as P, MandateUseCase as a, MandateLimitPeriod as b, PaymentCapabilityResponse as c, MandateAuthorizationSessionStatus as d, MandateStatus as e, MandatePaymentStatus as f, MandateDeclineReason as g, PaymentReadinessNotReadyReason as h, PaymentReadinessScope as i };
@@ -0,0 +1,114 @@
1
+ declare const MANDATE_LIMIT_PERIOD_VALUES: readonly ["daily", "weekly", "monthly"];
2
+ type MandateLimitPeriod = (typeof MANDATE_LIMIT_PERIOD_VALUES)[number];
3
+ declare const MANDATE_USE_CASE_VALUES: readonly ["immediate", "recurring", "top_up", "metered"];
4
+ type MandateUseCase = (typeof MANDATE_USE_CASE_VALUES)[number];
5
+ interface CreateMandatePaymentRequest {
6
+ amount: string;
7
+ currency: string;
8
+ description?: string | null;
9
+ mandateId: string;
10
+ merchantPaymentRef: string;
11
+ metadata?: Record<string, string> | null;
12
+ paymentOptionId?: string | null;
13
+ /**
14
+ * The sub-merchant name to show on the consumer's billing line. Returned
15
+ * on authenticated payment reads; NOT included in webhook payloads.
16
+ * Rejects control, zero-width and bidi override characters.
17
+ */
18
+ subMerchantDisplayName?: string | null;
19
+ /**
20
+ * Your reconciliation anchor for the sub-merchant this payment was
21
+ * collected for. Echoed on every payment projection and included in
22
+ * payment webhooks. Display and reconciliation only — Facto never keys,
23
+ * joins or deduplicates on it.
24
+ */
25
+ subMerchantRef?: string | null;
26
+ useCase: MandateUseCase;
27
+ }
28
+ interface ExchangeLinkCodeResponse {
29
+ appId: string;
30
+ cardRef?: string | null;
31
+ factoServerWalletAddress?: string | null;
32
+ factoUserId?: string | null;
33
+ grantStatus: string;
34
+ pipelineReady: boolean;
35
+ scopes: string[];
36
+ /**
37
+ * Opaque public link handle (GA contract). Store this; the legacy
38
+ * factoUserId/factoServerWalletAddress fields remain for pre-GA callers.
39
+ */
40
+ userLinkRef: string;
41
+ }
42
+ declare const MANDATE_DECLINE_REASON_VALUES: readonly ["mandate_inactive", "mandate_revoked", "mandate_expired", "use_case_not_allowed", "mandate_limit_exceeded", "mandate_period_limit_exceeded", "user_limit_exceeded", "limit_check_unavailable", "payment_path_unavailable", "funding_source_not_authorized", "payment_option_not_pinned", "settlement_reverted", "idempotency_conflict"];
43
+ type MandateDeclineReason = (typeof MANDATE_DECLINE_REASON_VALUES)[number];
44
+ declare const MANDATE_PAYMENT_STATUS_VALUES: readonly ["accepted", "declined", "charging", "finalizing", "succeeded", "paid_via_coverage", "failed", "canceled"];
45
+ type MandatePaymentStatus = (typeof MANDATE_PAYMENT_STATUS_VALUES)[number];
46
+ declare const MANDATE_STATUS_VALUES: readonly ["pending", "active", "paused", "revoked", "expired", "suspended"];
47
+ type MandateStatus = (typeof MANDATE_STATUS_VALUES)[number];
48
+ declare const MANDATE_AUTHORIZATION_SESSION_STATUS_VALUES: readonly ["created", "authorized", "declined", "expired"];
49
+ type MandateAuthorizationSessionStatus = (typeof MANDATE_AUTHORIZATION_SESSION_STATUS_VALUES)[number];
50
+ interface MandatePayment {
51
+ amount: string;
52
+ /**
53
+ * Cumulative refunded amount — merchants compute the remaining
54
+ * refundable headroom as `amount - amountRefunded` without local
55
+ * bookkeeping (spec 012 FR-004).
56
+ */
57
+ amountRefunded: string;
58
+ chargeId?: string | null;
59
+ createdAt: string;
60
+ currency: string;
61
+ declineReason?: MandateDeclineReason | null;
62
+ finalityEtaSeconds?: number | null;
63
+ mandateId: string;
64
+ merchantPaymentRef: string;
65
+ paymentId: string;
66
+ status: MandatePaymentStatus;
67
+ /** The name shown on the consumer's billing line. */
68
+ subMerchantDisplayName?: string | null;
69
+ /**
70
+ * Echoed back so a PSP can reconcile without a local join. DISPLAY ONLY:
71
+ * no read path keys, matches, joins or deduplicates on it (migration 281's
72
+ * rule, inherited by 329).
73
+ */
74
+ subMerchantRef?: string | null;
75
+ /** When the payment reached a terminal status. Serialized as `terminalAt`. */
76
+ terminalAt?: string | null;
77
+ /**
78
+ * On-chain settlement tx hash of the linked charge, stamped by the settler
79
+ * once the payment reaches a terminal status. Serialized as `txHash`.
80
+ */
81
+ txHash?: string | null;
82
+ updatedAt?: string | null;
83
+ useCase: MandateUseCase;
84
+ }
85
+ /** Property bag shared by every `anyOf` branch of `PaymentCapabilityRequest`. */
86
+ interface PaymentCapabilityRequestProperties {
87
+ /** Legacy shape: merchant app id, sent together with `facto_server_wallet_address`. */
88
+ app_id?: string;
89
+ /** Legacy shape: Facto server wallet address of the linked user. */
90
+ facto_server_wallet_address?: string;
91
+ /** Optional merchant mandate. When present, readiness follows that mandate's pinned route. */
92
+ mandateId?: string;
93
+ /** GA shape: opaque user-link reference minted by the link-code exchange. */
94
+ userLinkRef?: string;
95
+ }
96
+ declare const PAYMENT_READINESS_NOT_READY_REASON_VALUES: readonly ["payment_route_not_provisioned", "protocol_config_incomplete"];
97
+ type PaymentReadinessNotReadyReason = (typeof PAYMENT_READINESS_NOT_READY_REASON_VALUES)[number];
98
+ declare const PAYMENT_READINESS_SCOPE_VALUES: readonly ["account_default", "mandate_pinned"];
99
+ type PaymentReadinessScope = (typeof PAYMENT_READINESS_SCOPE_VALUES)[number];
100
+ interface PaymentCapabilityResponse {
101
+ appId: string;
102
+ assetSymbol: string;
103
+ chainId: number;
104
+ factoServerWalletAddress?: string | null;
105
+ factoUserId?: string | null;
106
+ notReadyReason?: PaymentReadinessNotReadyReason | null;
107
+ pipelineReady: boolean;
108
+ protocolId: string;
109
+ readinessScope: PaymentReadinessScope;
110
+ spendMode: string;
111
+ userLinkRef: string;
112
+ }
113
+
114
+ export type { CreateMandatePaymentRequest as C, ExchangeLinkCodeResponse as E, MandatePayment as M, PaymentCapabilityRequestProperties as P, MandateUseCase as a, MandateLimitPeriod as b, PaymentCapabilityResponse as c, MandateAuthorizationSessionStatus as d, MandateStatus as e, MandatePaymentStatus as f, MandateDeclineReason as g, PaymentReadinessNotReadyReason as h, PaymentReadinessScope as i };
@@ -1,2 +1 @@
1
1
  "use strict";var r=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var i=Object.getOwnPropertyNames;var d=Object.prototype.hasOwnProperty;var f=(t,e)=>{for(var o in e)r(t,o,{get:e[o],enumerable:!0})},l=(t,e,o,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of i(e))!d.call(t,n)&&n!==o&&r(t,n,{get:()=>e[n],enumerable:!(a=c(e,n))||a.enumerable});return t};var s=t=>l(r({},"__esModule",{value:!0}),t);var h={};f(h,{createFactoConnectReactUnavailable:()=>v});module.exports=s(h);function v(){throw new Error("@facto-to/connect/react is reserved for the React integration and is not implemented yet.")}
2
- //# sourceMappingURL=index.cjs.map
@@ -1,2 +1 @@
1
1
  function e(){throw new Error("@facto-to/connect/react is reserved for the React integration and is not implemented yet.")}export{e as createFactoConnectReactUnavailable};
2
- //# sourceMappingURL=index.js.map
@@ -1,2 +1 @@
1
- "use strict";var W=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var Ie=Object.getOwnPropertyNames;var ve=Object.prototype.hasOwnProperty;var _e=(t,e)=>{for(var n in e)W(t,n,{get:e[n],enumerable:!0})},Ee=(t,e,n,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ie(e))!ve.call(t,o)&&o!==n&&W(t,o,{get:()=>e[o],enumerable:!(a=Ae(e,o))||a.enumerable});return t};var we=t=>Ee(W({},"__esModule",{value:!0}),t);var Xt={};_e(Xt,{FACTO_CONNECT_API_BASE_URLS:()=>N,FACTO_CONNECT_HOSTED_URLS:()=>E,FactoConnectHintError:()=>f,FactoConnectServerError:()=>R,buildHostedConnectUrl:()=>me,createFactoConnectServer:()=>fe,default:()=>Qt,isTerminalMandatePaymentStatus:()=>pe,signWebhookPayload:()=>Ot,verifyFactoCardProgramConnectHint:()=>Wt,verifyWebhookSignature:()=>Nt,withServerRetry:()=>le});module.exports=we(Xt);var U=require("crypto");var Q=["mandate_inactive","mandate_revoked","mandate_expired","use_case_not_allowed","mandate_limit_exceeded","mandate_period_limit_exceeded","user_limit_exceeded","limit_check_unavailable","payment_path_unavailable","payment_option_not_pinned","idempotency_conflict"];var X=["payment_route_not_provisioned","protocol_config_incomplete"];function j(t){return t==="sandbox"?"dev":t}var N=Object.freeze({dev:"https://dev-api.facto.to",production:"https://api.facto.to"}),E=Object.freeze({dev:"https://dev.facto.to",production:"https://app.facto.to"}),h=Object.freeze({exchangeLinkCode:"/api/merchant/user-links/exchange",paymentCapability:"/api/merchant/payment-readiness",checkoutSessions:"/api/merchant/checkout-sessions",authorizationSessions:"/api/merchant/authorization-sessions",paymentAuthorizations:"/api/merchant/payment-authorizations",paymentOptions:"/api/merchant/payment-options",payments:"/api/merchant/payments"}),R=class extends Error{code;retryable;status;details;retryAfterSeconds;constructor(e,n,a){super(n),this.name="FactoConnectServerError",this.code=e,this.retryable=a.retryable,this.status=a.status,this.details=a.details,this.retryAfterSeconds=a.retryAfterSeconds}};function Pe(t){let e=t.headers.get("retry-after");if(!e)return;let n=Number(e.trim());return Number.isFinite(n)&&n>=0?n:void 0}function Te(t,e){return t<=0?Promise.resolve():new Promise((n,a)=>{if(e?.aborted){a(new R("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}));return}let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),a(new R("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}))};e?.addEventListener("abort",s,{once:!0})})}async function le(t,e={}){let n=e.maxRetries??2,a=e.baseDelayMs??200,o=e.maxDelayMs??5e3,s=e.respectRetryAfter??!0,c=e.sleep??Te,u=0;for(;;)try{return await t()}catch(l){if(!(l instanceof R)||!l.retryable||u>=n)throw l;u+=1;let r=s&&typeof l.retryAfterSeconds=="number"?l.retryAfterSeconds*1e3:void 0,i=Math.min(o,a*2**(u-1)),y=i*.25*Math.random(),L=r??i+y;e.onRetry?.({attempt:u,error:l,delayMs:L}),await c(L,e.signal)}}function me(t){t.appId||m("appId is required"),t.state||m("state is required"),t.nonce||m("nonce is required"),t.hostedConnectUrl||m("hostedConnectUrl is required and has no implicit default: pass the Hosted Connect origin for the target environment (e.g. FACTO_CONNECT_HOSTED_URLS.dev)");let e=J(t.hostedConnectUrl);_(e,E,"hostedConnectUrl",!0);let n=new URL("/connect",`${e}/`);n.searchParams.set("external_app_id",t.appId),n.searchParams.set("external_state",t.state),n.searchParams.set("external_nonce",t.nonce);let a=new URLSearchParams;t.customerEmail!==void 0&&a.set("customer_email",t.customerEmail),t.customerUsername!==void 0&&a.set("customer_username",t.customerUsername);let o=a.toString();return o&&(n.hash=o),n.toString()}function fe(t){let e=De(t),n=`Basic ${Dt(`${e.clientId}:${e.clientSecret}`)}`,a=(r,i)=>S(e,r,{code:i.code,state:i.state,nonce:i.nonce},n,ot),o=(r,i)=>S(e,r,at(e,i),n,st),s=(r,i)=>S(e,r,{appId:e.appId,externalCustomerRef:i.externalCustomerRef,requestedUseCases:i.requestedUseCases,defaultLimits:i.defaultLimits,returnUrl:i.returnUrl,state:i.state,...i.customerEmail===void 0?{}:{customerEmail:i.customerEmail},...i.customerUsername===void 0?{}:{customerUsername:i.customerUsername}},n,ie),c=(r,i)=>b(e,`${r}/${encodeURIComponent(i)}`,n,ie),u=(r,i)=>b(e,`${r}/${encodeURIComponent(i)}`,n,de),l=(r,i)=>{let y={mandateId:i.mandateId,merchantPaymentRef:i.merchantPaymentRef,amount:i.amount,currency:i.currency,useCase:i.useCase};return i.paymentOptionId!==void 0&&(y.paymentOptionId=i.paymentOptionId),i.description!==void 0&&(y.description=i.description),i.metadata!==void 0&&(y.metadata=i.metadata),S(e,r,y,n,O,{"Idempotency-Key":i.idempotencyKey},[402])},p=(r,i)=>b(e,`${r}/${encodeURIComponent(i)}`,n,O);return{createHostedConnectUrl(r){let i=r.hostedConnectUrl??e.hostedConnectUrl;if(r.hostedConnectUrl!==void 0){let y=_(r.hostedConnectUrl,E,"hostedConnectUrl",!0);y!==void 0&&y!==e.environment&&m("hostedConnectUrl conflicts with the configured environment")}return me({appId:e.appId,state:r.state,nonce:r.nonce,customerEmail:r.customerEmail,customerUsername:r.customerUsername,hostedConnectUrl:i})},exchangeUserLinkCode(r){return a(h.exchangeLinkCode,r)},getPaymentReadiness(r){return o(h.paymentCapability,r)},createAuthorizationSession(r){return s(h.authorizationSessions,r)},getAuthorizationSession(r){return c(h.authorizationSessions,r)},getPaymentAuthorization(r){return u(h.paymentAuthorizations,r)},createMerchantPayment(r){return l(h.payments,r)},getMerchantPayment(r){return p(h.payments,r)},exchangeLinkCode(r){return a(h.exchangeLinkCode,r)},getPaymentCapability(r){return o(h.paymentCapability,r)},createCheckoutSession(r){return r.userLinkRef!==void 0&&v(r.userLinkRef,"ul_","userLinkRef"),S(e,h.checkoutSessions,{...r.userLinkRef!==void 0?{userLinkRef:r.userLinkRef}:{app_id:e.appId,facto_server_wallet_address:r.factoServerWalletAddress},amount:r.amount,asset_symbol:r.assetSymbol,order_ref:r.orderRef,return_url:r.returnUrl},n,it)},getCheckoutSession(r){return b(e,`${h.checkoutSessions}/${encodeURIComponent(r)}`,n,dt)},createMandateAuthorizationSession(r){return s(h.authorizationSessions,r)},getMandateAuthorizationSession(r){return c(h.authorizationSessions,r)},getMerchantMandate(r){return u(h.paymentAuthorizations,r)},listPaymentOptions(r){return r.userLinkRef!==void 0&&v(r.userLinkRef,"ul_","userLinkRef"),S(e,h.paymentOptions,{...r.userLinkRef!==void 0?{userLinkRef:r.userLinkRef}:{appId:e.appId,grantRef:r.grantRef},...r.amount!==void 0?{amount:r.amount}:{},...r.assetSymbol!==void 0?{assetSymbol:r.assetSymbol}:{}},n,lt)},createMandatePayment(r){return l(h.payments,r)},getMandatePayment(r){return p(h.payments,r)},onStatus(r,i,y){return Me(()=>b(e,`${h.payments}/${encodeURIComponent(r)}`,n,O),i,y)},revokeUserLink(r){return re(e,`/api/merchant/user-links/${encodeURIComponent(r)}`,n)},listMerchantPayments(r={}){return b(e,z("/api/merchant/payments",{limit:r.limit,startingAfter:r.startingAfter,createdAfter:r.createdAfter,createdBefore:r.createdBefore,authorizationId:r.authorizationId,status:r.status}),n,i=>H(i,O))},listPaymentAuthorizations(r={}){return b(e,z("/api/merchant/payment-authorizations",{limit:r.limit,startingAfter:r.startingAfter,userLinkRef:r.userLinkRef,status:r.status}),n,i=>H(i,de))},createRefund(r){let i={paymentId:r.paymentId};return r.amount!==void 0&&(i.amount=r.amount),r.reason!==void 0&&(i.reason=r.reason),r.merchantRefundRef!==void 0&&(i.merchantRefundRef=r.merchantRefundRef),S(e,"/api/merchant/refunds",i,n,$,{"Idempotency-Key":r.idempotencyKey},[402])},getRefund(r){return b(e,`/api/merchant/refunds/${encodeURIComponent(r)}`,n,$)},listRefunds(r={}){return b(e,z("/api/merchant/refunds",{limit:r.limit,startingAfter:r.startingAfter,paymentId:r.paymentId}),n,i=>H(i,$))},createWebhookEndpoint(r){return S(e,"/api/merchant/webhook-endpoints",{url:r.url,enabledEvents:r.enabledEvents},n,ae)},listWebhookEndpoints(){return b(e,"/api/merchant/webhook-endpoints",n,r=>{let y=g(r).data;if(!Array.isArray(y))throw new Error("expected data array");return y.map(K)})},getWebhookEndpoint(r){return b(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n,K)},deleteWebhookEndpoint(r){return re(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n)},rotateWebhookSecret(r){return S(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}/rotate-secret`,{},n,ae)},getDevCapabilities(){return D(e,"getDevCapabilities"),b(e,"/api/dev/capabilities",n,Qe)},fundDevUser(r){return D(e,"fundDevUser"),ee(r.userLinkRef),te(r.amount),ne(r.idempotencyKey),S(e,"/api/dev/faucet/usdc",{userLinkRef:r.userLinkRef,amount:r.amount},n,tt,{"Idempotency-Key":r.idempotencyKey})},simulateDevCharge(r){return D(e,"simulateDevCharge"),ee(r.userLinkRef),r.cardRef!==void 0&&v(r.cardRef,"card_","cardRef"),te(r.amount),Fe(r.scenario),r.merchantReference!==void 0&&(typeof r.merchantReference!="string"||r.merchantReference.length>120)&&m("merchantReference must not exceed 120 characters"),ne(r.idempotencyKey),S(e,"/api/dev/simulate/charge",{userLinkRef:r.userLinkRef,...r.cardRef===void 0?{}:{cardRef:r.cardRef},amount:r.amount,scenario:r.scenario,...r.merchantReference===void 0?{}:{merchantReference:r.merchantReference}},n,oe,{"Idempotency-Key":r.idempotencyKey})},getDevSimulation(r){return D(e,"getDevSimulation"),v(r,"sim_","simulationId"),b(e,`/api/dev/simulations/${encodeURIComponent(r)}`,n,oe)},sendWebhookTestDelivery(r){return Oe(e),Ne(r.webhookEndpointId),r.message!==void 0&&(typeof r.message!="string"||r.message.length>120)&&m("webhook test message must not exceed 120 characters"),S(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r.webhookEndpointId)}/test-delivery`,r.message===void 0?{}:{message:r.message},n,nt)}}}var ke=new Set(["declined","succeeded","paid_via_coverage","failed","canceled"]);function pe(t){return ke.has(t)}async function Me(t,e,n={}){let a=Math.max(0,n.initialIntervalMs??1e3),o=Math.max(a,n.maxIntervalMs??8e3),s=n.backoffFactor??1.5,c=n.timeoutMs??3e5,u=n.signal,l=Date.now()+c,p=a,r;for(;;){xe(u);let i=await t();if(i.status!==r&&(r=i.status,e(i)),pe(i.status))return i;let y=l-Date.now();if(y<=0)return i;await Ue(Math.min(p,y),u),p=Math.min(p*s,o)}}function xe(t){if(t?.aborted)throw new R("FACTO_STATUS_POLL_ABORTED","mandate payment polling aborted",{retryable:!1})}function Ue(t,e){return new Promise((n,a)=>{let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),a(new R("FACTO_STATUS_POLL_ABORTED","mandate payment polling aborted",{retryable:!1}))};if(e){if(e.aborted){clearTimeout(o),s();return}e.addEventListener("abort",s,{once:!0})}})}var Le=Object.freeze(["dev","production","sandbox"]);function De(t){t.appId||m("appId is required"),t.clientId||m("clientId is required"),t.clientSecret||m("clientSecret is required");let e=t.environment;(e===void 0||!Le.includes(e))&&m("environment is required and must be 'dev', 'production', or 'sandbox' ('sandbox' is the documented public test environment name and targets the same dev endpoints \u2014 ADR-0077). 'staging' and the former 'custom' selector are retired: pass explicit apiBaseUrl and hostedConnectUrl overrides (valid with any environment) for a local, private, or staging deployment. There is no implicit default; the legacy production fallback over /api/external/* routes was removed. See https://docs.facto.to/reference/sdk"),t.transport!==void 0&&t.fetch!==void 0&&m("provide either transport or fetch, not both"),t.timeoutMs!==void 0&&(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<=0)&&m("timeoutMs must be a positive safe integer");let n=t.apiBaseUrl?_(t.apiBaseUrl,N,"apiBaseUrl",!1):void 0,a=t.hostedConnectUrl?_(t.hostedConnectUrl,E,"hostedConnectUrl",!0):void 0;n!==void 0&&a!==void 0&&n!==a&&m("apiBaseUrl and hostedConnectUrl target different Facto environments");let o=e,s=j(o);for(let p of[n,a])p!==void 0&&p!==s&&m("environment selector conflicts with a published Facto endpoint");let c=J(t.apiBaseUrl??N[s]),u=J(t.hostedConnectUrl??E[s]),l=_(c,N,"apiBaseUrl",!1);return _(u,E,"hostedConnectUrl",!0),We(t.clientId,l),{appId:t.appId,clientId:t.clientId,clientSecret:t.clientSecret,environment:o,apiBaseUrl:c,hostedConnectUrl:u,transport:t.transport??t.fetch??((p,r)=>globalThis.fetch(p,r)),...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.retry===void 0?{}:{retry:t.retry},...t.signal===void 0?{}:{signal:t.signal}}}function D(t,e){j(t.environment)!=="dev"&&m(`${e} is available only in the sandbox/dev environment`)}function Oe(t){j(t.environment)!=="dev"&&m("sendWebhookTestDelivery is available only in the sandbox/dev environment")}function v(t,e,n){(typeof t!="string"||!new RegExp(`^${e}[A-Za-z0-9_-]+$`).test(t))&&m(`${n} must be an opaque ${e} reference`)}function ee(t){v(t,"ul_","userLinkRef")}function Ne(t){(typeof t!="string"||!/^we_[A-Za-z0-9]+$/.test(t))&&m("webhookEndpointId must be an opaque we_ reference")}function te(t){(typeof t!="object"||t===null||t.currency!=="USDC"||typeof t.amount!="string"||!/^[0-9]+(?:\.[0-9]{1,6})?$/.test(t.amount))&&m("Dev amount must be a USDC decimal with at most six fractional digits")}function Fe(t){(typeof t!="string"||!ye.includes(t))&&m("unknown Dev simulation scenario")}function ne(t){(typeof t!="string"||t.trim()!==t||t.length<16||t.length>255)&&m("idempotencyKey must be 16 to 255 non-whitespace-trimmed characters")}function We(t,e){let n=e==="dev",a=e==="production";t.startsWith("dev_")&&e!==void 0&&!n&&m("a dev credential can target only the sandbox/dev environment"),(n||a)&&(t.startsWith("staging_")||t.startsWith("test_")||t.startsWith("lab_")||t.startsWith("sandbox_"))&&m("internal or legacy (staging_/test_/lab_/sandbox_) credentials cannot target a published Facto environment")}function _(t,e,n,a){let o;try{o=new URL(t)}catch{m(`${n} must be an absolute URL`)}let s=o.hostname.toLowerCase().replace(/\.$/,"");for(let c of["dev","production"]){let u=new URL(e[c]);if(s!==u.hostname.toLowerCase())continue;let l=o.pathname==="/"||a&&o.pathname==="/connect";return(o.origin!==u.origin||o.username!==""||o.password!==""||!l||o.search!==""||o.hash!=="")&&m(`${n} is not the exact published ${c} endpoint`),c}}async function S(t,e,n,a,o,s={},c=[]){let u=await ge(t,async()=>{let l=await Y(t,`${t.apiBaseUrl}${e}`,{method:"POST",headers:{authorization:a,"content-type":"application/json",...s},body:JSON.stringify(n)});if(!l.ok&&!c.includes(l.status))throw await G(l);return l},s["Idempotency-Key"]!==void 0);try{return o(await u.json())}catch(l){throw new R("FACTO_ENGINE_RESPONSE_INVALID","Facto Engine returned an invalid response",{retryable:!1,details:l})}}async function b(t,e,n,a){let o=await ge(t,async()=>{let s=await Y(t,`${t.apiBaseUrl}${e}`,{method:"GET",headers:{authorization:n}});if(!s.ok)throw await G(s);return s},!0);try{return a(await o.json())}catch(s){throw new R("FACTO_ENGINE_RESPONSE_INVALID","Facto Engine returned an invalid response",{retryable:!1,details:s})}}async function re(t,e,n){let a=await Y(t,`${t.apiBaseUrl}${e}`,{method:"DELETE",headers:{authorization:n}});if(!a.ok)throw await G(a)}async function G(t){return new R("FACTO_ENGINE_REQUEST_FAILED",`Facto Engine request failed with status ${t.status}`,{retryable:t.status===429||t.status>=500,status:t.status,details:await Lt(t),retryAfterSeconds:Pe(t)})}function ge(t,e,n){return n?le(e,{...t.retry,signal:t.signal??t.retry?.signal}):e()}function Y(t,e,n){return t.timeoutMs===void 0?t.transport(e,{...n,signal:t.signal}):ze(t,e,n)}function ze(t,e,n){let a=new AbortController,o=()=>a.abort();return t.signal?.aborted?Promise.reject(new R("FACTO_REQUEST_ABORTED","Facto Engine request aborted",{retryable:!1})):(t.signal?.addEventListener("abort",o,{once:!0}),new Promise((s,c)=>{let u=setTimeout(()=>{a.abort(),c(new R("FACTO_REQUEST_ABORTED","Facto Engine request timed out",{retryable:!1}))},t.timeoutMs);t.transport(e,{...n,signal:a.signal}).then(s,c).finally(()=>{clearTimeout(u),t.signal?.removeEventListener("abort",o)})}))}function z(t,e){let n=new URLSearchParams;for(let[o,s]of Object.entries(e))s!==void 0&&s!==""&&n.set(o,String(s));let a=n.toString();return a?`${t}?${a}`:t}function H(t,e){let n=g(t),a=n.data;if(!Array.isArray(a))throw new Error("expected data array");return{data:a.map(e),hasMore:P(n,"hasMore")}}var He=["pending","succeeded","failed"],$e=["requested_by_customer","duplicate","fraudulent","other"];function qe(t,e){let n=t[e];if(typeof n!="string"||!He.includes(n))throw new Error(`expected refund status at ${e}`);return n}function Ve(t,e){let n=t[e];if(n!==void 0){if(typeof n!="string"||!$e.includes(n))throw new Error(`expected refund reason at ${e}`);return n}}function $(t){let e=g(t),n=Ve(e,"reason"),a=A(e,"merchantRefundRef");return{refundId:d(e,"refundId"),paymentId:d(e,"paymentId"),status:qe(e,"status"),amount:d(e,"amount"),currency:d(e,"currency"),...n===void 0?{}:{reason:n},...a===void 0?{}:{merchantRefundRef:a},createdAt:d(e,"createdAt")}}var Be=["user_link.revoked","payment_authorization.activated","payment_authorization.updated","payment_authorization.revoked","checkout_session.completed","checkout_session.expired","payment.succeeded","payment.failed","refund.succeeded","refund.failed"];function Ke(t,e){let n=t[e];if(!Array.isArray(n))throw new Error(`expected event-type array at ${e}`);return n.map(a=>{if(typeof a!="string"||!Be.includes(a))throw new Error(`unknown webhook event type: ${String(a)}`);return a})}function K(t){let e=g(t),n=e.status;if(n!=="enabled"&&n!=="disabled")throw new Error("expected webhook endpoint status");return{webhookEndpointId:d(e,"webhookEndpointId"),url:d(e,"url"),enabledEvents:Ke(e,"enabledEvents"),status:n,createdAt:d(e,"createdAt")}}function ae(t){let e=K(t),n=g(t);return{...e,secret:d(n,"secret")}}var F=["fixtures","synthetic_identity","faucet","simulation","money_loop","webhook_test_delivery"],Je=["unavailable","degraded","ready"],je=["contract","implemented","deployed","verified"],ye=["approved","declined_setup","declined_limit","payment_failed"],Ge=["pre_admission","onchain_test_assets"],Ye=["accepted","processing","succeeded","failed","declined"],Ze=["accepted","broadcast","confirmed","failed"];function Qe(t){let e=g(t),n=e.capabilities;if(!Array.isArray(n)||n.length!==F.length)throw new Error("expected exactly six Dev capabilities");let a=n.map(Xe),o=new Set(a.map(s=>s.name));if(o.size!==F.length)throw new Error("expected each Dev capability exactly once");for(let s of F)if(!o.has(s))throw new Error(`missing Dev capability: ${s}`);return{environment:x(e,"environment","dev"),contractVersion:x(e,"contractVersion","2026-07-09"),capabilities:a,checkedAt:d(e,"checkedAt")}}function Xe(t){let e=g(t),n=C(e,"name",F,"Dev capability name"),a=C(e,"status",Je,"Dev capability status"),o=C(e,"evidenceLevel",je,"Dev evidence level"),s=w(e,"reasonCode"),c=w(e,"verifiedAt");if(a==="ready"&&(o!=="verified"||c===null))throw new Error("ready Dev capability requires verified evidence");let u=rt(e,"limits");return{name:n,status:a,evidenceLevel:o,...s===void 0?{}:{reasonCode:s},...c===void 0?{}:{verifiedAt:c},...u===void 0?{}:{limits:u}}}function et(t){let e=g(t),n=d(e,"amount");if(!/^[0-9]+(?:\.[0-9]{1,6})?$/.test(n))throw new Error("expected Dev USDC decimal amount");return{amount:n,currency:x(e,"currency","USDC")}}function tt(t){let e=g(t);return{faucetTransferId:M(e,"faucetTransferId","sft_"),userLinkRef:M(e,"userLinkRef","ul_"),amount:et(e.amount),status:C(e,"status",Ze,"Dev faucet status"),createdAt:d(e,"createdAt")}}function oe(t){let e=g(t);return{simulationId:M(e,"simulationId","sim_"),scenario:C(e,"scenario",ye,"Dev scenario"),executionMode:C(e,"executionMode",Ge,"Dev execution mode"),status:C(e,"status",Ye,"Dev simulation status"),reasonCode:q(e,"reasonCode"),authorizationRef:q(e,"authorizationRef"),chargeRef:q(e,"chargeRef"),createdAt:d(e,"createdAt"),updatedAt:d(e,"updatedAt")}}function nt(t){let e=g(t);return{eventId:se(e,"eventId","evt_"),deliveryId:se(e,"deliveryId","wd_"),status:x(e,"status","queued"),createdAt:d(e,"createdAt")}}function rt(t,e){if(t[e]===void 0)return;let n=g(t[e]);for(let a of Object.values(n))if(a!==null&&typeof a!="string"&&typeof a!="number"&&typeof a!="boolean")throw new Error(`expected scalar Dev limit at ${e}`);return n}function M(t,e,n){let a=d(t,e);if(!new RegExp(`^${n}[A-Za-z0-9_-]+$`).test(a))throw new Error(`expected opaque ${e}`);return a}function se(t,e,n){let a=d(t,e);if(!new RegExp(`^${n}[A-Za-z0-9]+$`).test(a))throw new Error(`expected opaque ${e}`);return a}function at(t,e){return e.userLinkRef===void 0&&e.factoServerWalletAddress===void 0&&m("payment readiness requires userLinkRef, factoServerWalletAddress, or both"),e.userLinkRef!==void 0&&v(e.userLinkRef,"ul_","userLinkRef"),e.factoServerWalletAddress!==void 0&&typeof e.factoServerWalletAddress!="string"&&m("factoServerWalletAddress must be a string"),{...e.userLinkRef===void 0?{}:{userLinkRef:e.userLinkRef},...e.factoServerWalletAddress===void 0?{}:{app_id:t.appId,facto_server_wallet_address:e.factoServerWalletAddress}}}function k(t,e){let n=t[e];if(n==null)return n;if(typeof n!="string"||n.length===0)throw new Error(`expected non-empty string or null at ${e}`);return n}function ot(t){let e=g(t),n=k(e,"cardRef"),a=k(e,"factoUserId"),o=k(e,"factoServerWalletAddress");if(n!=null&&(v(n,"card_","cardRef"),a!=null||o!=null))throw new Error("synthetic Dev links must not expose canonical identity");return{appId:d(e,"appId"),userLinkRef:M(e,"userLinkRef","ul_"),grantStatus:d(e,"grantStatus"),pipelineReady:P(e,"pipelineReady"),scopes:Ut(e,"scopes"),...n===void 0?{}:{cardRef:n},...a===void 0?{}:{factoUserId:a},...o===void 0?{}:{factoServerWalletAddress:o}}}function st(t){let e=g(t),n=P(e,"pipelineReady"),a=e.notReadyReason,o=a==null?a:C(e,"notReadyReason",X,"payment readiness not-ready reason");if(n&&o!==void 0&&o!==null)throw new Error("expected notReadyReason only when pipelineReady is false");let s=k(e,"factoUserId"),c=k(e,"factoServerWalletAddress");return{appId:d(e,"appId"),userLinkRef:M(e,"userLinkRef","ul_"),selectedPipelineId:d(e,"selectedPipelineId"),chainId:Ce(e,"chainId"),protocolId:d(e,"protocolId"),assetSymbol:d(e,"assetSymbol"),spendMode:d(e,"spendMode"),pipelineReady:n,...o===void 0?{}:{notReadyReason:o},...s===void 0?{}:{factoUserId:s},...c===void 0?{}:{factoServerWalletAddress:c}}}function it(t){let e=g(t);return{sessionId:d(e,"sessionId"),checkoutUrl:d(e,"checkoutUrl"),status:x(e,"status","pending"),amount:d(e,"amount"),assetSymbol:d(e,"assetSymbol"),orderRef:w(e,"orderRef")}}function dt(t){let e=g(t);return{sessionId:d(e,"sessionId"),status:_t(e,"status"),amount:d(e,"amount"),assetSymbol:d(e,"assetSymbol"),orderRef:w(e,"orderRef"),chargeId:w(e,"chargeId"),confirmedAt:w(e,"confirmedAt")}}function ie(t){let e=g(t),n=A(e,"mandateId"),a=A(e,"userLinkRef");return{sessionId:d(e,"sessionId"),authorizationUrl:d(e,"authorizationUrl"),status:Tt(e,"status"),...n===void 0?{}:{mandateId:n},...a===void 0?{}:{userLinkRef:a},expiresAt:d(e,"expiresAt"),state:d(e,"state")}}function de(t){let e=g(t),n=A(e,"expiresAt");return{mandateId:d(e,"mandateId"),appId:d(e,"appId"),status:Pt(e,"status"),allowedUseCases:xt(e,"allowedUseCases"),limits:yt(e.limits),paymentPath:ht(e.paymentPath),createdAt:d(e,"createdAt"),...n===void 0?{}:{expiresAt:n}}}var ct="direct",ut="defaultPaymentOptionId";function lt(t){let e=g(t);be(e,"payment options");let n=e.paymentOptions;if(!Array.isArray(n))throw new Error("expected paymentOptions array");let a=n.map(pt).filter(c=>c.settlementPath===ct),o=Ct(e,ut),s=mt(a,o);return{paymentOptions:a,...s===void 0?{}:{selectedPaymentOptionId:s}}}function mt(t,e){return e!==void 0&&t.some(a=>a.paymentOptionId===e)?e:(t.find(a=>a.ready)??t[0])?.paymentOptionId}function ft(t){let e=A(t,"settlementPath"),n=A(t,"spendMode"),a=e??n;if(a===void 0)throw new Error("expected settlementPath or the deprecated spendMode on a payment option");return{settlementPath:a,spendMode:n??a}}function pt(t){let e=g(t);be(e,"payment option");let n=A(e,"blockingReason"),a=d(e,"assetSymbol"),o=d(e,"chainLabel"),s=d(e,"protocolLabel"),{settlementPath:c,spendMode:u}=ft(e);return{paymentOptionId:he(e,"paymentOptionId"),label:gt({assetSymbol:a,protocolLabel:s,chainLabel:o},d(e,"label")),ready:P(e,"ready"),isDefault:P(e,"isDefault"),chainId:Ce(e,"chainId"),chainLabel:o,protocolLabel:s,assetSymbol:a,spendMode:u,settlementPath:c,...n===void 0?{}:{blockingReason:n}}}function gt(t,e){let n=[t.assetSymbol,t.protocolLabel,t.chainLabel].map(a=>a.trim()).filter(a=>a.length>0);return n.length>0?n.join(" \xB7 "):e}function O(t){let e=g(t),n=A(e,"chargeId"),a=A(e,"txHash"),o=Mt(e,"declineReason"),s=Rt(e,"finalityEtaSeconds"),c=A(e,"terminalAt"),u=A(e,"updatedAt");return{paymentId:d(e,"paymentId"),mandateId:d(e,"mandateId"),merchantPaymentRef:d(e,"merchantPaymentRef"),status:kt(e,"status"),amount:d(e,"amount"),currency:d(e,"currency"),useCase:Et(e,"useCase"),...n===void 0?{}:{chargeId:n},...a===void 0?{}:{txHash:a},...o===void 0?{}:{declineReason:o},...s===void 0?{}:{finalityEtaSeconds:s},...c===void 0?{}:{terminalAt:c},createdAt:d(e,"createdAt"),...u===void 0?{}:{updatedAt:u}}}function yt(t){let e=g(t);return{perTxAmount:d(e,"perTxAmount"),periodAmount:d(e,"periodAmount"),period:wt(e,"period")}}function ht(t){let e=g(t),n=A(e,"blockingReason");return{ready:P(e,"ready"),summary:d(e,"summary"),...n===void 0?{}:{blockingReason:n}}}function g(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("expected object");return t}function d(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`expected non-empty string at ${e}`);return n}function A(t,e){let n=t[e];if(n!==void 0){if(typeof n!="string"||n.length===0)throw new Error(`expected non-empty string at ${e}`);return n}}function he(t,e){let n=d(t,e);if(!n.startsWith("fpo_"))throw new Error(`expected opaque Facto payment option id at ${e}`);return n}function Ct(t,e){if(!(t[e]===void 0||t[e]===null))return he(t,e)}function x(t,e,n){if(t[e]!==n)throw new Error(`expected ${n} at ${e}`);return n}function P(t,e){let n=t[e];if(typeof n!="boolean")throw new Error(`expected boolean at ${e}`);return n}function Ce(t,e){let n=t[e];if(typeof n!="number"||!Number.isFinite(n))throw new Error(`expected finite number at ${e}`);return n}function Rt(t,e){let n=t[e];if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n))throw new Error(`expected finite number at ${e}`);return n}}var bt=["pending","charged","expired","cancelled"],Re=["immediate","recurring","top_up","metered"],St=["daily","weekly","monthly"],At=["pending","active","paused","revoked","expired","suspended"],It=["created","authorized","declined","expired"],vt=["accepted","declined","charging","finalizing","succeeded","paid_via_coverage","failed","canceled"];function _t(t,e){let n=t[e];if(typeof n!="string"||!bt.includes(n))throw new Error(`expected checkout status at ${e}`);return n}function Et(t,e){return C(t,e,Re,"mandate use case")}function wt(t,e){return C(t,e,St,"mandate limit period")}function Pt(t,e){return C(t,e,At,"mandate status")}function Tt(t,e){return C(t,e,It,"mandate authorization status")}function kt(t,e){return C(t,e,vt,"mandate payment status")}function Mt(t,e){if(t[e]!==void 0)return C(t,e,Q,"mandate decline reason")}function xt(t,e){let n=t[e];if(!Array.isArray(n))throw new Error(`expected mandate use case array at ${e}`);return n.map(a=>{if(typeof a!="string"||!Re.includes(a))throw new Error(`expected mandate use case array at ${e}`);return a})}function C(t,e,n,a){let o=t[e];if(typeof o!="string"||!n.includes(o))throw new Error(`expected ${a} at ${e}`);return o}function w(t,e){let n=t[e];if(n==null)return null;if(typeof n!="string")throw new Error(`expected string or null at ${e}`);return n}function q(t,e){let n=t[e];if(n===null)return null;if(typeof n!="string")throw new Error(`expected required string or null at ${e}`);return n}function Ut(t,e){let n=t[e];if(!Array.isArray(n)||n.some(a=>typeof a!="string"))throw new Error(`expected string array at ${e}`);return n}function be(t,e){let a=["userId","factoUserId","cardId","routeId","vaultKind","serverWallet","factoServerWalletAddress","pathSnapshot","paymentPathSnapshot","pipelineId","selectedPipelineId","paymentRouteId","routeSelector"].find(o=>t[o]!==void 0);if(a)throw new Error(`unsafe ${e} field: ${a}`)}async function Lt(t){try{return await t.json()}catch{return await t.text().catch(()=>null)}}function J(t){return t.replace(/\/+$/,"")}function m(t){throw new R("FACTO_CONFIG_INVALID",t,{retryable:!1})}function Dt(t){let e=globalThis.btoa;if(e)return e(t);let n=globalThis.Buffer;if(n)return n.from(t).toString("base64");m("No base64 encoder is available in this runtime")}function Ot(t,e,n=Math.floor(Date.now()/1e3)){e||m("webhook secret is required"),(!Number.isSafeInteger(n)||n<0)&&m("webhook timestamp must be a non-negative safe integer");let a=(0,U.createHmac)("sha256",e).update(`${n}.`).update(t).digest("hex");return`t=${n},v1=${a}`}function Nt(t,e,n,a=300){let o=e.split(",").map(l=>l.trim()),s,c=[];for(let l of o){let p=l.indexOf("=");if(p===-1)continue;let r=l.slice(0,p),i=l.slice(p+1);r==="t"?s=Number(i):r==="v1"&&c.push(i)}if(s===void 0||!Number.isFinite(s)||Math.abs(Date.now()/1e3-s)>a||c.length===0)return!1;let u=(0,U.createHmac)("sha256",n).update(`${s}.`).update(t).digest();return c.some(l=>{let p;try{p=Buffer.from(l,"hex")}catch{return!1}return p.length===u.length&&(0,U.timingSafeEqual)(p,u)})}var f=class extends Error{code;details;constructor(e,n,a={}){super(n),this.name="FactoConnectHintError",this.code=e,this.details=a.details}},Ft="facto";async function Wt(t){if(t===null||typeof t!="object")throw new f("FACTO_HINT_INPUT_INVALID","verifyFactoCardProgramConnectHint requires an input object");let e=B(t.connectHint,"connectHint"),n=B(t.audience,"audience"),a=t.issuer===void 0?Ft:B(t.issuer,"issuer"),o=Jt(t.clockToleranceSeconds),s=Math.floor(jt(t.now)/1e3),{headerB64:c,payloadB64:u,signature:l}=zt(e),p=Z(ce(c,"header"),"FACTO_HINT_MALFORMED","connect hint header");if(p.alg!=="EdDSA")throw new f("FACTO_HINT_UNSUPPORTED_ALG","connect hint JWS alg must be EdDSA",{details:{alg:p.alg}});let r=typeof p.kid=="string"?p.kid:void 0,i=await Ht(t.jwks),y=Vt(i,r),L=Yt(`${c}.${u}`);if(!await Bt(L,l,y))throw new f("FACTO_HINT_SIGNATURE_INVALID","connect hint signature does not verify against the Facto JWKS");let I=Kt(ce(u,"payload"));if(I.iss!==a)throw new f("FACTO_HINT_ISSUER_MISMATCH","connect hint issuer mismatch",{details:{expected:a,actual:I.iss}});if(I.aud!==n)throw new f("FACTO_HINT_AUDIENCE_MISMATCH","connect hint audience mismatch",{details:{expected:n,actual:I.aud}});if(s>I.exp+o)throw new f("FACTO_HINT_EXPIRED","connect hint has expired",{details:{exp:I.exp,now:s}});return{programRef:I.program_ref,pairwiseSubject:I.sub,nonce:I.nonce,expiresAt:new Date(I.exp*1e3).toISOString()}}function zt(t){let e=t.split(".");if(e.length!==3)throw new f("FACTO_HINT_MALFORMED","connect hint is not a compact JWS (expected three segments)");let[n,a,o]=e;if(!n||!a||!o)throw new f("FACTO_HINT_MALFORMED","connect hint has an empty JWS segment");return{headerB64:n,payloadB64:a,signature:Se(o,"signature")}}function ce(t,e){let n=new TextDecoder().decode(Se(t,e));try{return JSON.parse(n)}catch(a){throw new f("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid JSON`,{details:a})}}async function Ht(t){if(t==null)throw new f("FACTO_HINT_INPUT_INVALID","jwks is required");return V(typeof t=="function"?await t():typeof t=="string"?await $t(t):t)}async function $t(t){let e;try{e=await fetch(t,{method:"GET",headers:{accept:"application/json"}})}catch(n){throw new f("FACTO_HINT_JWKS_INVALID",`failed to fetch Facto JWKS from ${t}`,{details:n})}if(!e.ok)throw new f("FACTO_HINT_JWKS_INVALID",`Facto JWKS request failed with status ${e.status}`,{details:{status:e.status}});try{return await e.json()}catch(n){throw new f("FACTO_HINT_JWKS_INVALID","Facto JWKS response was not valid JSON",{details:n})}}function V(t){let e=Z(t,"FACTO_HINT_JWKS_INVALID","JWKS");if(!Array.isArray(e.keys))throw new f("FACTO_HINT_JWKS_INVALID",'JWKS "keys" must be an array');return{keys:e.keys.map(qt)}}function qt(t){let e=typeof t=="object"&&t!==null?t:{};return{kty:typeof e.kty=="string"?e.kty:"",crv:typeof e.crv=="string"?e.crv:"",x:typeof e.x=="string"?e.x:"",...typeof e.kid=="string"?{kid:e.kid}:{},...typeof e.alg=="string"?{alg:e.alg}:{},...typeof e.use=="string"?{use:e.use}:{}}}function Vt(t,e){let n=t.keys.filter(a=>a.kty==="OKP"&&a.crv==="Ed25519"&&a.x.length>0);if(n.length===0)throw new f("FACTO_HINT_JWKS_INVALID","Facto JWKS has no usable Ed25519 signing key");if(e!==void 0){let a=n.filter(o=>o.kid===e);if(a.length>0)return a}return n}async function Bt(t,e,n){let a=Zt();for(let o of n){let s;try{s=await a.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:o.x},{name:"Ed25519"},!1,["verify"])}catch{continue}try{if(await a.verify({name:"Ed25519"},s,e,t))return!0}catch{continue}}return!1}function Kt(t){let e=Z(t,"FACTO_HINT_CLAIMS_INVALID","connect hint claims");return{iss:T(e,"iss"),aud:T(e,"aud"),sub:T(e,"sub"),program_ref:T(e,"program_ref"),nonce:T(e,"nonce"),iat:ue(e,"iat"),exp:ue(e,"exp")}}function B(t,e){if(typeof t!="string"||t.length===0)throw new f("FACTO_HINT_INPUT_INVALID",`${e} must be a non-empty string`);return t}function Jt(t){if(t===void 0)return 0;if(typeof t!="number"||!Number.isFinite(t)||t<0)throw new f("FACTO_HINT_INPUT_INVALID","clockToleranceSeconds must be a non-negative finite number");return t}function jt(t){if(t===void 0)return Date.now();if(t instanceof Date){let e=t.getTime();if(Number.isNaN(e))throw new f("FACTO_HINT_INPUT_INVALID","now is an invalid Date");return e}if(typeof t=="number"&&Number.isFinite(t))return t;throw new f("FACTO_HINT_INPUT_INVALID","now must be a Date or unix milliseconds number")}function Z(t,e,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new f(e,`${n} must be a JSON object`);return t}function T(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new f("FACTO_HINT_CLAIMS_INVALID",`connect hint claim "${e}" must be a non-empty string`);return n}function ue(t,e){let n=t[e];if(typeof n!="number"||!Number.isFinite(n))throw new f("FACTO_HINT_CLAIMS_INVALID",`connect hint claim "${e}" must be a finite number`);return n}function Se(t,e){if(!/^[A-Za-z0-9_-]*$/.test(t))throw new f("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid base64url`);let n=t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4);return Gt(n,e)}function Gt(t,e){let n=globalThis.atob;if(n){let o;try{o=n(t)}catch(c){throw new f("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid base64url`,{details:c})}let s=new Uint8Array(o.length);for(let c=0;c<o.length;c+=1)s[c]=o.charCodeAt(c);return s}let a=globalThis.Buffer;if(a)return new Uint8Array(a.from(t,"base64"));throw new f("FACTO_HINT_INPUT_INVALID","No base64 decoder is available in this runtime")}function Yt(t){let e=new TextEncoder().encode(t),n=new Uint8Array(e.length);return n.set(e),n}function Zt(){let t=globalThis.crypto;if(t?.subtle)return t.subtle;throw new f("FACTO_HINT_INPUT_INVALID","Web Crypto (crypto.subtle) is not available in this runtime")}var Qt=fe;
2
- //# sourceMappingURL=index.cjs.map
1
+ "use strict";var H=Object.defineProperty;var Le=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Ne=Object.prototype.hasOwnProperty;var Oe=(t,e)=>{for(var n in e)H(t,n,{get:e[n],enumerable:!0})},De=(t,e,n,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ue(e))!Ne.call(t,o)&&o!==n&&H(t,o,{get:()=>e[o],enumerable:!(a=Le(e,o))||a.enumerable});return t};var Fe=t=>De(H({},"__esModule",{value:!0}),t);var yn={};Oe(yn,{FACTO_CONNECT_API_BASE_URLS:()=>F,FACTO_CONNECT_HOSTED_URLS:()=>v,FactoConnectHintError:()=>m,FactoConnectServerError:()=>R,PSP_CAPABILITY_TEMPLATES:()=>re,PSP_CREDENTIAL_KEYSPACE:()=>oe,PSP_CREDENTIAL_SCOPES:()=>q,PSP_PARTNER_ROLE_TYPE:()=>se,buildHostedConnectUrl:()=>Ae,carriesMoneyVerb:()=>ae,createFactoConnectServer:()=>_e,default:()=>fn,factoConnectEnvironmentFromClientId:()=>Re,isTerminalMandatePaymentStatus:()=>Ie,signWebhookPayload:()=>Gt,subMerchantOf:()=>de,verifyFactoCardProgramConnectHint:()=>Qt,verifyWebhookSignature:()=>Zt,withServerRetry:()=>be,withSubMerchant:()=>ie});module.exports=Fe(yn);var U=require("node:crypto");var ee=["mandate_inactive","mandate_revoked","mandate_expired","use_case_not_allowed","mandate_limit_exceeded","mandate_period_limit_exceeded","user_limit_exceeded","limit_check_unavailable","payment_path_unavailable","funding_source_not_authorized","payment_option_not_pinned","settlement_reverted","idempotency_conflict"];var te=["payment_route_not_provisioned","protocol_config_incomplete"],ne=["account_default","mandate_pinned"];var re=["psp_connect_sandbox","psp_mandate_sandbox","psp_billing_sandbox"],q={psp_connect_sandbox:["readiness.read","authorizations.request"],psp_mandate_sandbox:["readiness.read","authorizations.request","payments.execute","refunds.execute"],psp_billing_sandbox:["readiness.read","authorizations.request","payments.execute","refunds.execute","checkout.write"]};function ae(t){return q[t].includes("payments.execute")}var oe={dev:{clientIdPrefix:"dev_pspid_",clientSecretPrefix:"dev_pspsk_"},test:{clientIdPrefix:"test_pspid_"},lab:{clientIdPrefix:"lab_pspid_"}},se="psp";function ie(t,e){return{...t,...e.ref===void 0?{}:{subMerchantRef:e.ref},...e.displayName===void 0?{}:{subMerchantDisplayName:e.displayName}}}function de(t){return{...t.subMerchantRef==null?{}:{ref:t.subMerchantRef},...t.subMerchantDisplayName==null?{}:{displayName:t.subMerchantDisplayName}}}function z(t){return t==="sandbox"?"dev":t}var F=Object.freeze({dev:"https://dev-api.facto.to",production:"https://api.facto.to"}),v=Object.freeze({dev:"https://dev.facto.to",production:"https://app.facto.to"}),We=Object.freeze({dev:Object.freeze(["dev_mcid_","dev_pspid_","dev_cpid_"]),production:Object.freeze(["mcid_","pspid_","cpid_"])});function Re(t){if(typeof t=="string"){for(let e of["dev","production"])for(let n of We[e])if(t.startsWith(n))return e}}var h=Object.freeze({exchangeLinkCode:"/api/merchant/user-links/exchange",paymentCapability:"/api/merchant/payment-readiness",checkoutSessions:"/api/merchant/checkout-sessions",authorizationSessions:"/api/merchant/authorization-sessions",paymentAuthorizations:"/api/merchant/payment-authorizations",paymentOptions:"/api/merchant/payment-options",payments:"/api/merchant/payments"}),R=class extends Error{code;retryable;status;details;retryAfterSeconds;constructor(e,n,a){super(n),this.name="FactoConnectServerError",this.code=e,this.retryable=a.retryable,this.status=a.status,this.details=a.details,this.retryAfterSeconds=a.retryAfterSeconds}};function ze(t){let e=t.headers.get("retry-after");if(!e)return;let n=Number(e.trim());return Number.isFinite(n)&&n>=0?n:void 0}function He(t,e){return t<=0?Promise.resolve():new Promise((n,a)=>{if(e?.aborted){a(new R("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}));return}let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),a(new R("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}))};e?.addEventListener("abort",s,{once:!0})})}async function be(t,e={}){let n=e.maxRetries??2,a=e.baseDelayMs??200,o=e.maxDelayMs??5e3,s=e.respectRetryAfter??!0,d=e.sleep??He,u=0;for(;;)try{return await t()}catch(p){if(!(p instanceof R)||!p.retryable||u>=n)throw p;u+=1;let r=s&&typeof p.retryAfterSeconds=="number"?p.retryAfterSeconds*1e3:void 0,i=Math.min(o,a*2**(u-1)),y=i*.25*Math.random(),E=r??i+y;e.onRetry?.({attempt:u,error:p,delayMs:E}),await d(E,e.signal)}}function Ae(t){t.appId||l("appId is required"),t.state||l("state is required"),t.nonce||l("nonce is required"),t.hostedConnectUrl||l("hostedConnectUrl is required and has no implicit default: pass the Hosted Connect origin for the target environment (e.g. FACTO_CONNECT_HOSTED_URLS.dev)"),t.merchantOrigin||l("merchantOrigin is required and has no implicit default: pass the origin of the browsing context that will open this URL (the merchant page origin for this single call)");let e=jt(t.merchantOrigin),n=G(t.hostedConnectUrl);P(n,v,"hostedConnectUrl",!0);let a=new URL("/connect",`${n}/`);a.searchParams.set("external_app_id",t.appId),a.searchParams.set("external_state",t.state),a.searchParams.set("external_nonce",t.nonce),a.searchParams.set("external_origin",e);let o=new URLSearchParams;t.customerEmail!==void 0&&o.set("customer_email",t.customerEmail),t.customerUsername!==void 0&&o.set("customer_username",t.customerUsername);let s=o.toString();return s&&(a.hash=s),a.toString()}function _e(t){let e=Je(t),n=`Basic ${Yt(`${e.clientId}:${e.clientSecret}`)}`,a=(r,i)=>b(e,r,{code:i.code,state:i.state,nonce:i.nonce},n,ht),o=(r,i)=>b(e,r,gt(e,i),n,St),s=(r,i)=>b(e,r,{appId:e.appId,externalCustomerRef:i.externalCustomerRef,requestedUseCases:i.requestedUseCases,defaultLimits:i.defaultLimits,returnUrl:i.returnUrl,state:i.state,...i.customerEmail===void 0?{}:{customerEmail:i.customerEmail},...i.customerUsername===void 0?{}:{customerUsername:i.customerUsername}},n,ge),d=(r,i)=>C(e,`${r}/${encodeURIComponent(i)}`,n,ge),u=(r,i)=>C(e,`${r}/${encodeURIComponent(i)}`,n,he),p=(r,i)=>{let y={mandateId:i.mandateId,merchantPaymentRef:i.merchantPaymentRef,amount:i.amount,currency:i.currency,useCase:i.useCase};return i.paymentOptionId!==void 0&&(y.paymentOptionId=i.paymentOptionId),i.description!==void 0&&(y.description=i.description),i.metadata!==void 0&&(y.metadata=i.metadata),b(e,r,y,n,O,{"Idempotency-Key":i.idempotencyKey},[402])},f=(r,i)=>C(e,`${r}/${encodeURIComponent(i)}`,n,O);return{createHostedConnectUrl(r){let i=r.hostedConnectUrl??e.hostedConnectUrl;if(r.hostedConnectUrl!==void 0){let y=P(r.hostedConnectUrl,v,"hostedConnectUrl",!0);y!==void 0&&y!==z(e.environment)&&l("hostedConnectUrl conflicts with the configured environment")}return Ae({appId:e.appId,state:r.state,nonce:r.nonce,customerEmail:r.customerEmail,customerUsername:r.customerUsername,hostedConnectUrl:i,merchantOrigin:r.merchantOrigin})},exchangeUserLinkCode(r){return a(h.exchangeLinkCode,r)},getPaymentReadiness(r){return o(h.paymentCapability,r)},createAuthorizationSession(r){return s(h.authorizationSessions,r)},getAuthorizationSession(r){return d(h.authorizationSessions,r)},getPaymentAuthorization(r){return u(h.paymentAuthorizations,r)},createMerchantPayment(r){return p(h.payments,r)},getMerchantPayment(r){return f(h.payments,r)},exchangeLinkCode(r){return a(h.exchangeLinkCode,r)},getPaymentCapability(r){return o(h.paymentCapability,r)},createCheckoutSession(r){return r.userLinkRef!==void 0&&I(r.userLinkRef,"ul_","userLinkRef"),b(e,h.checkoutSessions,{...r.userLinkRef!==void 0?{userLinkRef:r.userLinkRef}:{app_id:e.appId,facto_server_wallet_address:r.factoServerWalletAddress},amount:r.amount,asset_symbol:r.assetSymbol,order_ref:r.orderRef,return_url:r.returnUrl},n,Ct)},getCheckoutSession(r){return C(e,`${h.checkoutSessions}/${encodeURIComponent(r)}`,n,Rt)},createMandateAuthorizationSession(r){return s(h.authorizationSessions,r)},getMandateAuthorizationSession(r){return d(h.authorizationSessions,r)},getMerchantMandate(r){return u(h.paymentAuthorizations,r)},listPaymentOptions(r){return r.userLinkRef!==void 0&&I(r.userLinkRef,"ul_","userLinkRef"),b(e,h.paymentOptions,{...r.userLinkRef!==void 0?{userLinkRef:r.userLinkRef}:{appId:e.appId,grantRef:r.grantRef},...r.amount!==void 0?{amount:r.amount}:{},...r.assetSymbol!==void 0?{assetSymbol:r.assetSymbol}:{}},n,_t)},createMandatePayment(r){return p(h.payments,r)},getMandatePayment(r){return f(h.payments,r)},onStatus(r,i,y){return $e(()=>C(e,`${h.payments}/${encodeURIComponent(r)}`,n,O),i,y)},revokeUserLink(r){return me(e,`/api/merchant/user-links/${encodeURIComponent(r)}`,n)},listMerchantPayments(r={}){return C(e,$("/api/merchant/payments",{limit:r.limit,startingAfter:r.startingAfter,createdAfter:r.createdAfter,createdBefore:r.createdBefore,authorizationId:r.authorizationId,status:r.status}),n,i=>V(i,O))},listPaymentAuthorizations(r={}){return C(e,$("/api/merchant/payment-authorizations",{limit:r.limit,startingAfter:r.startingAfter,userLinkRef:r.userLinkRef,status:r.status}),n,i=>V(i,he))},createRefund(r){let i={paymentId:r.paymentId};return r.amount!==void 0&&(i.amount=r.amount),r.reason!==void 0&&(i.reason=r.reason),r.merchantRefundRef!==void 0&&(i.merchantRefundRef=r.merchantRefundRef),b(e,"/api/merchant/refunds",i,n,B,{"Idempotency-Key":r.idempotencyKey},[402])},getRefund(r){return C(e,`/api/merchant/refunds/${encodeURIComponent(r)}`,n,B)},listRefunds(r={}){return C(e,$("/api/merchant/refunds",{limit:r.limit,startingAfter:r.startingAfter,paymentId:r.paymentId}),n,i=>V(i,B))},createWebhookEndpoint(r){return b(e,"/api/merchant/webhook-endpoints",{url:r.url,enabledEvents:r.enabledEvents},n,pe)},listWebhookEndpoints(){return C(e,"/api/merchant/webhook-endpoints",n,r=>{let y=g(r).data;if(!Array.isArray(y))throw new Error("expected data array");return y.map(Y)})},getWebhookEndpoint(r){return C(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n,Y)},deleteWebhookEndpoint(r){return me(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n)},rotateWebhookSecret(r){return b(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}/rotate-secret`,{},n,pe)},getDevCapabilities(){return N(e,"getDevCapabilities"),C(e,"/api/dev/capabilities",n,ut)},fundDevUser(r){return N(e,"fundDevUser"),ce(r.userLinkRef),ue(r.amount),le(r.idempotencyKey),b(e,"/api/dev/faucet/usdc",{userLinkRef:r.userLinkRef,amount:r.amount},n,pt,{"Idempotency-Key":r.idempotencyKey})},simulateDevCharge(r){return N(e,"simulateDevCharge"),ce(r.userLinkRef),r.cardRef!==void 0&&I(r.cardRef,"card_","cardRef"),ue(r.amount),Ge(r.scenario),r.merchantReference!==void 0&&(typeof r.merchantReference!="string"||r.merchantReference.length>120)&&l("merchantReference must not exceed 120 characters"),le(r.idempotencyKey),b(e,"/api/dev/simulate/charge",{userLinkRef:r.userLinkRef,...r.cardRef===void 0?{}:{cardRef:r.cardRef},amount:r.amount,scenario:r.scenario,...r.merchantReference===void 0?{}:{merchantReference:r.merchantReference}},n,fe,{"Idempotency-Key":r.idempotencyKey})},getDevSimulation(r){return N(e,"getDevSimulation"),I(r,"sim_","simulationId"),C(e,`/api/dev/simulations/${encodeURIComponent(r)}`,n,fe)},sendWebhookTestDelivery(r){return je(e),Ye(r.webhookEndpointId),r.message!==void 0&&(typeof r.message!="string"||r.message.length>120)&&l("webhook test message must not exceed 120 characters"),b(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r.webhookEndpointId)}/test-delivery`,r.message===void 0?{}:{message:r.message},n,ft)}}}var qe=new Set(["declined","succeeded","paid_via_coverage","failed","canceled"]);function Ie(t){return qe.has(t)}async function $e(t,e,n={}){let a=Math.max(0,n.initialIntervalMs??1e3),o=Math.max(a,n.maxIntervalMs??8e3),s=n.backoffFactor??1.5,d=n.timeoutMs??3e5,u=n.signal,p=Date.now()+d,f=a,r;for(;;){Ve(u);let i=await t();if(i.status!==r&&(r=i.status,e(i)),Ie(i.status))return i;let y=p-Date.now();if(y<=0)return i;await Be(Math.min(f,y),u),f=Math.min(f*s,o)}}function Ve(t){if(t?.aborted)throw new R("FACTO_STATUS_POLL_ABORTED","mandate payment polling aborted",{retryable:!1})}function Be(t,e){return new Promise((n,a)=>{let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),a(new R("FACTO_STATUS_POLL_ABORTED","mandate payment polling aborted",{retryable:!1}))};if(e){if(e.aborted){clearTimeout(o),s();return}e.addEventListener("abort",s,{once:!0})}})}var Ke=Object.freeze(["dev","production","sandbox"]);function Je(t){t.appId||l("appId is required"),t.clientId||l("clientId is required"),t.clientSecret||l("clientSecret is required");let e=t.environment;e!==void 0&&!Ke.includes(e)&&l("environment must be 'dev', 'production', or 'sandbox' ('sandbox' is the documented public test environment name and targets the same dev endpoints \u2014 ADR-0077). 'staging' and the former 'custom' selector are retired: pass explicit apiBaseUrl and hostedConnectUrl overrides (valid with any environment) for a local, private, or staging deployment. See https://docs.facto.to/merchants/quickstart"),t.transport!==void 0&&t.fetch!==void 0&&l("provide either transport or fetch, not both"),t.timeoutMs!==void 0&&(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<=0)&&l("timeoutMs must be a positive safe integer");let n=t.apiBaseUrl?P(t.apiBaseUrl,F,"apiBaseUrl",!1):void 0,a=t.hostedConnectUrl?P(t.hostedConnectUrl,v,"hostedConnectUrl",!0):void 0;n!==void 0&&a!==void 0&&n!==a&&l("apiBaseUrl and hostedConnectUrl target different Facto environments");let o=Re(t.clientId),s=e??o??n??a;s===void 0&&l("environment could not be resolved: pass it explicitly as 'dev', 'production', or 'sandbox' ('sandbox' is the documented public test environment name and targets the same dev endpoints \u2014 ADR-0077). It is normally derived from clientId, but this one carries no published keyspace: dev credentials are issued as dev_mcid_/dev_pspid_/dev_cpid_ and production credentials as mcid_/pspid_/cpid_. Internal (lab_/staging_/test_) and legacy (sandbox_) credentials never derive a published environment. See https://docs.facto.to/merchants/quickstart");let d=z(s);e!==void 0&&o!==void 0&&o!==d&&l(`environment '${e}' conflicts with the clientId keyspace, which is ${o} material`);for(let r of[n,a])r!==void 0&&r!==d&&l("environment selector conflicts with a published Facto endpoint");let u=G(t.apiBaseUrl??F[d]),p=G(t.hostedConnectUrl??v[d]),f=P(u,F,"apiBaseUrl",!1);return P(p,v,"hostedConnectUrl",!0),Ze(t.clientId,f),{appId:t.appId,clientId:t.clientId,clientSecret:t.clientSecret,environment:s,apiBaseUrl:u,hostedConnectUrl:p,transport:t.transport??t.fetch??((r,i)=>globalThis.fetch(r,i)),...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.retry===void 0?{}:{retry:t.retry},...t.signal===void 0?{}:{signal:t.signal}}}function N(t,e){z(t.environment)!=="dev"&&l(`${e} is available only in the sandbox/dev environment`)}function je(t){z(t.environment)!=="dev"&&l("sendWebhookTestDelivery is available only in the sandbox/dev environment")}function I(t,e,n){(typeof t!="string"||!new RegExp(`^${e}[A-Za-z0-9_-]+$`).test(t))&&l(`${n} must be an opaque ${e} reference`)}function ce(t){I(t,"ul_","userLinkRef")}function Ye(t){(typeof t!="string"||!/^we_[A-Za-z0-9]+$/.test(t))&&l("webhookEndpointId must be an opaque we_ reference")}function ue(t){(typeof t!="object"||t===null||t.currency!=="USDC"||typeof t.amount!="string"||!/^[0-9]+(?:\.[0-9]{1,6})?$/.test(t.amount))&&l("Dev amount must be a USDC decimal with at most six fractional digits")}function Ge(t){(typeof t!="string"||!ve.includes(t))&&l("unknown Dev simulation scenario")}function le(t){(typeof t!="string"||t.trim()!==t||t.length<16||t.length>255)&&l("idempotencyKey must be 16 to 255 non-whitespace-trimmed characters")}function Ze(t,e){let n=e==="dev",a=e==="production";t.startsWith("dev_")&&e!==void 0&&!n&&l("a dev credential can target only the sandbox/dev environment"),(n||a)&&(t.startsWith("staging_")||t.startsWith("test_")||t.startsWith("lab_")||t.startsWith("sandbox_"))&&l("internal or legacy (staging_/test_/lab_/sandbox_) credentials cannot target a published Facto environment")}function P(t,e,n,a){let o;try{o=new URL(t)}catch{l(`${n} must be an absolute URL`)}let s=o.hostname.toLowerCase().replace(/\.$/,"");for(let d of["dev","production"]){let u=new URL(e[d]);if(s!==u.hostname.toLowerCase())continue;let p=o.pathname==="/"||a&&o.pathname==="/connect";return(o.origin!==u.origin||o.username!==""||o.password!==""||!p||o.search!==""||o.hash!=="")&&l(`${n} is not the exact published ${d} endpoint`),d}}async function b(t,e,n,a,o,s={},d=[]){return Pe(t,()=>X(t,`${t.apiBaseUrl}${e}`,{method:"POST",headers:{authorization:a,"content-type":"application/json",...s},body:JSON.stringify(n)},async u=>{if(!u.ok&&!d.includes(u.status))throw await Z(u);return Ee(u,o)}),s["Idempotency-Key"]!==void 0)}async function C(t,e,n,a){return Pe(t,()=>X(t,`${t.apiBaseUrl}${e}`,{method:"GET",headers:{authorization:n}},async o=>{if(!o.ok)throw await Z(o);return Ee(o,a)}),!0)}async function Ee(t,e){try{return e(await t.json())}catch(n){throw new R("FACTO_ENGINE_RESPONSE_INVALID","Facto Engine returned an invalid response",{retryable:!1,details:n})}}async function me(t,e,n){return X(t,`${t.apiBaseUrl}${e}`,{method:"DELETE",headers:{authorization:n}},async a=>{if(!a.ok)throw await Z(a)})}async function Z(t){return new R("FACTO_ENGINE_REQUEST_FAILED",`Facto Engine request failed with status ${t.status}`,{retryable:t.status===429||t.status>=500,status:t.status,details:await Jt(t),retryAfterSeconds:ze(t)})}function Pe(t,e,n){return n?be(e,{...t.retry,signal:t.signal??t.retry?.signal}):e()}async function X(t,e,n,a){return t.timeoutMs===void 0&&t.signal===void 0?a(await t.transport(e,n)):Xe(t,e,n,a)}function Xe(t,e,n,a){let o=new AbortController;return t.signal?.aborted?Promise.reject(new R("FACTO_REQUEST_ABORTED","Facto Engine request aborted",{retryable:!1})):new Promise((s,d)=>{let u=!1,p,f=()=>{p!==void 0&&clearTimeout(p),t.signal?.removeEventListener("abort",i)},r=y=>{u||(u=!0,f(),d(new R("FACTO_REQUEST_ABORTED",y,{retryable:!1})),o.abort())},i=()=>r("Facto Engine request aborted");t.signal?.addEventListener("abort",i,{once:!0}),t.timeoutMs!==void 0&&(p=setTimeout(()=>r("Facto Engine request timed out"),t.timeoutMs)),(async()=>{try{let y=await t.transport(e,{...n,signal:o.signal});if(u){y.body?.cancel().catch(()=>{});return}let E=await a(y);u||(u=!0,f(),s(E))}catch(y){u||(u=!0,f(),d(y))}})()})}function $(t,e){let n=new URLSearchParams;for(let[o,s]of Object.entries(e))s!==void 0&&s!==""&&n.set(o,String(s));let a=n.toString();return a?`${t}?${a}`:t}function V(t,e){let n=g(t),a=n.data;if(!Array.isArray(a))throw new Error("expected data array");return{data:a.map(e),hasMore:w(n,"hasMore")}}var Qe=["pending","succeeded","failed"],et=["requested_by_customer","duplicate","fraudulent","other"];function tt(t,e){let n=t[e];if(typeof n!="string"||!Qe.includes(n))throw new Error(`expected refund status at ${e}`);return n}function nt(t,e){let n=t[e];if(n!==void 0){if(typeof n!="string"||!et.includes(n))throw new Error(`expected refund reason at ${e}`);return n}}function B(t){let e=g(t),n=nt(e,"reason"),a=A(e,"merchantRefundRef");return{refundId:c(e,"refundId"),paymentId:c(e,"paymentId"),status:tt(e,"status"),amount:c(e,"amount"),currency:c(e,"currency"),...n===void 0?{}:{reason:n},...a===void 0?{}:{merchantRefundRef:a},createdAt:c(e,"createdAt")}}var rt=["user_link.revoked","payment_authorization.activated","payment_authorization.updated","payment_authorization.revoked","checkout_session.completed","checkout_session.expired","payment.succeeded","payment.failed","refund.succeeded","refund.failed"];function at(t,e){let n=t[e];if(!Array.isArray(n))throw new Error(`expected event-type array at ${e}`);return n.map(a=>{if(typeof a!="string"||!rt.includes(a))throw new Error(`unknown webhook event type: ${String(a)}`);return a})}function Y(t){let e=g(t),n=e.status;if(n!=="enabled"&&n!=="disabled")throw new Error("expected webhook endpoint status");return{webhookEndpointId:c(e,"webhookEndpointId"),url:c(e,"url"),enabledEvents:at(e,"enabledEvents"),status:n,createdAt:c(e,"createdAt")}}function pe(t){let e=Y(t),n=g(t);return{...e,secret:c(n,"secret")}}var W=["fixtures","synthetic_identity","faucet","simulation","money_loop","webhook_test_delivery"],ot=["unavailable","degraded","ready"],st=["contract","implemented","deployed","verified"],ve=["approved","declined_setup","declined_limit","payment_failed"],it=["pre_admission","onchain_test_assets"],dt=["accepted","processing","succeeded","failed","declined"],ct=["accepted","broadcast","confirmed","failed"];function ut(t){let e=g(t),n=e.capabilities;if(!Array.isArray(n)||n.length!==W.length)throw new Error("expected exactly six Dev capabilities");let a=n.map(lt),o=new Set(a.map(s=>s.name));if(o.size!==W.length)throw new Error("expected each Dev capability exactly once");for(let s of W)if(!o.has(s))throw new Error(`missing Dev capability: ${s}`);return{environment:L(e,"environment","dev"),contractVersion:L(e,"contractVersion","2026-07-09"),capabilities:a,checkedAt:c(e,"checkedAt")}}function lt(t){let e=g(t),n=S(e,"name",W,"Dev capability name"),a=S(e,"status",ot,"Dev capability status"),o=S(e,"evidenceLevel",st,"Dev evidence level"),s=T(e,"reasonCode"),d=T(e,"verifiedAt");if(a==="ready"&&(o!=="verified"||d===null))throw new Error("ready Dev capability requires verified evidence");let u=yt(e,"limits");return{name:n,status:a,evidenceLevel:o,...s===void 0?{}:{reasonCode:s},...d===void 0?{}:{verifiedAt:d},...u===void 0?{}:{limits:u}}}function mt(t){let e=g(t),n=c(e,"amount");if(!/^[0-9]+(?:\.[0-9]{1,6})?$/.test(n))throw new Error("expected Dev USDC decimal amount");return{amount:n,currency:L(e,"currency","USDC")}}function pt(t){let e=g(t);return{faucetTransferId:x(e,"faucetTransferId","sft_"),userLinkRef:x(e,"userLinkRef","ul_"),amount:mt(e.amount),status:S(e,"status",ct,"Dev faucet status"),createdAt:c(e,"createdAt")}}function fe(t){let e=g(t);return{simulationId:x(e,"simulationId","sim_"),scenario:S(e,"scenario",ve,"Dev scenario"),executionMode:S(e,"executionMode",it,"Dev execution mode"),status:S(e,"status",dt,"Dev simulation status"),reasonCode:K(e,"reasonCode"),authorizationRef:K(e,"authorizationRef"),chargeRef:K(e,"chargeRef"),createdAt:c(e,"createdAt"),updatedAt:c(e,"updatedAt")}}function ft(t){let e=g(t);return{eventId:ye(e,"eventId","evt_"),deliveryId:ye(e,"deliveryId","wd_"),status:L(e,"status","queued"),createdAt:c(e,"createdAt")}}function yt(t,e){if(t[e]===void 0)return;let n=g(t[e]);for(let a of Object.values(n))if(a!==null&&typeof a!="string"&&typeof a!="number"&&typeof a!="boolean")throw new Error(`expected scalar Dev limit at ${e}`);return n}function x(t,e,n){let a=c(t,e);if(!new RegExp(`^${n}[A-Za-z0-9_-]+$`).test(a))throw new Error(`expected opaque ${e}`);return a}function ye(t,e,n){let a=c(t,e);if(!new RegExp(`^${n}[A-Za-z0-9]+$`).test(a))throw new Error(`expected opaque ${e}`);return a}function gt(t,e){return e.userLinkRef===void 0&&e.factoServerWalletAddress===void 0&&l("payment readiness requires userLinkRef, factoServerWalletAddress, or both"),e.userLinkRef!==void 0&&I(e.userLinkRef,"ul_","userLinkRef"),e.factoServerWalletAddress!==void 0&&typeof e.factoServerWalletAddress!="string"&&l("factoServerWalletAddress must be a string"),{...e.userLinkRef===void 0?{}:{userLinkRef:e.userLinkRef},...e.factoServerWalletAddress===void 0?{}:{app_id:t.appId,facto_server_wallet_address:e.factoServerWalletAddress}}}function k(t,e){let n=t[e];if(n==null)return n;if(typeof n!="string"||n.length===0)throw new Error(`expected non-empty string or null at ${e}`);return n}function ht(t){let e=g(t),n=k(e,"cardRef"),a=k(e,"factoUserId"),o=k(e,"factoServerWalletAddress");if(n!=null&&(I(n,"card_","cardRef"),a!=null||o!=null))throw new Error("synthetic Dev links must not expose canonical identity");return{appId:c(e,"appId"),userLinkRef:x(e,"userLinkRef","ul_"),grantStatus:c(e,"grantStatus"),pipelineReady:w(e,"pipelineReady"),scopes:Bt(e,"scopes"),...n===void 0?{}:{cardRef:n},...a===void 0?{}:{factoUserId:a},...o===void 0?{}:{factoServerWalletAddress:o}}}function St(t){let e=g(t),n=w(e,"pipelineReady"),a=e.notReadyReason,o=a==null?a:S(e,"notReadyReason",te,"payment readiness not-ready reason");if(n&&o!==void 0&&o!==null)throw new Error("expected notReadyReason only when pipelineReady is false");let s=k(e,"factoUserId"),d=k(e,"factoServerWalletAddress");return Kt(e,"payment readiness"),{appId:c(e,"appId"),userLinkRef:x(e,"userLinkRef","ul_"),readinessScope:S(e,"readinessScope",ne,"payment readiness scope"),chainId:we(e,"chainId"),protocolId:c(e,"protocolId"),assetSymbol:c(e,"assetSymbol"),spendMode:c(e,"spendMode"),pipelineReady:n,...o===void 0?{}:{notReadyReason:o},...s===void 0?{}:{factoUserId:s},...d===void 0?{}:{factoServerWalletAddress:d}}}function Ct(t){let e=g(t);return{sessionId:c(e,"sessionId"),checkoutUrl:c(e,"checkoutUrl"),status:L(e,"status","pending"),amount:c(e,"amount"),assetSymbol:c(e,"assetSymbol"),orderRef:T(e,"orderRef")}}function Rt(t){let e=g(t);return{sessionId:c(e,"sessionId"),status:Dt(e,"status"),amount:c(e,"amount"),assetSymbol:c(e,"assetSymbol"),orderRef:T(e,"orderRef"),chargeId:T(e,"chargeId"),confirmedAt:T(e,"confirmedAt")}}function ge(t){let e=g(t),n=A(e,"mandateId"),a=A(e,"userLinkRef");return{sessionId:c(e,"sessionId"),authorizationUrl:c(e,"authorizationUrl"),status:Ht(e,"status"),...n===void 0?{}:{mandateId:n},...a===void 0?{}:{userLinkRef:a},expiresAt:c(e,"expiresAt"),state:c(e,"state")}}function he(t){let e=g(t),n=A(e,"expiresAt");return{mandateId:c(e,"mandateId"),appId:c(e,"appId"),status:zt(e,"status"),allowedUseCases:Vt(e,"allowedUseCases"),limits:Tt(e.limits),paymentPath:wt(e.paymentPath),createdAt:c(e,"createdAt"),...n===void 0?{}:{expiresAt:n}}}var bt="direct",At="defaultPaymentOptionId";function _t(t){let e=g(t);ke(e,"payment options");let n=e.paymentOptions;if(!Array.isArray(n))throw new Error("expected paymentOptions array");let a=n.map(Pt).filter(d=>d.settlementPath===bt),o=Mt(e,At),s=It(a,o);return{paymentOptions:a,...s===void 0?{}:{selectedPaymentOptionId:s}}}function It(t,e){return e!==void 0&&t.some(a=>a.paymentOptionId===e)?e:(t.find(a=>a.ready)??t[0])?.paymentOptionId}function Et(t){let e=A(t,"settlementPath"),n=A(t,"spendMode"),a=e??n;if(a===void 0)throw new Error("expected settlementPath or the deprecated spendMode on a payment option");return{settlementPath:a,spendMode:n??a}}function Pt(t){let e=g(t);ke(e,"payment option");let n=A(e,"blockingReason"),a=c(e,"assetSymbol"),o=c(e,"chainLabel"),s=c(e,"protocolLabel"),{settlementPath:d,spendMode:u}=Et(e);return{paymentOptionId:Te(e,"paymentOptionId"),label:vt({assetSymbol:a,protocolLabel:s,chainLabel:o},c(e,"label")),ready:w(e,"ready"),isDefault:w(e,"isDefault"),chainId:we(e,"chainId"),chainLabel:o,protocolLabel:s,assetSymbol:a,spendMode:u,settlementPath:d,...n===void 0?{}:{blockingReason:n}}}function vt(t,e){let n=[t.assetSymbol,t.protocolLabel,t.chainLabel].map(a=>a.trim()).filter(a=>a.length>0);return n.length>0?n.join(" \xB7 "):e}function O(t){let e=g(t),n=A(e,"chargeId"),a=A(e,"txHash"),o=$t(e,"declineReason"),s=kt(e,"finalityEtaSeconds"),d=A(e,"terminalAt"),u=A(e,"updatedAt");return{paymentId:c(e,"paymentId"),mandateId:c(e,"mandateId"),merchantPaymentRef:c(e,"merchantPaymentRef"),status:qt(e,"status"),amount:c(e,"amount"),currency:c(e,"currency"),useCase:Ft(e,"useCase"),...n===void 0?{}:{chargeId:n},...a===void 0?{}:{txHash:a},...o===void 0?{}:{declineReason:o},...s===void 0?{}:{finalityEtaSeconds:s},...d===void 0?{}:{terminalAt:d},createdAt:c(e,"createdAt"),...u===void 0?{}:{updatedAt:u}}}function Tt(t){let e=g(t);return{perTxAmount:c(e,"perTxAmount"),periodAmount:c(e,"periodAmount"),period:Wt(e,"period")}}function wt(t){let e=g(t),n=A(e,"blockingReason");return{ready:w(e,"ready"),summary:c(e,"summary"),...n===void 0?{}:{blockingReason:n}}}function g(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("expected object");return t}function c(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`expected non-empty string at ${e}`);return n}function A(t,e){let n=t[e];if(n!==void 0){if(typeof n!="string"||n.length===0)throw new Error(`expected non-empty string at ${e}`);return n}}function Te(t,e){let n=c(t,e);if(!n.startsWith("fpo_"))throw new Error(`expected opaque Facto payment option id at ${e}`);return n}function Mt(t,e){if(!(t[e]===void 0||t[e]===null))return Te(t,e)}function L(t,e,n){if(t[e]!==n)throw new Error(`expected ${n} at ${e}`);return n}function w(t,e){let n=t[e];if(typeof n!="boolean")throw new Error(`expected boolean at ${e}`);return n}function we(t,e){let n=t[e];if(typeof n!="number"||!Number.isFinite(n))throw new Error(`expected finite number at ${e}`);return n}function kt(t,e){let n=t[e];if(n!==void 0){if(typeof n!="number"||!Number.isFinite(n))throw new Error(`expected finite number at ${e}`);return n}}var xt=["pending","charged","expired","cancelled"],Me=["immediate","recurring","top_up","metered"],Lt=["daily","weekly","monthly"],Ut=["pending","active","paused","revoked","expired","suspended"],Nt=["created","authorized","declined","expired"],Ot=["accepted","declined","charging","finalizing","succeeded","paid_via_coverage","failed","canceled"];function Dt(t,e){let n=t[e];if(typeof n!="string"||!xt.includes(n))throw new Error(`expected checkout status at ${e}`);return n}function Ft(t,e){return S(t,e,Me,"mandate use case")}function Wt(t,e){return S(t,e,Lt,"mandate limit period")}function zt(t,e){return S(t,e,Ut,"mandate status")}function Ht(t,e){return S(t,e,Nt,"mandate authorization status")}function qt(t,e){return S(t,e,Ot,"mandate payment status")}function $t(t,e){if(t[e]!==void 0)return S(t,e,ee,"mandate decline reason")}function Vt(t,e){let n=t[e];if(!Array.isArray(n))throw new Error(`expected mandate use case array at ${e}`);return n.map(a=>{if(typeof a!="string"||!Me.includes(a))throw new Error(`expected mandate use case array at ${e}`);return a})}function S(t,e,n,a){let o=t[e];if(typeof o!="string"||!n.includes(o))throw new Error(`expected ${a} at ${e}`);return o}function T(t,e){let n=t[e];if(n==null)return null;if(typeof n!="string")throw new Error(`expected string or null at ${e}`);return n}function K(t,e){let n=t[e];if(n===null)return null;if(typeof n!="string")throw new Error(`expected required string or null at ${e}`);return n}function Bt(t,e){let n=t[e];if(!Array.isArray(n)||n.some(a=>typeof a!="string"))throw new Error(`expected string array at ${e}`);return n}function Kt(t,e){let a=["pipelineId","selectedPipelineId","paymentRouteId","routeId","routeSelector"].find(o=>t[o]!==void 0);if(a)throw new Error(`unsafe ${e} field: ${a}`)}function ke(t,e){let a=["userId","factoUserId","cardId","routeId","vaultKind","serverWallet","factoServerWalletAddress","pathSnapshot","paymentPathSnapshot","pipelineId","selectedPipelineId","paymentRouteId","routeSelector"].find(o=>t[o]!==void 0);if(a)throw new Error(`unsafe ${e} field: ${a}`)}async function Jt(t){try{return await t.json()}catch{return await t.text().catch(()=>null)}}function G(t){return t.replace(/\/+$/,"")}function jt(t){let e;try{e=new URL(t)}catch{l("merchantOrigin must be an absolute http(s) origin")}e.protocol!=="http:"&&e.protocol!=="https:"&&l("merchantOrigin must be an absolute http(s) origin");let n=e.origin;return t!==n&&t!==`${n}/`&&l("merchantOrigin must be an absolute http(s) origin"),n}function l(t){throw new R("FACTO_CONFIG_INVALID",t,{retryable:!1})}function Yt(t){let e=globalThis.btoa;if(e)return e(t);let n=globalThis.Buffer;if(n)return n.from(t).toString("base64");l("No base64 encoder is available in this runtime")}function Gt(t,e,n=Math.floor(Date.now()/1e3)){e||l("webhook secret is required"),(!Number.isSafeInteger(n)||n<0)&&l("webhook timestamp must be a non-negative safe integer");let a=(0,U.createHmac)("sha256",e).update(`${n}.`).update(t).digest("hex");return`t=${n},v1=${a}`}function Zt(t,e,n,a=300){n||l("webhook secret is required");let o=e.split(",").map(p=>p.trim()),s,d=[];for(let p of o){let f=p.indexOf("=");if(f===-1)continue;let r=p.slice(0,f),i=p.slice(f+1);r==="t"?s=Number(i):r==="v1"&&d.push(i)}if(s===void 0||!Number.isFinite(s)||Math.abs(Date.now()/1e3-s)>a||d.length===0)return!1;let u=(0,U.createHmac)("sha256",n).update(`${s}.`).update(t).digest();return d.some(p=>{let f;try{f=Buffer.from(p,"hex")}catch{return!1}return f.length===u.length&&(0,U.timingSafeEqual)(f,u)})}var m=class extends Error{code;details;constructor(e,n,a={}){super(n),this.name="FactoConnectHintError",this.code=e,this.details=a.details}},Xt="facto";async function Qt(t){if(t===null||typeof t!="object")throw new m("FACTO_HINT_INPUT_INVALID","verifyFactoCardProgramConnectHint requires an input object");let e=j(t.connectHint,"connectHint"),n=j(t.audience,"audience"),a=t.issuer===void 0?Xt:j(t.issuer,"issuer"),o=cn(t.clockToleranceSeconds),s=Math.floor(un(t.now)/1e3),{headerB64:d,payloadB64:u,signature:p}=en(e),f=Q(Se(d,"header"),"FACTO_HINT_MALFORMED","connect hint header");if(f.alg!=="EdDSA")throw new m("FACTO_HINT_UNSUPPORTED_ALG","connect hint JWS alg must be EdDSA",{details:{alg:f.alg}});let r=typeof f.kid=="string"?f.kid:void 0,i=await tn(t.jwks),y=on(i,r),E=mn(`${d}.${u}`);if(!await sn(E,p,y))throw new m("FACTO_HINT_SIGNATURE_INVALID","connect hint signature does not verify against the Facto JWKS");let _=dn(Se(u,"payload"));if(_.iss!==a)throw new m("FACTO_HINT_ISSUER_MISMATCH","connect hint issuer mismatch",{details:{expected:a,actual:_.iss}});if(_.aud!==n)throw new m("FACTO_HINT_AUDIENCE_MISMATCH","connect hint audience mismatch",{details:{expected:n,actual:_.aud}});if(s>_.exp+o)throw new m("FACTO_HINT_EXPIRED","connect hint has expired",{details:{exp:_.exp,now:s}});return{programRef:_.program_ref,pairwiseSubject:_.sub,nonce:_.nonce,expiresAt:new Date(_.exp*1e3).toISOString()}}function en(t){let e=t.split(".");if(e.length!==3)throw new m("FACTO_HINT_MALFORMED","connect hint is not a compact JWS (expected three segments)");let[n,a,o]=e;if(!n||!a||!o)throw new m("FACTO_HINT_MALFORMED","connect hint has an empty JWS segment");return{headerB64:n,payloadB64:a,signature:xe(o,"signature")}}function Se(t,e){let n=new TextDecoder().decode(xe(t,e));try{return JSON.parse(n)}catch(a){throw new m("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid JSON`,{details:a})}}async function tn(t){if(t==null)throw new m("FACTO_HINT_INPUT_INVALID","jwks is required");return J(typeof t=="function"?await t():typeof t=="string"?await rn(t):t)}var nn=5e3,D=64*1024;async function rn(t){let e;try{e=new URL(t)}catch{throw new m("FACTO_HINT_JWKS_INVALID",`JWKS url is not a valid URL: ${t}`)}if(e.protocol!=="https:")throw new m("FACTO_HINT_JWKS_INVALID",`JWKS url must use https: (got ${e.protocol})`,{details:{protocol:e.protocol}});let n=new AbortController,a=setTimeout(()=>n.abort(),nn),o,s;try{try{o=await fetch(t,{method:"GET",headers:{accept:"application/json"},redirect:"follow",signal:n.signal})}catch(u){throw new m("FACTO_HINT_JWKS_INVALID",`failed to fetch Facto JWKS from ${t}`,{details:u})}if(!o.ok)throw new m("FACTO_HINT_JWKS_INVALID",`Facto JWKS request failed with status ${o.status}`,{details:{status:o.status}});let d=Number(o.headers.get("content-length"));if(Number.isFinite(d)&&d>D)throw new m("FACTO_HINT_JWKS_INVALID",`Facto JWKS response exceeds ${D} bytes`,{details:{contentLength:d}});try{s=await o.text()}catch(u){throw new m("FACTO_HINT_JWKS_INVALID","Facto JWKS response could not be read",{details:u})}}finally{clearTimeout(a)}if(s.length>D)throw new m("FACTO_HINT_JWKS_INVALID",`Facto JWKS response exceeds ${D} bytes`,{details:{bytes:s.length}});try{return JSON.parse(s)}catch(d){throw new m("FACTO_HINT_JWKS_INVALID","Facto JWKS response was not valid JSON",{details:d})}}function J(t){let e=Q(t,"FACTO_HINT_JWKS_INVALID","JWKS");if(!Array.isArray(e.keys))throw new m("FACTO_HINT_JWKS_INVALID",'JWKS "keys" must be an array');return{keys:e.keys.map(an)}}function an(t){let e=typeof t=="object"&&t!==null?t:{};return{kty:typeof e.kty=="string"?e.kty:"",crv:typeof e.crv=="string"?e.crv:"",x:typeof e.x=="string"?e.x:"",...typeof e.kid=="string"?{kid:e.kid}:{},...typeof e.alg=="string"?{alg:e.alg}:{},...typeof e.use=="string"?{use:e.use}:{}}}function on(t,e){let n=t.keys.filter(a=>a.kty==="OKP"&&a.crv==="Ed25519"&&a.x.length>0);if(n.length===0)throw new m("FACTO_HINT_JWKS_INVALID","Facto JWKS has no usable Ed25519 signing key");if(e!==void 0){let a=n.filter(o=>o.kid===e);if(a.length>0)return a}return n}async function sn(t,e,n){let a=pn();for(let o of n){let s;try{s=await a.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:o.x},{name:"Ed25519"},!1,["verify"])}catch{continue}try{if(await a.verify({name:"Ed25519"},s,e,t))return!0}catch{continue}}return!1}function dn(t){let e=Q(t,"FACTO_HINT_CLAIMS_INVALID","connect hint claims");return{iss:M(e,"iss"),aud:M(e,"aud"),sub:M(e,"sub"),program_ref:M(e,"program_ref"),nonce:M(e,"nonce"),iat:Ce(e,"iat"),exp:Ce(e,"exp")}}function j(t,e){if(typeof t!="string"||t.length===0)throw new m("FACTO_HINT_INPUT_INVALID",`${e} must be a non-empty string`);return t}function cn(t){if(t===void 0)return 0;if(typeof t!="number"||!Number.isFinite(t)||t<0)throw new m("FACTO_HINT_INPUT_INVALID","clockToleranceSeconds must be a non-negative finite number");return t}function un(t){if(t===void 0)return Date.now();if(t instanceof Date){let e=t.getTime();if(Number.isNaN(e))throw new m("FACTO_HINT_INPUT_INVALID","now is an invalid Date");return e}if(typeof t=="number"&&Number.isFinite(t))return t;throw new m("FACTO_HINT_INPUT_INVALID","now must be a Date or unix milliseconds number")}function Q(t,e,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new m(e,`${n} must be a JSON object`);return t}function M(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new m("FACTO_HINT_CLAIMS_INVALID",`connect hint claim "${e}" must be a non-empty string`);return n}function Ce(t,e){let n=t[e];if(typeof n!="number"||!Number.isFinite(n))throw new m("FACTO_HINT_CLAIMS_INVALID",`connect hint claim "${e}" must be a finite number`);return n}function xe(t,e){if(!/^[A-Za-z0-9_-]*$/.test(t))throw new m("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid base64url`);let n=t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4);return ln(n,e)}function ln(t,e){let n=globalThis.atob;if(n){let o;try{o=n(t)}catch(d){throw new m("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid base64url`,{details:d})}let s=new Uint8Array(o.length);for(let d=0;d<o.length;d+=1)s[d]=o.charCodeAt(d);return s}let a=globalThis.Buffer;if(a)return new Uint8Array(a.from(t,"base64"));throw new m("FACTO_HINT_INPUT_INVALID","No base64 decoder is available in this runtime")}function mn(t){let e=new TextEncoder().encode(t),n=new Uint8Array(e.length);return n.set(e),n}function pn(){let t=globalThis.crypto;if(t?.subtle)return t.subtle;throw new m("FACTO_HINT_INPUT_INVALID","Web Crypto (crypto.subtle) is not available in this runtime")}var fn=_e;