@facto-to/connect 0.0.1-beta.5 → 0.0.1-beta1
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 +13 -117
- package/dist/browser/index.cjs +5 -5
- package/dist/browser/index.d.cts +31 -1
- package/dist/browser/index.d.ts +31 -1
- package/dist/browser/index.js +4 -4
- package/dist/server/index.cjs +1 -1
- package/dist/server/index.d.cts +233 -33
- package/dist/server/index.d.ts +233 -33
- package/dist/server/index.js +1 -1
- package/dist/testing/index.cjs +1 -1
- package/dist/testing/index.d.cts +12 -1
- package/dist/testing/index.d.ts +12 -1
- package/dist/testing/index.js +1 -1
- package/package.json +5 -8
- package/dist/index.d-DE9GmLfU.d.cts +0 -114
- package/dist/index.d-DE9GmLfU.d.ts +0 -114
package/dist/server/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHmac as me,timingSafeEqual as ve}from"node:crypto";var Z=["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 X=["payment_route_not_provisioned","protocol_config_incomplete"],Q=["account_default","mandate_pinned"];var be=["psp_connect_sandbox","psp_mandate_sandbox","psp_billing_sandbox"],ee={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 ee[t].includes("payments.execute")}var _e={dev:{clientIdPrefix:"dev_pspid_",clientSecretPrefix:"dev_pspsk_"},test:{clientIdPrefix:"test_pspid_"},lab:{clientIdPrefix:"lab_pspid_"}},Ie="psp";function Ee(t,e){return{...t,...e.ref===void 0?{}:{subMerchantRef:e.ref},...e.displayName===void 0?{}:{subMerchantDisplayName:e.displayName}}}function Pe(t){return{...t.subMerchantRef==null?{}:{ref:t.subMerchantRef},...t.subMerchantDisplayName==null?{}:{displayName:t.subMerchantDisplayName}}}function F(t){return t==="sandbox"?"dev":t}var W=Object.freeze({dev:"https://dev-api.facto.to",production:"https://api.facto.to"}),M=Object.freeze({dev:"https://dev.facto.to",production:"https://app.facto.to"}),Te=Object.freeze({dev:Object.freeze(["dev_mcid_","dev_pspid_","dev_cpid_"]),production:Object.freeze(["mcid_","pspid_","cpid_"])});function we(t){if(typeof t=="string"){for(let e of["dev","production"])for(let n of Te[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"}),A=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 Me(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 ke(t,e){return t<=0?Promise.resolve():new Promise((n,a)=>{if(e?.aborted){a(new A("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}));return}let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),a(new A("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}))};e?.addEventListener("abort",s,{once:!0})})}async function xe(t,e={}){let n=e.maxRetries??2,a=e.baseDelayMs??200,o=e.maxDelayMs??5e3,s=e.respectRetryAfter??!0,d=e.sleep??ke,u=0;for(;;)try{return await t()}catch(p){if(!(p instanceof A)||!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 Le(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=qt(t.merchantOrigin),n=J(t.hostedConnectUrl);P(n,M,"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 Ue(t){let e=He(t),n=`Basic ${$t(`${e.clientId}:${e.clientSecret}`)}`,a=(r,i)=>R(e,r,{code:i.code,state:i.state,nonce:i.nonce},n,lt),o=(r,i)=>R(e,r,ut(e,i),n,mt),s=(r,i)=>R(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,de),d=(r,i)=>C(e,`${r}/${encodeURIComponent(i)}`,n,de),u=(r,i)=>C(e,`${r}/${encodeURIComponent(i)}`,n,ce),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),R(e,r,y,n,N,{"Idempotency-Key":i.idempotencyKey},[402])},f=(r,i)=>C(e,`${r}/${encodeURIComponent(i)}`,n,N);return{createHostedConnectUrl(r){let i=r.hostedConnectUrl??e.hostedConnectUrl;if(r.hostedConnectUrl!==void 0){let y=P(r.hostedConnectUrl,M,"hostedConnectUrl",!0);y!==void 0&&y!==F(e.environment)&&l("hostedConnectUrl conflicts with the configured environment")}return Le({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"),R(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,pt)},getCheckoutSession(r){return C(e,`${h.checkoutSessions}/${encodeURIComponent(r)}`,n,ft)},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"),R(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,ht)},createMandatePayment(r){return p(h.payments,r)},getMandatePayment(r){return f(h.payments,r)},onStatus(r,i,y){return De(()=>C(e,`${h.payments}/${encodeURIComponent(r)}`,n,N),i,y)},revokeUserLink(r){return ae(e,`/api/merchant/user-links/${encodeURIComponent(r)}`,n)},listMerchantPayments(r={}){return C(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,N))},listPaymentAuthorizations(r={}){return C(e,z("/api/merchant/payment-authorizations",{limit:r.limit,startingAfter:r.startingAfter,userLinkRef:r.userLinkRef,status:r.status}),n,i=>H(i,ce))},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),R(e,"/api/merchant/refunds",i,n,q,{"Idempotency-Key":r.idempotencyKey},[402])},getRefund(r){return C(e,`/api/merchant/refunds/${encodeURIComponent(r)}`,n,q)},listRefunds(r={}){return C(e,z("/api/merchant/refunds",{limit:r.limit,startingAfter:r.startingAfter,paymentId:r.paymentId}),n,i=>H(i,q))},createWebhookEndpoint(r){return R(e,"/api/merchant/webhook-endpoints",{url:r.url,enabledEvents:r.enabledEvents},n,oe)},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(K)})},getWebhookEndpoint(r){return C(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n,K)},deleteWebhookEndpoint(r){return ae(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n)},rotateWebhookSecret(r){return R(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}/rotate-secret`,{},n,oe)},getDevCapabilities(){return U(e,"getDevCapabilities"),C(e,"/api/dev/capabilities",n,at)},fundDevUser(r){return U(e,"fundDevUser"),te(r.userLinkRef),ne(r.amount),re(r.idempotencyKey),R(e,"/api/dev/faucet/usdc",{userLinkRef:r.userLinkRef,amount:r.amount},n,it,{"Idempotency-Key":r.idempotencyKey})},simulateDevCharge(r){return U(e,"simulateDevCharge"),te(r.userLinkRef),r.cardRef!==void 0&&I(r.cardRef,"card_","cardRef"),ne(r.amount),Ve(r.scenario),r.merchantReference!==void 0&&(typeof r.merchantReference!="string"||r.merchantReference.length>120)&&l("merchantReference must not exceed 120 characters"),re(r.idempotencyKey),R(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,se,{"Idempotency-Key":r.idempotencyKey})},getDevSimulation(r){return U(e,"getDevSimulation"),I(r,"sim_","simulationId"),C(e,`/api/dev/simulations/${encodeURIComponent(r)}`,n,se)},sendWebhookTestDelivery(r){return qe(e),$e(r.webhookEndpointId),r.message!==void 0&&(typeof r.message!="string"||r.message.length>120)&&l("webhook test message must not exceed 120 characters"),R(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r.webhookEndpointId)}/test-delivery`,r.message===void 0?{}:{message:r.message},n,dt)}}}var Ne=new Set(["declined","succeeded","paid_via_coverage","failed","canceled"]);function Oe(t){return Ne.has(t)}async function De(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(;;){Fe(u);let i=await t();if(i.status!==r&&(r=i.status,e(i)),Oe(i.status))return i;let y=p-Date.now();if(y<=0)return i;await We(Math.min(f,y),u),f=Math.min(f*s,o)}}function Fe(t){if(t?.aborted)throw new A("FACTO_STATUS_POLL_ABORTED","mandate payment polling aborted",{retryable:!1})}function We(t,e){return new Promise((n,a)=>{let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),a(new A("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 ze=Object.freeze(["dev","production","sandbox"]);function He(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&&!ze.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,W,"apiBaseUrl",!1):void 0,a=t.hostedConnectUrl?P(t.hostedConnectUrl,M,"hostedConnectUrl",!0):void 0;n!==void 0&&a!==void 0&&n!==a&&l("apiBaseUrl and hostedConnectUrl target different Facto environments");let o=we(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=F(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=J(t.apiBaseUrl??W[d]),p=J(t.hostedConnectUrl??M[d]),f=P(u,W,"apiBaseUrl",!1);return P(p,M,"hostedConnectUrl",!0),Be(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 U(t,e){F(t.environment)!=="dev"&&l(`${e} is available only in the sandbox/dev environment`)}function qe(t){F(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 te(t){I(t,"ul_","userLinkRef")}function $e(t){(typeof t!="string"||!/^we_[A-Za-z0-9]+$/.test(t))&&l("webhookEndpointId must be an opaque we_ reference")}function ne(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 Ve(t){(typeof t!="string"||!ye.includes(t))&&l("unknown Dev simulation scenario")}function re(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 Be(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 R(t,e,n,a,o,s={},d=[]){return fe(t,()=>Y(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 j(u);return pe(u,o)}),s["Idempotency-Key"]!==void 0)}async function C(t,e,n,a){return fe(t,()=>Y(t,`${t.apiBaseUrl}${e}`,{method:"GET",headers:{authorization:n}},async o=>{if(!o.ok)throw await j(o);return pe(o,a)}),!0)}async function pe(t,e){try{return e(await t.json())}catch(n){throw new A("FACTO_ENGINE_RESPONSE_INVALID","Facto Engine returned an invalid response",{retryable:!1,details:n})}}async function ae(t,e,n){return Y(t,`${t.apiBaseUrl}${e}`,{method:"DELETE",headers:{authorization:n}},async a=>{if(!a.ok)throw await j(a)})}async function j(t){return new A("FACTO_ENGINE_REQUEST_FAILED",`Facto Engine request failed with status ${t.status}`,{retryable:t.status===429||t.status>=500,status:t.status,details:await Ht(t),retryAfterSeconds:Me(t)})}function fe(t,e,n){return n?xe(e,{...t.retry,signal:t.signal??t.retry?.signal}):e()}async function Y(t,e,n,a){return t.timeoutMs===void 0&&t.signal===void 0?a(await t.transport(e,n)):Ke(t,e,n,a)}function Ke(t,e,n,a){let o=new AbortController;return t.signal?.aborted?Promise.reject(new A("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 A("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 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:T(n,"hasMore")}}var Je=["pending","succeeded","failed"],je=["requested_by_customer","duplicate","fraudulent","other"];function Ye(t,e){let n=t[e];if(typeof n!="string"||!Je.includes(n))throw new Error(`expected refund status at ${e}`);return n}function Ge(t,e){let n=t[e];if(n!==void 0){if(typeof n!="string"||!je.includes(n))throw new Error(`expected refund reason at ${e}`);return n}}function q(t){let e=g(t),n=Ge(e,"reason"),a=b(e,"merchantRefundRef");return{refundId:c(e,"refundId"),paymentId:c(e,"paymentId"),status:Ye(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 Ze=["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 Xe(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"||!Ze.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:c(e,"webhookEndpointId"),url:c(e,"url"),enabledEvents:Xe(e,"enabledEvents"),status:n,createdAt:c(e,"createdAt")}}function oe(t){let e=K(t),n=g(t);return{...e,secret:c(n,"secret")}}var D=["fixtures","synthetic_identity","faucet","simulation","money_loop","webhook_test_delivery"],Qe=["unavailable","degraded","ready"],et=["contract","implemented","deployed","verified"],ye=["approved","declined_setup","declined_limit","payment_failed"],tt=["pre_admission","onchain_test_assets"],nt=["accepted","processing","succeeded","failed","declined"],rt=["accepted","broadcast","confirmed","failed"];function at(t){let e=g(t),n=e.capabilities;if(!Array.isArray(n)||n.length!==D.length)throw new Error("expected exactly six Dev capabilities");let a=n.map(ot),o=new Set(a.map(s=>s.name));if(o.size!==D.length)throw new Error("expected each Dev capability exactly once");for(let s of D)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 ot(t){let e=g(t),n=S(e,"name",D,"Dev capability name"),a=S(e,"status",Qe,"Dev capability status"),o=S(e,"evidenceLevel",et,"Dev evidence level"),s=v(e,"reasonCode"),d=v(e,"verifiedAt");if(a==="ready"&&(o!=="verified"||d===null))throw new Error("ready Dev capability requires verified evidence");let u=ct(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 st(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 it(t){let e=g(t);return{faucetTransferId:x(e,"faucetTransferId","sft_"),userLinkRef:x(e,"userLinkRef","ul_"),amount:st(e.amount),status:S(e,"status",rt,"Dev faucet status"),createdAt:c(e,"createdAt")}}function se(t){let e=g(t);return{simulationId:x(e,"simulationId","sim_"),scenario:S(e,"scenario",ye,"Dev scenario"),executionMode:S(e,"executionMode",tt,"Dev execution mode"),status:S(e,"status",nt,"Dev simulation status"),reasonCode:$(e,"reasonCode"),authorizationRef:$(e,"authorizationRef"),chargeRef:$(e,"chargeRef"),createdAt:c(e,"createdAt"),updatedAt:c(e,"updatedAt")}}function dt(t){let e=g(t);return{eventId:ie(e,"eventId","evt_"),deliveryId:ie(e,"deliveryId","wd_"),status:L(e,"status","queued"),createdAt:c(e,"createdAt")}}function ct(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 ie(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 ut(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 lt(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:T(e,"pipelineReady"),scopes:Wt(e,"scopes"),...n===void 0?{}:{cardRef:n},...a===void 0?{}:{factoUserId:a},...o===void 0?{}:{factoServerWalletAddress:o}}}function mt(t){let e=g(t),n=T(e,"pipelineReady"),a=e.notReadyReason,o=a==null?a:S(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"),d=k(e,"factoServerWalletAddress");return zt(e,"payment readiness"),{appId:c(e,"appId"),userLinkRef:x(e,"userLinkRef","ul_"),readinessScope:S(e,"readinessScope",Q,"payment readiness scope"),chainId:he(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 pt(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:v(e,"orderRef")}}function ft(t){let e=g(t);return{sessionId:c(e,"sessionId"),status:kt(e,"status"),amount:c(e,"amount"),assetSymbol:c(e,"assetSymbol"),orderRef:v(e,"orderRef"),chargeId:v(e,"chargeId"),confirmedAt:v(e,"confirmedAt")}}function de(t){let e=g(t),n=b(e,"mandateId"),a=b(e,"userLinkRef");return{sessionId:c(e,"sessionId"),authorizationUrl:c(e,"authorizationUrl"),status:Nt(e,"status"),...n===void 0?{}:{mandateId:n},...a===void 0?{}:{userLinkRef:a},expiresAt:c(e,"expiresAt"),state:c(e,"state")}}function ce(t){let e=g(t),n=b(e,"expiresAt");return{mandateId:c(e,"mandateId"),appId:c(e,"appId"),status:Ut(e,"status"),allowedUseCases:Ft(e,"allowedUseCases"),limits:At(e.limits),paymentPath:_t(e.paymentPath),createdAt:c(e,"createdAt"),...n===void 0?{}:{expiresAt:n}}}var yt="direct",gt="defaultPaymentOptionId";function ht(t){let e=g(t);Ce(e,"payment options");let n=e.paymentOptions;if(!Array.isArray(n))throw new Error("expected paymentOptions array");let a=n.map(Rt).filter(d=>d.settlementPath===yt),o=It(e,gt),s=St(a,o);return{paymentOptions:a,...s===void 0?{}:{selectedPaymentOptionId:s}}}function St(t,e){return e!==void 0&&t.some(a=>a.paymentOptionId===e)?e:(t.find(a=>a.ready)??t[0])?.paymentOptionId}function Ct(t){let e=b(t,"settlementPath"),n=b(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 Rt(t){let e=g(t);Ce(e,"payment option");let n=b(e,"blockingReason"),a=c(e,"assetSymbol"),o=c(e,"chainLabel"),s=c(e,"protocolLabel"),{settlementPath:d,spendMode:u}=Ct(e);return{paymentOptionId:ge(e,"paymentOptionId"),label:bt({assetSymbol:a,protocolLabel:s,chainLabel:o},c(e,"label")),ready:T(e,"ready"),isDefault:T(e,"isDefault"),chainId:he(e,"chainId"),chainLabel:o,protocolLabel:s,assetSymbol:a,spendMode:u,settlementPath:d,...n===void 0?{}:{blockingReason:n}}}function bt(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 N(t){let e=g(t),n=b(e,"chargeId"),a=b(e,"txHash"),o=Dt(e,"declineReason"),s=Et(e,"finalityEtaSeconds"),d=b(e,"terminalAt"),u=b(e,"updatedAt");return{paymentId:c(e,"paymentId"),mandateId:c(e,"mandateId"),merchantPaymentRef:c(e,"merchantPaymentRef"),status:Ot(e,"status"),amount:c(e,"amount"),currency:c(e,"currency"),useCase:xt(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 At(t){let e=g(t);return{perTxAmount:c(e,"perTxAmount"),periodAmount:c(e,"periodAmount"),period:Lt(e,"period")}}function _t(t){let e=g(t),n=b(e,"blockingReason");return{ready:T(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 b(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 ge(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 It(t,e){if(!(t[e]===void 0||t[e]===null))return ge(t,e)}function L(t,e,n){if(t[e]!==n)throw new Error(`expected ${n} at ${e}`);return n}function T(t,e){let n=t[e];if(typeof n!="boolean")throw new Error(`expected boolean at ${e}`);return n}function he(t,e){let n=t[e];if(typeof n!="number"||!Number.isFinite(n))throw new Error(`expected finite number at ${e}`);return n}function Et(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 Pt=["pending","charged","expired","cancelled"],Se=["immediate","recurring","top_up","metered"],vt=["daily","weekly","monthly"],Tt=["pending","active","paused","revoked","expired","suspended"],wt=["created","authorized","declined","expired"],Mt=["accepted","declined","charging","finalizing","succeeded","paid_via_coverage","failed","canceled"];function kt(t,e){let n=t[e];if(typeof n!="string"||!Pt.includes(n))throw new Error(`expected checkout status at ${e}`);return n}function xt(t,e){return S(t,e,Se,"mandate use case")}function Lt(t,e){return S(t,e,vt,"mandate limit period")}function Ut(t,e){return S(t,e,Tt,"mandate status")}function Nt(t,e){return S(t,e,wt,"mandate authorization status")}function Ot(t,e){return S(t,e,Mt,"mandate payment status")}function Dt(t,e){if(t[e]!==void 0)return S(t,e,Z,"mandate decline reason")}function Ft(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"||!Se.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 v(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 $(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 Wt(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 zt(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 Ce(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 Ht(t){try{return await t.json()}catch{return await t.text().catch(()=>null)}}function J(t){return t.replace(/\/+$/,"")}function qt(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 A("FACTO_CONFIG_INVALID",t,{retryable:!1})}function $t(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 un(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=me("sha256",e).update(`${n}.`).update(t).digest("hex");return`t=${n},v1=${a}`}function ln(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=me("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&&ve(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}},Vt="facto";async function mn(t){if(t===null||typeof t!="object")throw new m("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?Vt:B(t.issuer,"issuer"),o=Qt(t.clockToleranceSeconds),s=Math.floor(en(t.now)/1e3),{headerB64:d,payloadB64:u,signature:p}=Bt(e),f=G(ue(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 Kt(t.jwks),y=Gt(i,r),E=nn(`${d}.${u}`);if(!await Zt(E,p,y))throw new m("FACTO_HINT_SIGNATURE_INVALID","connect hint signature does not verify against the Facto JWKS");let _=Xt(ue(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 Bt(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:Re(o,"signature")}}function ue(t,e){let n=new TextDecoder().decode(Re(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 Kt(t){if(t==null)throw new m("FACTO_HINT_INPUT_INVALID","jwks is required");return V(typeof t=="function"?await t():typeof t=="string"?await jt(t):t)}var Jt=5e3,O=64*1024;async function jt(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(),Jt),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>O)throw new m("FACTO_HINT_JWKS_INVALID",`Facto JWKS response exceeds ${O} 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>O)throw new m("FACTO_HINT_JWKS_INVALID",`Facto JWKS response exceeds ${O} 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 V(t){let e=G(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(Yt)}}function Yt(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 Gt(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 Zt(t,e,n){let a=rn();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 Xt(t){let e=G(t,"FACTO_HINT_CLAIMS_INVALID","connect hint claims");return{iss:w(e,"iss"),aud:w(e,"aud"),sub:w(e,"sub"),program_ref:w(e,"program_ref"),nonce:w(e,"nonce"),iat:le(e,"iat"),exp:le(e,"exp")}}function B(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 Qt(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 en(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 G(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 w(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 le(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 Re(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 tn(n,e)}function tn(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 nn(t){let e=new TextEncoder().encode(t),n=new Uint8Array(e.length);return n.set(e),n}function rn(){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 pn=Ue;export{W as FACTO_CONNECT_API_BASE_URLS,M as FACTO_CONNECT_HOSTED_URLS,m as FactoConnectHintError,A as FactoConnectServerError,be as PSP_CAPABILITY_TEMPLATES,_e as PSP_CREDENTIAL_KEYSPACE,ee as PSP_CREDENTIAL_SCOPES,Ie as PSP_PARTNER_ROLE_TYPE,Le as buildHostedConnectUrl,Ae as carriesMoneyVerb,Ue as createFactoConnectServer,pn as default,we as factoConnectEnvironmentFromClientId,Oe as isTerminalMandatePaymentStatus,un as signWebhookPayload,Pe as subMerchantOf,mn as verifyFactoCardProgramConnectHint,ln as verifyWebhookSignature,xe as withServerRetry,Ee as withSubMerchant};
|
|
1
|
+
import{createHmac as ue,timingSafeEqual as Ce}from"node:crypto";var Z=["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 Q=["payment_route_not_provisioned","protocol_config_incomplete"];function K(t){return t==="sandbox"?"dev":t}var F=Object.freeze({dev:"https://dev-api.facto.to",production:"https://api.facto.to"}),T=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"}),b=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 Se(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 be(t,e){return t<=0?Promise.resolve():new Promise((n,a)=>{if(e?.aborted){a(new b("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}));return}let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),a(new b("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}))};e?.addEventListener("abort",s,{once:!0})})}async function Re(t,e={}){let n=e.maxRetries??2,a=e.baseDelayMs??200,o=e.maxDelayMs??5e3,s=e.respectRetryAfter??!0,d=e.sleep??be,u=0;for(;;)try{return await t()}catch(m){if(!(m instanceof b)||!m.retryable||u>=n)throw m;u+=1;let r=s&&typeof m.retryAfterSeconds=="number"?m.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:m,delayMs:L}),await d(L,e.signal)}}function Ae(t){t.appId||f("appId is required"),t.state||f("state is required"),t.nonce||f("nonce is required"),t.hostedConnectUrl||f("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);v(e,T,"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 Ie(t){let e=ke(t),n=`Basic ${kt(`${e.clientId}:${e.clientSecret}`)}`,a=(r,i)=>R(e,r,{code:i.code,state:i.state,nonce:i.nonce},n,et),o=(r,i)=>R(e,r,Xe(e,i),n,tt),s=(r,i)=>R(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,se),d=(r,i)=>S(e,`${r}/${encodeURIComponent(i)}`,n,se),u=(r,i)=>S(e,`${r}/${encodeURIComponent(i)}`,n,ie),m=(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),R(e,r,y,n,N,{"Idempotency-Key":i.idempotencyKey},[402])},p=(r,i)=>S(e,`${r}/${encodeURIComponent(i)}`,n,N);return{createHostedConnectUrl(r){let i=r.hostedConnectUrl??e.hostedConnectUrl;if(r.hostedConnectUrl!==void 0){let y=v(r.hostedConnectUrl,T,"hostedConnectUrl",!0);y!==void 0&&y!==e.environment&&f("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})},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 m(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&&_(r.userLinkRef,"ul_","userLinkRef"),R(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,nt)},getCheckoutSession(r){return S(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&&_(r.userLinkRef,"ul_","userLinkRef"),R(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,st)},createMandatePayment(r){return m(h.payments,r)},getMandatePayment(r){return p(h.payments,r)},onStatus(r,i,y){return Ee(()=>S(e,`${h.payments}/${encodeURIComponent(r)}`,n,N),i,y)},revokeUserLink(r){return ne(e,`/api/merchant/user-links/${encodeURIComponent(r)}`,n)},listMerchantPayments(r={}){return S(e,W("/api/merchant/payments",{limit:r.limit,startingAfter:r.startingAfter,createdAfter:r.createdAfter,createdBefore:r.createdBefore,authorizationId:r.authorizationId,status:r.status}),n,i=>z(i,N))},listPaymentAuthorizations(r={}){return S(e,W("/api/merchant/payment-authorizations",{limit:r.limit,startingAfter:r.startingAfter,userLinkRef:r.userLinkRef,status:r.status}),n,i=>z(i,ie))},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),R(e,"/api/merchant/refunds",i,n,H,{"Idempotency-Key":r.idempotencyKey},[402])},getRefund(r){return S(e,`/api/merchant/refunds/${encodeURIComponent(r)}`,n,H)},listRefunds(r={}){return S(e,W("/api/merchant/refunds",{limit:r.limit,startingAfter:r.startingAfter,paymentId:r.paymentId}),n,i=>z(i,H))},createWebhookEndpoint(r){return R(e,"/api/merchant/webhook-endpoints",{url:r.url,enabledEvents:r.enabledEvents},n,re)},listWebhookEndpoints(){return S(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(B)})},getWebhookEndpoint(r){return S(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n,B)},deleteWebhookEndpoint(r){return ne(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n)},rotateWebhookSecret(r){return R(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}/rotate-secret`,{},n,re)},getDevCapabilities(){return U(e,"getDevCapabilities"),S(e,"/api/dev/capabilities",n,Ke)},fundDevUser(r){return U(e,"fundDevUser"),X(r.userLinkRef),ee(r.amount),te(r.idempotencyKey),R(e,"/api/dev/faucet/usdc",{userLinkRef:r.userLinkRef,amount:r.amount},n,Ye,{"Idempotency-Key":r.idempotencyKey})},simulateDevCharge(r){return U(e,"simulateDevCharge"),X(r.userLinkRef),r.cardRef!==void 0&&_(r.cardRef,"card_","cardRef"),ee(r.amount),Le(r.scenario),r.merchantReference!==void 0&&(typeof r.merchantReference!="string"||r.merchantReference.length>120)&&f("merchantReference must not exceed 120 characters"),te(r.idempotencyKey),R(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,ae,{"Idempotency-Key":r.idempotencyKey})},getDevSimulation(r){return U(e,"getDevSimulation"),_(r,"sim_","simulationId"),S(e,`/api/dev/simulations/${encodeURIComponent(r)}`,n,ae)},sendWebhookTestDelivery(r){return Me(e),xe(r.webhookEndpointId),r.message!==void 0&&(typeof r.message!="string"||r.message.length>120)&&f("webhook test message must not exceed 120 characters"),R(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r.webhookEndpointId)}/test-delivery`,r.message===void 0?{}:{message:r.message},n,Ze)}}}var _e=new Set(["declined","succeeded","paid_via_coverage","failed","canceled"]);function ve(t){return _e.has(t)}async function Ee(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,m=Date.now()+d,p=a,r;for(;;){we(u);let i=await t();if(i.status!==r&&(r=i.status,e(i)),ve(i.status))return i;let y=m-Date.now();if(y<=0)return i;await Pe(Math.min(p,y),u),p=Math.min(p*s,o)}}function we(t){if(t?.aborted)throw new b("FACTO_STATUS_POLL_ABORTED","mandate payment polling aborted",{retryable:!1})}function Pe(t,e){return new Promise((n,a)=>{let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),a(new b("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 Te=Object.freeze(["dev","production","sandbox"]);function ke(t){t.appId||f("appId is required"),t.clientId||f("clientId is required"),t.clientSecret||f("clientSecret is required");let e=t.environment;(e===void 0||!Te.includes(e))&&f("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&&f("provide either transport or fetch, not both"),t.timeoutMs!==void 0&&(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<=0)&&f("timeoutMs must be a positive safe integer");let n=t.apiBaseUrl?v(t.apiBaseUrl,F,"apiBaseUrl",!1):void 0,a=t.hostedConnectUrl?v(t.hostedConnectUrl,T,"hostedConnectUrl",!0):void 0;n!==void 0&&a!==void 0&&n!==a&&f("apiBaseUrl and hostedConnectUrl target different Facto environments");let o=e,s=K(o);for(let p of[n,a])p!==void 0&&p!==s&&f("environment selector conflicts with a published Facto endpoint");let d=J(t.apiBaseUrl??F[s]),u=J(t.hostedConnectUrl??T[s]),m=v(d,F,"apiBaseUrl",!1);return v(u,T,"hostedConnectUrl",!0),Ue(t.clientId,m),{appId:t.appId,clientId:t.clientId,clientSecret:t.clientSecret,environment:o,apiBaseUrl:d,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 U(t,e){K(t.environment)!=="dev"&&f(`${e} is available only in the sandbox/dev environment`)}function Me(t){K(t.environment)!=="dev"&&f("sendWebhookTestDelivery is available only in the sandbox/dev environment")}function _(t,e,n){(typeof t!="string"||!new RegExp(`^${e}[A-Za-z0-9_-]+$`).test(t))&&f(`${n} must be an opaque ${e} reference`)}function X(t){_(t,"ul_","userLinkRef")}function xe(t){(typeof t!="string"||!/^we_[A-Za-z0-9]+$/.test(t))&&f("webhookEndpointId must be an opaque we_ reference")}function ee(t){(typeof t!="object"||t===null||t.currency!=="USDC"||typeof t.amount!="string"||!/^[0-9]+(?:\.[0-9]{1,6})?$/.test(t.amount))&&f("Dev amount must be a USDC decimal with at most six fractional digits")}function Le(t){(typeof t!="string"||!me.includes(t))&&f("unknown Dev simulation scenario")}function te(t){(typeof t!="string"||t.trim()!==t||t.length<16||t.length>255)&&f("idempotencyKey must be 16 to 255 non-whitespace-trimmed characters")}function Ue(t,e){let n=e==="dev",a=e==="production";t.startsWith("dev_")&&e!==void 0&&!n&&f("a dev credential can target only the sandbox/dev environment"),(n||a)&&(t.startsWith("staging_")||t.startsWith("test_")||t.startsWith("lab_")||t.startsWith("sandbox_"))&&f("internal or legacy (staging_/test_/lab_/sandbox_) credentials cannot target a published Facto environment")}function v(t,e,n,a){let o;try{o=new URL(t)}catch{f(`${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 m=o.pathname==="/"||a&&o.pathname==="/connect";return(o.origin!==u.origin||o.username!==""||o.password!==""||!m||o.search!==""||o.hash!=="")&&f(`${n} is not the exact published ${d} endpoint`),d}}async function R(t,e,n,a,o,s={},d=[]){let u=await le(t,async()=>{let m=await G(t,`${t.apiBaseUrl}${e}`,{method:"POST",headers:{authorization:a,"content-type":"application/json",...s},body:JSON.stringify(n)});if(!m.ok&&!d.includes(m.status))throw await j(m);return m},s["Idempotency-Key"]!==void 0);try{return o(await u.json())}catch(m){throw new b("FACTO_ENGINE_RESPONSE_INVALID","Facto Engine returned an invalid response",{retryable:!1,details:m})}}async function S(t,e,n,a){let o=await le(t,async()=>{let s=await G(t,`${t.apiBaseUrl}${e}`,{method:"GET",headers:{authorization:n}});if(!s.ok)throw await j(s);return s},!0);try{return a(await o.json())}catch(s){throw new b("FACTO_ENGINE_RESPONSE_INVALID","Facto Engine returned an invalid response",{retryable:!1,details:s})}}async function ne(t,e,n){let a=await G(t,`${t.apiBaseUrl}${e}`,{method:"DELETE",headers:{authorization:n}});if(!a.ok)throw await j(a)}async function j(t){return new b("FACTO_ENGINE_REQUEST_FAILED",`Facto Engine request failed with status ${t.status}`,{retryable:t.status===429||t.status>=500,status:t.status,details:await Tt(t),retryAfterSeconds:Se(t)})}function le(t,e,n){return n?Re(e,{...t.retry,signal:t.signal??t.retry?.signal}):e()}function G(t,e,n){return t.timeoutMs===void 0?t.transport(e,{...n,signal:t.signal}):Ne(t,e,n)}function Ne(t,e,n){let a=new AbortController,o=()=>a.abort();return t.signal?.aborted?Promise.reject(new b("FACTO_REQUEST_ABORTED","Facto Engine request aborted",{retryable:!1})):(t.signal?.addEventListener("abort",o,{once:!0}),new Promise((s,d)=>{let u=setTimeout(()=>{a.abort(),d(new b("FACTO_REQUEST_ABORTED","Facto Engine request timed out",{retryable:!1}))},t.timeoutMs);t.transport(e,{...n,signal:a.signal}).then(s,d).finally(()=>{clearTimeout(u),t.signal?.removeEventListener("abort",o)})}))}function W(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 z(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 Oe=["pending","succeeded","failed"],De=["requested_by_customer","duplicate","fraudulent","other"];function Fe(t,e){let n=t[e];if(typeof n!="string"||!Oe.includes(n))throw new Error(`expected refund status at ${e}`);return n}function We(t,e){let n=t[e];if(n!==void 0){if(typeof n!="string"||!De.includes(n))throw new Error(`expected refund reason at ${e}`);return n}}function H(t){let e=g(t),n=We(e,"reason"),a=A(e,"merchantRefundRef");return{refundId:c(e,"refundId"),paymentId:c(e,"paymentId"),status:Fe(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 ze=["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 He(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"||!ze.includes(a))throw new Error(`unknown webhook event type: ${String(a)}`);return a})}function B(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:He(e,"enabledEvents"),status:n,createdAt:c(e,"createdAt")}}function re(t){let e=B(t),n=g(t);return{...e,secret:c(n,"secret")}}var D=["fixtures","synthetic_identity","faucet","simulation","money_loop","webhook_test_delivery"],$e=["unavailable","degraded","ready"],qe=["contract","implemented","deployed","verified"],me=["approved","declined_setup","declined_limit","payment_failed"],Ve=["pre_admission","onchain_test_assets"],Be=["accepted","processing","succeeded","failed","declined"],Je=["accepted","broadcast","confirmed","failed"];function Ke(t){let e=g(t),n=e.capabilities;if(!Array.isArray(n)||n.length!==D.length)throw new Error("expected exactly six Dev capabilities");let a=n.map(je),o=new Set(a.map(s=>s.name));if(o.size!==D.length)throw new Error("expected each Dev capability exactly once");for(let s of D)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:c(e,"checkedAt")}}function je(t){let e=g(t),n=C(e,"name",D,"Dev capability name"),a=C(e,"status",$e,"Dev capability status"),o=C(e,"evidenceLevel",qe,"Dev evidence level"),s=E(e,"reasonCode"),d=E(e,"verifiedAt");if(a==="ready"&&(o!=="verified"||d===null))throw new Error("ready Dev capability requires verified evidence");let u=Qe(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 Ge(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:x(e,"currency","USDC")}}function Ye(t){let e=g(t);return{faucetTransferId:M(e,"faucetTransferId","sft_"),userLinkRef:M(e,"userLinkRef","ul_"),amount:Ge(e.amount),status:C(e,"status",Je,"Dev faucet status"),createdAt:c(e,"createdAt")}}function ae(t){let e=g(t);return{simulationId:M(e,"simulationId","sim_"),scenario:C(e,"scenario",me,"Dev scenario"),executionMode:C(e,"executionMode",Ve,"Dev execution mode"),status:C(e,"status",Be,"Dev simulation status"),reasonCode:$(e,"reasonCode"),authorizationRef:$(e,"authorizationRef"),chargeRef:$(e,"chargeRef"),createdAt:c(e,"createdAt"),updatedAt:c(e,"updatedAt")}}function Ze(t){let e=g(t);return{eventId:oe(e,"eventId","evt_"),deliveryId:oe(e,"deliveryId","wd_"),status:x(e,"status","queued"),createdAt:c(e,"createdAt")}}function Qe(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=c(t,e);if(!new RegExp(`^${n}[A-Za-z0-9_-]+$`).test(a))throw new Error(`expected opaque ${e}`);return a}function oe(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 Xe(t,e){return e.userLinkRef===void 0&&e.factoServerWalletAddress===void 0&&f("payment readiness requires userLinkRef, factoServerWalletAddress, or both"),e.userLinkRef!==void 0&&_(e.userLinkRef,"ul_","userLinkRef"),e.factoServerWalletAddress!==void 0&&typeof e.factoServerWalletAddress!="string"&&f("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 et(t){let e=g(t),n=k(e,"cardRef"),a=k(e,"factoUserId"),o=k(e,"factoServerWalletAddress");if(n!=null&&(_(n,"card_","cardRef"),a!=null||o!=null))throw new Error("synthetic Dev links must not expose canonical identity");return{appId:c(e,"appId"),userLinkRef:M(e,"userLinkRef","ul_"),grantStatus:c(e,"grantStatus"),pipelineReady:w(e,"pipelineReady"),scopes:Pt(e,"scopes"),...n===void 0?{}:{cardRef:n},...a===void 0?{}:{factoUserId:a},...o===void 0?{}:{factoServerWalletAddress:o}}}function tt(t){let e=g(t),n=w(e,"pipelineReady"),a=e.notReadyReason,o=a==null?a:C(e,"notReadyReason",Q,"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{appId:c(e,"appId"),userLinkRef:M(e,"userLinkRef","ul_"),selectedPipelineId:c(e,"selectedPipelineId"),chainId:pe(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 nt(t){let e=g(t);return{sessionId:c(e,"sessionId"),checkoutUrl:c(e,"checkoutUrl"),status:x(e,"status","pending"),amount:c(e,"amount"),assetSymbol:c(e,"assetSymbol"),orderRef:E(e,"orderRef")}}function rt(t){let e=g(t);return{sessionId:c(e,"sessionId"),status:bt(e,"status"),amount:c(e,"amount"),assetSymbol:c(e,"assetSymbol"),orderRef:E(e,"orderRef"),chargeId:E(e,"chargeId"),confirmedAt:E(e,"confirmedAt")}}function se(t){let e=g(t),n=A(e,"mandateId"),a=A(e,"userLinkRef");return{sessionId:c(e,"sessionId"),authorizationUrl:c(e,"authorizationUrl"),status:_t(e,"status"),...n===void 0?{}:{mandateId:n},...a===void 0?{}:{userLinkRef:a},expiresAt:c(e,"expiresAt"),state:c(e,"state")}}function ie(t){let e=g(t),n=A(e,"expiresAt");return{mandateId:c(e,"mandateId"),appId:c(e,"appId"),status:It(e,"status"),allowedUseCases:wt(e,"allowedUseCases"),limits:lt(e.limits),paymentPath:mt(e.paymentPath),createdAt:c(e,"createdAt"),...n===void 0?{}:{expiresAt:n}}}var at="direct",ot="defaultPaymentOptionId";function st(t){let e=g(t);ye(e,"payment options");let n=e.paymentOptions;if(!Array.isArray(n))throw new Error("expected paymentOptions array");let a=n.map(ct).filter(d=>d.settlementPath===at),o=ft(e,ot),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 dt(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 ct(t){let e=g(t);ye(e,"payment option");let n=A(e,"blockingReason"),a=c(e,"assetSymbol"),o=c(e,"chainLabel"),s=c(e,"protocolLabel"),{settlementPath:d,spendMode:u}=dt(e);return{paymentOptionId:fe(e,"paymentOptionId"),label:ut({assetSymbol:a,protocolLabel:s,chainLabel:o},c(e,"label")),ready:w(e,"ready"),isDefault:w(e,"isDefault"),chainId:pe(e,"chainId"),chainLabel:o,protocolLabel:s,assetSymbol:a,spendMode:u,settlementPath:d,...n===void 0?{}:{blockingReason:n}}}function ut(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 N(t){let e=g(t),n=A(e,"chargeId"),a=A(e,"txHash"),o=Et(e,"declineReason"),s=pt(e,"finalityEtaSeconds"),d=A(e,"terminalAt"),u=A(e,"updatedAt");return{paymentId:c(e,"paymentId"),mandateId:c(e,"mandateId"),merchantPaymentRef:c(e,"merchantPaymentRef"),status:vt(e,"status"),amount:c(e,"amount"),currency:c(e,"currency"),useCase:Rt(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 lt(t){let e=g(t);return{perTxAmount:c(e,"perTxAmount"),periodAmount:c(e,"periodAmount"),period:At(e,"period")}}function mt(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 fe(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 ft(t,e){if(!(t[e]===void 0||t[e]===null))return fe(t,e)}function x(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 pe(t,e){let n=t[e];if(typeof n!="number"||!Number.isFinite(n))throw new Error(`expected finite number at ${e}`);return n}function pt(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 gt=["pending","charged","expired","cancelled"],ge=["immediate","recurring","top_up","metered"],yt=["daily","weekly","monthly"],ht=["pending","active","paused","revoked","expired","suspended"],Ct=["created","authorized","declined","expired"],St=["accepted","declined","charging","finalizing","succeeded","paid_via_coverage","failed","canceled"];function bt(t,e){let n=t[e];if(typeof n!="string"||!gt.includes(n))throw new Error(`expected checkout status at ${e}`);return n}function Rt(t,e){return C(t,e,ge,"mandate use case")}function At(t,e){return C(t,e,yt,"mandate limit period")}function It(t,e){return C(t,e,ht,"mandate status")}function _t(t,e){return C(t,e,Ct,"mandate authorization status")}function vt(t,e){return C(t,e,St,"mandate payment status")}function Et(t,e){if(t[e]!==void 0)return C(t,e,Z,"mandate decline reason")}function wt(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"||!ge.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 E(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 $(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 Pt(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 ye(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 Tt(t){try{return await t.json()}catch{return await t.text().catch(()=>null)}}function J(t){return t.replace(/\/+$/,"")}function f(t){throw new b("FACTO_CONFIG_INVALID",t,{retryable:!1})}function kt(t){let e=globalThis.btoa;if(e)return e(t);let n=globalThis.Buffer;if(n)return n.from(t).toString("base64");f("No base64 encoder is available in this runtime")}function Gt(t,e,n=Math.floor(Date.now()/1e3)){e||f("webhook secret is required"),(!Number.isSafeInteger(n)||n<0)&&f("webhook timestamp must be a non-negative safe integer");let a=ue("sha256",e).update(`${n}.`).update(t).digest("hex");return`t=${n},v1=${a}`}function Yt(t,e,n,a=300){n||f("webhook secret is required");let o=e.split(",").map(m=>m.trim()),s,d=[];for(let m of o){let p=m.indexOf("=");if(p===-1)continue;let r=m.slice(0,p),i=m.slice(p+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=ue("sha256",n).update(`${s}.`).update(t).digest();return d.some(m=>{let p;try{p=Buffer.from(m,"hex")}catch{return!1}return p.length===u.length&&Ce(p,u)})}var l=class extends Error{code;details;constructor(e,n,a={}){super(n),this.name="FactoConnectHintError",this.code=e,this.details=a.details}},Mt="facto";async function Zt(t){if(t===null||typeof t!="object")throw new l("FACTO_HINT_INPUT_INVALID","verifyFactoCardProgramConnectHint requires an input object");let e=V(t.connectHint,"connectHint"),n=V(t.audience,"audience"),a=t.issuer===void 0?Mt:V(t.issuer,"issuer"),o=zt(t.clockToleranceSeconds),s=Math.floor(Ht(t.now)/1e3),{headerB64:d,payloadB64:u,signature:m}=xt(e),p=Y(de(d,"header"),"FACTO_HINT_MALFORMED","connect hint header");if(p.alg!=="EdDSA")throw new l("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 Lt(t.jwks),y=Dt(i,r),L=qt(`${d}.${u}`);if(!await Ft(L,m,y))throw new l("FACTO_HINT_SIGNATURE_INVALID","connect hint signature does not verify against the Facto JWKS");let I=Wt(de(u,"payload"));if(I.iss!==a)throw new l("FACTO_HINT_ISSUER_MISMATCH","connect hint issuer mismatch",{details:{expected:a,actual:I.iss}});if(I.aud!==n)throw new l("FACTO_HINT_AUDIENCE_MISMATCH","connect hint audience mismatch",{details:{expected:n,actual:I.aud}});if(s>I.exp+o)throw new l("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 xt(t){let e=t.split(".");if(e.length!==3)throw new l("FACTO_HINT_MALFORMED","connect hint is not a compact JWS (expected three segments)");let[n,a,o]=e;if(!n||!a||!o)throw new l("FACTO_HINT_MALFORMED","connect hint has an empty JWS segment");return{headerB64:n,payloadB64:a,signature:he(o,"signature")}}function de(t,e){let n=new TextDecoder().decode(he(t,e));try{return JSON.parse(n)}catch(a){throw new l("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid JSON`,{details:a})}}async function Lt(t){if(t==null)throw new l("FACTO_HINT_INPUT_INVALID","jwks is required");return q(typeof t=="function"?await t():typeof t=="string"?await Nt(t):t)}var Ut=5e3,O=64*1024;async function Nt(t){let e;try{e=new URL(t)}catch{throw new l("FACTO_HINT_JWKS_INVALID",`JWKS url is not a valid URL: ${t}`)}if(e.protocol!=="https:")throw new l("FACTO_HINT_JWKS_INVALID",`JWKS url must use https: (got ${e.protocol})`,{details:{protocol:e.protocol}});let n=new AbortController,a=setTimeout(()=>n.abort(),Ut),o,s;try{try{o=await fetch(t,{method:"GET",headers:{accept:"application/json"},redirect:"follow",signal:n.signal})}catch(u){throw new l("FACTO_HINT_JWKS_INVALID",`failed to fetch Facto JWKS from ${t}`,{details:u})}if(!o.ok)throw new l("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>O)throw new l("FACTO_HINT_JWKS_INVALID",`Facto JWKS response exceeds ${O} bytes`,{details:{contentLength:d}});try{s=await o.text()}catch(u){throw new l("FACTO_HINT_JWKS_INVALID","Facto JWKS response could not be read",{details:u})}}finally{clearTimeout(a)}if(s.length>O)throw new l("FACTO_HINT_JWKS_INVALID",`Facto JWKS response exceeds ${O} bytes`,{details:{bytes:s.length}});try{return JSON.parse(s)}catch(d){throw new l("FACTO_HINT_JWKS_INVALID","Facto JWKS response was not valid JSON",{details:d})}}function q(t){let e=Y(t,"FACTO_HINT_JWKS_INVALID","JWKS");if(!Array.isArray(e.keys))throw new l("FACTO_HINT_JWKS_INVALID",'JWKS "keys" must be an array');return{keys:e.keys.map(Ot)}}function Ot(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 Dt(t,e){let n=t.keys.filter(a=>a.kty==="OKP"&&a.crv==="Ed25519"&&a.x.length>0);if(n.length===0)throw new l("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 Ft(t,e,n){let a=Vt();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 Wt(t){let e=Y(t,"FACTO_HINT_CLAIMS_INVALID","connect hint claims");return{iss:P(e,"iss"),aud:P(e,"aud"),sub:P(e,"sub"),program_ref:P(e,"program_ref"),nonce:P(e,"nonce"),iat:ce(e,"iat"),exp:ce(e,"exp")}}function V(t,e){if(typeof t!="string"||t.length===0)throw new l("FACTO_HINT_INPUT_INVALID",`${e} must be a non-empty string`);return t}function zt(t){if(t===void 0)return 0;if(typeof t!="number"||!Number.isFinite(t)||t<0)throw new l("FACTO_HINT_INPUT_INVALID","clockToleranceSeconds must be a non-negative finite number");return t}function Ht(t){if(t===void 0)return Date.now();if(t instanceof Date){let e=t.getTime();if(Number.isNaN(e))throw new l("FACTO_HINT_INPUT_INVALID","now is an invalid Date");return e}if(typeof t=="number"&&Number.isFinite(t))return t;throw new l("FACTO_HINT_INPUT_INVALID","now must be a Date or unix milliseconds number")}function Y(t,e,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new l(e,`${n} must be a JSON object`);return t}function P(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new l("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 l("FACTO_HINT_CLAIMS_INVALID",`connect hint claim "${e}" must be a finite number`);return n}function he(t,e){if(!/^[A-Za-z0-9_-]*$/.test(t))throw new l("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid base64url`);let n=t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4);return $t(n,e)}function $t(t,e){let n=globalThis.atob;if(n){let o;try{o=n(t)}catch(d){throw new l("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 l("FACTO_HINT_INPUT_INVALID","No base64 decoder is available in this runtime")}function qt(t){let e=new TextEncoder().encode(t),n=new Uint8Array(e.length);return n.set(e),n}function Vt(){let t=globalThis.crypto;if(t?.subtle)return t.subtle;throw new l("FACTO_HINT_INPUT_INVALID","Web Crypto (crypto.subtle) is not available in this runtime")}var Qt=Ie;export{F as FACTO_CONNECT_API_BASE_URLS,T as FACTO_CONNECT_HOSTED_URLS,l as FactoConnectHintError,b as FactoConnectServerError,Ae as buildHostedConnectUrl,Ie as createFactoConnectServer,Qt as default,ve as isTerminalMandatePaymentStatus,Gt as signWebhookPayload,Zt as verifyFactoCardProgramConnectHint,Yt as verifyWebhookSignature,Re as withServerRetry};
|
package/dist/testing/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var P=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var Z=Object.prototype.hasOwnProperty;var H=(e,t)=>{for(var i in t)P(e,i,{get:t[i],enumerable:!0})},V=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of $(t))!Z.call(e,c)&&c!==i&&P(e,c,{get:()=>t[c],enumerable:!(s=G(t,c))||s.enumerable});return e};var B=e=>V(P({},"__esModule",{value:!0}),e);var ae={};H(ae,{MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS:()=>O,MerchantPartnerWorkspaceMockError:()=>d,createFactoConnectFixtureTransport:()=>N,createFactoTestTransport:()=>ne,createMerchantPartnerWorkspaceMock:()=>D,devFixtures:()=>y,devScenarios:()=>re,merchantDevAppFixture:()=>F,merchantFutureTemplateProjectionFixture:()=>L,merchantProductionAppNegativeFixture:()=>q});module.exports=B(ae);var O=["listMerchantWorkspaceApps","createMerchantDevApp","rotateMerchantWorkspaceCredential"],J=new Set(["merchant_connect_dev","merchant_webhook_dev"]),d=class extends Error{status;constructor(t,i){super(t),this.name="MerchantPartnerWorkspaceMockError",this.status=i}};function D(e={}){let t=[],i=(e.initialApps??[]).map(v),s=new Set(e.authenticatedSession?.scopes??[]),c=e.now??(()=>new Date),o=new Map,r=new Map,n=i.length+1;return{client:{async listMerchantWorkspaceApps({environment:p}){if(t.push({operationId:"listMerchantWorkspaceApps",method:"GET",path:"/api/partner-workspace/merchant/apps",query:{environment:p}}),p!=="dev")throw new d("Environment filter is outside the mock server-derived context.",403);return{items:i.filter(h=>h.environment===p).map(v)}},async createMerchantDevApp({idempotencyKey:p,body:h}){let g=C(p),m=I(h,["display_name","capability_template","allowed_origins"]),k=E(m.display_name,"Display name",1,160);if(!Y(m.capability_template))throw new d("Capability template is not approved for Merchant dev app creation.",400);let l={display_name:k,capability_template:m.capability_template,allowed_origins:Q(m.allowed_origins)};t.push({operationId:"createMerchantDevApp",method:"POST",path:"/api/partner-workspace/merchant/apps",headers:{"Idempotency-Key":g},body:l});let u=ee(l),w=o.get(g);if(w){if(w.fingerprint!==u)throw W("createMerchantDevApp");return v(w.response)}let x={app_id:`dev_mcid_mock_${String(n).padStart(2,"0")}`,display_name:l.display_name,environment:"dev",capability_template:l.capability_template,status:"draft",allowed_origins:[...l.allowed_origins]};return n+=1,i.push(x),o.set(g,{fingerprint:u,response:v(x)}),v(x)},async rotateMerchantWorkspaceCredential(p){let h=C(p.idempotencyKey),g=I(p.body,["reason"]),m=E(g.reason,"Rotation reason",3,500);t.push({operationId:"rotateMerchantWorkspaceCredential",method:"POST",path:`/api/partner-workspace/merchant/apps/${encodeURIComponent(p.appId)}/credential-rotations`,headers:{"Idempotency-Key":h},authorization:"partnerSession:step_up",body:{reason:m}});let k=te(p.appId,m),l=r.get(h);if(l){if(l.fingerprint!==k)throw W("rotateMerchantWorkspaceCredential");return{...l.response}}if(!s.has("step_up"))throw new d("Recent step-up authentication is required.",403);let u=i.find(K=>K.app_id===p.appId);if(!u)throw new d("Merchant app is not visible in the active server-derived context.",409);if(u.environment!=="dev")throw new d("Merchant app is outside the mock server-derived context.",403);let w=u.credential_version??0;u.credential_version=w+1;let x=new Date(c().getTime()+300*1e3).toISOString(),S={credential_id:`credential:${u.app_id}`,new_version:u.credential_version,old_version_expires_at:x,retrieval_mode:"protected_retrieval_handle",retrieval_handle:`mock-retrieval:${u.app_id}:${u.credential_version}`};return r.set(h,{fingerprint:k,response:{...S}}),S}},requests:t}}function v(e){return{...e,allowed_origins:[...e.allowed_origins]}}function Y(e){return J.has(e)}function C(e){if(typeof e!="string")throw _("Idempotency-Key must contain between 16 and 128 characters.");let t=e.trim();if(t.length<16||t.length>128)throw _("Idempotency-Key must contain between 16 and 128 characters.");return t}function I(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw _("Request body must be an object.");let i=new Set(t);if(Reflect.ownKeys(e).some(s=>typeof s!="string"||!i.has(s)))throw _("Request body contains an unsupported property.");return e}function E(e,t,i,s){if(typeof e!="string")throw _(`${t} must be a string.`);let c=e.trim(),o=Array.from(c).length;if(o<i||o>s)throw _(`${t} must contain between ${i} and ${s} characters.`);return c}function Q(e){if(!Array.isArray(e)||e.length>20)throw f("Allowed origins must be an array with at most 20 entries.");let t=[],i=new Set;for(let s of e){if(typeof s!="string"||s.length===0||/\s/.test(s))throw f("Each allowed origin must be a non-empty exact URL origin.");let c=/^(https?):\/\/([^/?#\\]+)\/?$/i.exec(s);if(!c)throw f("Allowed origins cannot include a path, query, or fragment.");let o;try{o=new URL(s)}catch{throw f("Allowed origin URL parsing failed.")}if(o.protocol!=="https:"&&o.protocol!=="http:"||o.username!==""||o.password!==""||o.pathname!=="/"||o.search!==""||o.hash!=="")throw f("Allowed origins must be credential-free exact HTTP(S) origins.");if(o.protocol==="http:"){let r=X(c[2]??"").toLowerCase();if(!(r==="localhost"||r==="127.0.0.1"||r==="[::1]"))throw f("Plain HTTP is allowed only for exact loopback origins.")}if(i.has(o.origin))throw f("Allowed origins must be unique after canonicalization.");i.add(o.origin),t.push(o.origin)}return t}function X(e){if(e.startsWith("[")){let i=e.indexOf("]");return i===-1?e:e.slice(0,i+1)}let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function f(e){return new d(e,400)}function _(e){return new d(e,400)}function ee(e){return JSON.stringify({display_name:e.display_name,capability_template:e.capability_template,allowed_origins:[...e.allowed_origins].sort()})}function te(e,t){return JSON.stringify({app_id:e,reason:t})}function W(e){return new d(`Idempotency key was already used for a different ${e} request.`,409)}var F={app_id:"dev_mcid_fixture_01",display_name:"Fixture storefront",environment:"dev",capability_template:"merchant_connect_dev",status:"draft",allowed_origins:["https://merchant.example"]},q={app_id:"production_mcid_fixture_01",display_name:"Production boundary fixture",environment:"production",capability_template:"merchant_connect_dev",status:"active",allowed_origins:["https://merchant.example"],credential_version:3},L={app_id:"app_fixture_future",display_name:"Future template fixture",environment:"dev",capability_template:"merchant_connect_dev_with_diagnostics",status:"active",allowed_origins:["https://merchant.example"],credential_version:1};var re=Object.freeze(["approved","declined_setup","declined_limit","payment_failed"]),y=Object.freeze({capabilities:{environment:"dev",contractVersion:"2026-07-09",checkedAt:"2026-07-10T00:00:00.000Z",capabilities:[{name:"fixtures",status:"ready",evidenceLevel:"verified",reasonCode:null,verifiedAt:"2026-07-10T00:00:00.000Z",limits:{networkCalls:0}},...["synthetic_identity","faucet","simulation","money_loop","webhook_test_delivery"].map(e=>({name:e,status:"unavailable",evidenceLevel:"contract",reasonCode:"DEV_NOT_DEPLOYED",verifiedAt:null,limits:{}}))]},faucetTransfer:{faucetTransferId:"sft_fixture_1001",userLinkRef:"ul_fixture_buyer_01",amount:{amount:"10.00",currency:"USDC"},status:"accepted",createdAt:"2026-07-10T00:00:00.000Z"},simulation:{simulationId:"sim_fixture_1001",scenario:"approved",executionMode:"pre_admission",status:"accepted",reasonCode:null,authorizationRef:null,chargeRef:null,createdAt:"2026-07-10T00:00:00.000Z",updatedAt:"2026-07-10T00:00:00.000Z"},webhookTestDelivery:{eventId:"evt_fixturetestping1001",deliveryId:"wd_fixturetestping1001",status:"queued",createdAt:"2026-07-10T00:00:00.000Z"}}),b="2026-07-10T00:00:00.000Z",j="0x1111111111111111111111111111111111111111";function N(e={}){let t=e.scenario??"happy_path",i=0;return async(s,c)=>{let o=new URL(s),r=(c?.method??"GET").toUpperCase(),n=o.pathname;if(r==="POST"&&n==="/api/merchant/user-links/exchange")return a({appId:"app_fixture",userLinkRef:"ul_fixture_buyer_01",factoUserId:"user_fixture",factoServerWalletAddress:j,grantStatus:"active",pipelineReady:t!=="setup_required",scopes:["wallet.read","payments.write"]});if(r==="POST"&&n==="/api/merchant/payment-readiness")return a({appId:"app_fixture",userLinkRef:"ul_fixture_buyer_01",factoUserId:"user_fixture",factoServerWalletAddress:j,readinessScope:"account_default",chainId:84532,protocolId:"aave-v3",assetSymbol:"USDC",spendMode:"direct",pipelineReady:t!=="setup_required",...t==="setup_required"?{notReadyReason:"payment_route_not_provisioned"}:{}});if(r==="POST"&&n==="/api/merchant/checkout-sessions")return a({sessionId:"checkout_fixture",checkoutUrl:"https://dev.facto.to/checkout/checkout_fixture",status:"pending",amount:"9.99",assetSymbol:"USDC",orderRef:"order_fixture"});if(r==="GET"&&n.startsWith("/api/merchant/checkout-sessions/"))return a({sessionId:"checkout_fixture",status:"charged",amount:"9.99",assetSymbol:"USDC",orderRef:"order_fixture",chargeId:"charge_fixture",confirmedAt:b});if(r==="POST"&&n==="/api/merchant/authorization-sessions")return a(z("created"));if(r==="GET"&&n.startsWith("/api/merchant/authorization-sessions/"))return a(z("authorized"));if(r==="GET"&&n.startsWith("/api/merchant/payment-authorizations/"))return a(U());if(r==="POST"&&n==="/api/merchant/payment-options")return a({paymentOptions:[{paymentOptionId:"fpo_fixture",label:"Fixture Direct",ready:t!=="setup_required",isDefault:!0,chainId:84532,chainLabel:"Base Sepolia",protocolLabel:"Aave V3",assetSymbol:"USDC",spendMode:"direct",settlementPath:"direct",...t==="setup_required"?{blockingReason:"setup_required"}:{}}],defaultPaymentOptionId:"fpo_fixture"});if(r==="POST"&&n==="/api/merchant/payments")return t==="idempotency_conflict"?a({code:"idempotency_conflict",message:"fixture idempotency conflict"},409):a(A(t==="declined_before_money"?"declined":"charging"));if(r==="GET"&&n.startsWith("/api/merchant/payments/")){let M=t==="status_progression"?["charging","finalizing","succeeded"]:["succeeded"],p=M[Math.min(i,M.length-1)]??"succeeded";return i+=1,a(A(p))}return r==="DELETE"&&n.startsWith("/api/merchant/user-links/")?new Response(null,{status:204}):r==="GET"&&n==="/api/merchant/payments"?a({data:[A("succeeded")],hasMore:!1}):r==="GET"&&n==="/api/merchant/payment-authorizations"?a({data:[U()],hasMore:!1}):r==="POST"&&n==="/api/merchant/refunds"?a(R()):r==="GET"&&n==="/api/merchant/refunds"?a({data:[R()],hasMore:!1}):r==="GET"&&n.startsWith("/api/merchant/refunds/")?a(R()):r==="POST"&&n==="/api/merchant/webhook-endpoints"?a({...T(),secret:"whsec_fixture_only"}):r==="GET"&&n==="/api/dev/capabilities"?a(y.capabilities):r==="POST"&&n==="/api/dev/faucet/usdc"?a(y.faucetTransfer,202):r==="POST"&&n==="/api/dev/simulate/charge"?a(y.simulation,202):r==="GET"&&n.startsWith("/api/dev/simulations/")?a(y.simulation):r==="POST"&&n.endsWith("/test-delivery")&&n.startsWith("/api/merchant/webhook-endpoints/")?a(y.webhookTestDelivery,202):r==="GET"&&n==="/api/merchant/webhook-endpoints"?a({data:[T()]}):r==="POST"&&n.endsWith("/rotate-secret")&&n.startsWith("/api/merchant/webhook-endpoints/")?a({...T(),secret:"whsec_fixture_rotated"}):r==="GET"&&n.startsWith("/api/merchant/webhook-endpoints/")?a(T()):r==="DELETE"&&n.startsWith("/api/merchant/webhook-endpoints/")?new Response(null,{status:204}):a({code:"fixture_route_not_found",method:r,path:n},404)}}var ne=N;function z(e){return{sessionId:"mauth_fixture",authorizationUrl:"https://dev.facto.to/merchant-mandates/authorize?session=mauth_fixture",status:e,...e==="authorized"?{mandateId:"mandate_fixture"}:{},expiresAt:"2026-07-10T00:15:00.000Z",state:"state_fixture"}}function U(){return{mandateId:"mandate_fixture",appId:"app_fixture",status:"active",allowedUseCases:["immediate","recurring","metered"],limits:{perTxAmount:"100.00",periodAmount:"500.00",period:"monthly"},paymentPath:{ready:!0,summary:"Fixture payment path ready"},createdAt:b}}function A(e){return{paymentId:"mpay_fixture",mandateId:"mandate_fixture",merchantPaymentRef:"payment_fixture",status:e,amount:e==="declined"?"75.00":"9.99",currency:"USDC",useCase:e==="declined"?"metered":"recurring",...e==="declined"?{declineReason:"mandate_limit_exceeded"}:{},...e==="succeeded"?{chargeId:"charge_fixture",txHash:`0x${"1".repeat(64)}`,terminalAt:"2026-07-10T00:00:03.000Z"}:{},createdAt:b,updatedAt:"2026-07-10T00:00:03.000Z"}}function R(){return{refundId:"refund_fixture",paymentId:"mpay_fixture",status:"succeeded",amount:"9.99",currency:"USDC",reason:"requested_by_customer",merchantRefundRef:"merchant_refund_fixture",createdAt:b}}function T(){return{webhookEndpointId:"webhook_fixture",url:"https://merchant.example/facto-webhooks",enabledEvents:["payment.succeeded","payment.failed"],status:"enabled",createdAt:b}}function a(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"content-type":"application/json"}})}
|
|
1
|
+
"use strict";var P=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var Z=Object.prototype.hasOwnProperty;var H=(e,t)=>{for(var i in t)P(e,i,{get:t[i],enumerable:!0})},V=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of $(t))!Z.call(e,c)&&c!==i&&P(e,c,{get:()=>t[c],enumerable:!(s=G(t,c))||s.enumerable});return e};var B=e=>V(P({},"__esModule",{value:!0}),e);var ae={};H(ae,{MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS:()=>O,MerchantPartnerWorkspaceMockError:()=>d,createFactoConnectFixtureTransport:()=>N,createFactoTestTransport:()=>ne,createMerchantPartnerWorkspaceMock:()=>D,devFixtures:()=>y,devScenarios:()=>re,merchantDevAppFixture:()=>F,merchantFutureTemplateProjectionFixture:()=>L,merchantProductionAppNegativeFixture:()=>q});module.exports=B(ae);var O=["listMerchantWorkspaceApps","createMerchantDevApp","rotateMerchantWorkspaceCredential"],J=new Set(["merchant_connect_dev","merchant_webhook_dev"]),d=class extends Error{status;constructor(t,i){super(t),this.name="MerchantPartnerWorkspaceMockError",this.status=i}};function D(e={}){let t=[],i=(e.initialApps??[]).map(v),s=new Set(e.authenticatedSession?.scopes??[]),c=e.now??(()=>new Date),o=new Map,r=new Map,n=i.length+1;return{client:{async listMerchantWorkspaceApps({environment:p}){if(t.push({operationId:"listMerchantWorkspaceApps",method:"GET",path:"/api/partner-workspace/merchant/apps",query:{environment:p}}),p!=="dev")throw new d("Environment filter is outside the mock server-derived context.",403);return{items:i.filter(h=>h.environment===p).map(v)}},async createMerchantDevApp({idempotencyKey:p,body:h}){let g=I(p),m=C(h,["display_name","capability_template","allowed_origins"]),k=E(m.display_name,"Display name",1,160);if(!Y(m.capability_template))throw new d("Capability template is not approved for Merchant dev app creation.",400);let l={display_name:k,capability_template:m.capability_template,allowed_origins:Q(m.allowed_origins)};t.push({operationId:"createMerchantDevApp",method:"POST",path:"/api/partner-workspace/merchant/apps",headers:{"Idempotency-Key":g},body:l});let u=ee(l),w=o.get(g);if(w){if(w.fingerprint!==u)throw W("createMerchantDevApp");return v(w.response)}let x={app_id:`dev_mcid_mock_${String(n).padStart(2,"0")}`,display_name:l.display_name,environment:"dev",capability_template:l.capability_template,status:"draft",allowed_origins:[...l.allowed_origins]};return n+=1,i.push(x),o.set(g,{fingerprint:u,response:v(x)}),v(x)},async rotateMerchantWorkspaceCredential(p){let h=I(p.idempotencyKey),g=C(p.body,["reason"]),m=E(g.reason,"Rotation reason",3,500);t.push({operationId:"rotateMerchantWorkspaceCredential",method:"POST",path:`/api/partner-workspace/merchant/apps/${encodeURIComponent(p.appId)}/credential-rotations`,headers:{"Idempotency-Key":h},authorization:"partnerSession:step_up",body:{reason:m}});let k=te(p.appId,m),l=r.get(h);if(l){if(l.fingerprint!==k)throw W("rotateMerchantWorkspaceCredential");return{...l.response}}if(!s.has("step_up"))throw new d("Recent step-up authentication is required.",403);let u=i.find(K=>K.app_id===p.appId);if(!u)throw new d("Merchant app is not visible in the active server-derived context.",409);if(u.environment!=="dev")throw new d("Merchant app is outside the mock server-derived context.",403);let w=u.credential_version??0;u.credential_version=w+1;let x=new Date(c().getTime()+300*1e3).toISOString(),S={credential_id:`credential:${u.app_id}`,new_version:u.credential_version,old_version_expires_at:x,retrieval_mode:"protected_retrieval_handle",retrieval_handle:`mock-retrieval:${u.app_id}:${u.credential_version}`};return r.set(h,{fingerprint:k,response:{...S}}),S}},requests:t}}function v(e){return{...e,allowed_origins:[...e.allowed_origins]}}function Y(e){return J.has(e)}function I(e){if(typeof e!="string")throw _("Idempotency-Key must contain between 16 and 128 characters.");let t=e.trim();if(t.length<16||t.length>128)throw _("Idempotency-Key must contain between 16 and 128 characters.");return t}function C(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw _("Request body must be an object.");let i=new Set(t);if(Reflect.ownKeys(e).some(s=>typeof s!="string"||!i.has(s)))throw _("Request body contains an unsupported property.");return e}function E(e,t,i,s){if(typeof e!="string")throw _(`${t} must be a string.`);let c=e.trim(),o=Array.from(c).length;if(o<i||o>s)throw _(`${t} must contain between ${i} and ${s} characters.`);return c}function Q(e){if(!Array.isArray(e)||e.length>20)throw f("Allowed origins must be an array with at most 20 entries.");let t=[],i=new Set;for(let s of e){if(typeof s!="string"||s.length===0||/\s/.test(s))throw f("Each allowed origin must be a non-empty exact URL origin.");let c=/^(https?):\/\/([^/?#\\]+)\/?$/i.exec(s);if(!c)throw f("Allowed origins cannot include a path, query, or fragment.");let o;try{o=new URL(s)}catch{throw f("Allowed origin URL parsing failed.")}if(o.protocol!=="https:"&&o.protocol!=="http:"||o.username!==""||o.password!==""||o.pathname!=="/"||o.search!==""||o.hash!=="")throw f("Allowed origins must be credential-free exact HTTP(S) origins.");if(o.protocol==="http:"){let r=X(c[2]??"").toLowerCase();if(!(r==="localhost"||r==="127.0.0.1"||r==="[::1]"))throw f("Plain HTTP is allowed only for exact loopback origins.")}if(i.has(o.origin))throw f("Allowed origins must be unique after canonicalization.");i.add(o.origin),t.push(o.origin)}return t}function X(e){if(e.startsWith("[")){let i=e.indexOf("]");return i===-1?e:e.slice(0,i+1)}let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function f(e){return new d(e,400)}function _(e){return new d(e,400)}function ee(e){return JSON.stringify({display_name:e.display_name,capability_template:e.capability_template,allowed_origins:[...e.allowed_origins].sort()})}function te(e,t){return JSON.stringify({app_id:e,reason:t})}function W(e){return new d(`Idempotency key was already used for a different ${e} request.`,409)}var F={app_id:"dev_mcid_fixture_01",display_name:"Fixture storefront",environment:"dev",capability_template:"merchant_connect_dev",status:"draft",allowed_origins:["https://merchant.example"]},q={app_id:"production_mcid_fixture_01",display_name:"Production boundary fixture",environment:"production",capability_template:"merchant_connect_dev",status:"active",allowed_origins:["https://merchant.example"],credential_version:3},L={app_id:"app_fixture_future",display_name:"Future template fixture",environment:"dev",capability_template:"merchant_connect_dev_with_diagnostics",status:"active",allowed_origins:["https://merchant.example"],credential_version:1};var re=Object.freeze(["approved","declined_setup","declined_limit","payment_failed"]),y=Object.freeze({capabilities:{environment:"dev",contractVersion:"2026-07-09",checkedAt:"2026-07-10T00:00:00.000Z",capabilities:[{name:"fixtures",status:"ready",evidenceLevel:"verified",reasonCode:null,verifiedAt:"2026-07-10T00:00:00.000Z",limits:{networkCalls:0}},...["synthetic_identity","faucet","simulation","money_loop","webhook_test_delivery"].map(e=>({name:e,status:"unavailable",evidenceLevel:"contract",reasonCode:"DEV_NOT_DEPLOYED",verifiedAt:null,limits:{}}))]},faucetTransfer:{faucetTransferId:"sft_fixture_1001",userLinkRef:"ul_fixture_buyer_01",amount:{amount:"10.00",currency:"USDC"},status:"accepted",createdAt:"2026-07-10T00:00:00.000Z"},simulation:{simulationId:"sim_fixture_1001",scenario:"approved",executionMode:"pre_admission",status:"accepted",reasonCode:null,authorizationRef:null,chargeRef:null,createdAt:"2026-07-10T00:00:00.000Z",updatedAt:"2026-07-10T00:00:00.000Z"},webhookTestDelivery:{eventId:"evt_fixturetestping1001",deliveryId:"wd_fixturetestping1001",status:"queued",createdAt:"2026-07-10T00:00:00.000Z"}}),b="2026-07-10T00:00:00.000Z",j="0x1111111111111111111111111111111111111111";function N(e={}){let t=e.scenario??"happy_path",i=0;return async(s,c)=>{let o=new URL(s),r=(c?.method??"GET").toUpperCase(),n=o.pathname;if(r==="POST"&&n==="/api/merchant/user-links/exchange")return a({appId:"app_fixture",userLinkRef:"ul_fixture_buyer_01",factoUserId:"user_fixture",factoServerWalletAddress:j,grantStatus:"active",pipelineReady:t!=="setup_required",scopes:["wallet.read","payments.write"]});if(r==="POST"&&n==="/api/merchant/payment-readiness")return a({appId:"app_fixture",userLinkRef:"ul_fixture_buyer_01",factoUserId:"user_fixture",factoServerWalletAddress:j,selectedPipelineId:"pipeline_fixture",chainId:84532,protocolId:"aave-v3",assetSymbol:"USDC",spendMode:"direct",pipelineReady:t!=="setup_required",...t==="setup_required"?{notReadyReason:"payment_route_not_provisioned"}:{}});if(r==="POST"&&n==="/api/merchant/checkout-sessions")return a({sessionId:"checkout_fixture",checkoutUrl:"https://dev.facto.to/checkout/checkout_fixture",status:"pending",amount:"9.99",assetSymbol:"USDC",orderRef:"order_fixture"});if(r==="GET"&&n.startsWith("/api/merchant/checkout-sessions/"))return a({sessionId:"checkout_fixture",status:"charged",amount:"9.99",assetSymbol:"USDC",orderRef:"order_fixture",chargeId:"charge_fixture",confirmedAt:b});if(r==="POST"&&n==="/api/merchant/authorization-sessions")return a(z("created"));if(r==="GET"&&n.startsWith("/api/merchant/authorization-sessions/"))return a(z("authorized"));if(r==="GET"&&n.startsWith("/api/merchant/payment-authorizations/"))return a(U());if(r==="POST"&&n==="/api/merchant/payment-options")return a({paymentOptions:[{paymentOptionId:"fpo_fixture",label:"Fixture Direct",ready:t!=="setup_required",isDefault:!0,chainId:84532,chainLabel:"Base Sepolia",protocolLabel:"Aave V3",assetSymbol:"USDC",spendMode:"direct",settlementPath:"direct",...t==="setup_required"?{blockingReason:"setup_required"}:{}}],defaultPaymentOptionId:"fpo_fixture"});if(r==="POST"&&n==="/api/merchant/payments")return t==="idempotency_conflict"?a({code:"idempotency_conflict",message:"fixture idempotency conflict"},409):a(A(t==="declined_before_money"?"declined":"charging"));if(r==="GET"&&n.startsWith("/api/merchant/payments/")){let M=t==="status_progression"?["charging","finalizing","succeeded"]:["succeeded"],p=M[Math.min(i,M.length-1)]??"succeeded";return i+=1,a(A(p))}return r==="DELETE"&&n.startsWith("/api/merchant/user-links/")?new Response(null,{status:204}):r==="GET"&&n==="/api/merchant/payments"?a({data:[A("succeeded")],hasMore:!1}):r==="GET"&&n==="/api/merchant/payment-authorizations"?a({data:[U()],hasMore:!1}):r==="POST"&&n==="/api/merchant/refunds"?a(R()):r==="GET"&&n==="/api/merchant/refunds"?a({data:[R()],hasMore:!1}):r==="GET"&&n.startsWith("/api/merchant/refunds/")?a(R()):r==="POST"&&n==="/api/merchant/webhook-endpoints"?a({...T(),secret:"whsec_fixture_only"}):r==="GET"&&n==="/api/dev/capabilities"?a(y.capabilities):r==="POST"&&n==="/api/dev/faucet/usdc"?a(y.faucetTransfer,202):r==="POST"&&n==="/api/dev/simulate/charge"?a(y.simulation,202):r==="GET"&&n.startsWith("/api/dev/simulations/")?a(y.simulation):r==="POST"&&n.endsWith("/test-delivery")&&n.startsWith("/api/merchant/webhook-endpoints/")?a(y.webhookTestDelivery,202):r==="GET"&&n==="/api/merchant/webhook-endpoints"?a({data:[T()]}):r==="POST"&&n.endsWith("/rotate-secret")&&n.startsWith("/api/merchant/webhook-endpoints/")?a({...T(),secret:"whsec_fixture_rotated"}):r==="GET"&&n.startsWith("/api/merchant/webhook-endpoints/")?a(T()):r==="DELETE"&&n.startsWith("/api/merchant/webhook-endpoints/")?new Response(null,{status:204}):a({code:"fixture_route_not_found",method:r,path:n},404)}}var ne=N;function z(e){return{sessionId:"mauth_fixture",authorizationUrl:"https://dev.facto.to/merchant-mandates/authorize?session=mauth_fixture",status:e,...e==="authorized"?{mandateId:"mandate_fixture"}:{},expiresAt:"2026-07-10T00:15:00.000Z",state:"state_fixture"}}function U(){return{mandateId:"mandate_fixture",appId:"app_fixture",status:"active",allowedUseCases:["immediate","recurring","metered"],limits:{perTxAmount:"100.00",periodAmount:"500.00",period:"monthly"},paymentPath:{ready:!0,summary:"Fixture payment path ready"},createdAt:b}}function A(e){return{paymentId:"mpay_fixture",mandateId:"mandate_fixture",merchantPaymentRef:"payment_fixture",status:e,amount:e==="declined"?"75.00":"9.99",currency:"USDC",useCase:e==="declined"?"metered":"recurring",...e==="declined"?{declineReason:"mandate_limit_exceeded"}:{},...e==="succeeded"?{chargeId:"charge_fixture",txHash:`0x${"1".repeat(64)}`,terminalAt:"2026-07-10T00:00:03.000Z"}:{},createdAt:b,updatedAt:"2026-07-10T00:00:03.000Z"}}function R(){return{refundId:"refund_fixture",paymentId:"mpay_fixture",status:"succeeded",amount:"9.99",currency:"USDC",reason:"requested_by_customer",merchantRefundRef:"merchant_refund_fixture",createdAt:b}}function T(){return{webhookEndpointId:"webhook_fixture",url:"https://merchant.example/facto-webhooks",enabledEvents:["payment.succeeded","payment.failed"],status:"enabled",createdAt:b}}function a(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"content-type":"application/json"}})}
|
package/dist/testing/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { FactoConnectTransport, DevCapabilities, DevFaucetTransfer, DevSimulation, WebhookTestDeliveryAccepted } from '../server/index.cjs';
|
|
2
|
-
import '
|
|
2
|
+
import '@facto-to/engine-wire';
|
|
3
3
|
|
|
4
4
|
declare const MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS: readonly ["listMerchantWorkspaceApps", "createMerchantDevApp", "rotateMerchantWorkspaceCredential"];
|
|
5
5
|
type MerchantPartnerWorkspaceOperationId = (typeof MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS)[number];
|
|
@@ -88,6 +88,7 @@ declare function createMerchantPartnerWorkspaceMock(options?: {
|
|
|
88
88
|
requests: MerchantPartnerWorkspaceRequest[];
|
|
89
89
|
};
|
|
90
90
|
|
|
91
|
+
/** Safe dev projection for Merchant Partner Workspace testing. */
|
|
91
92
|
declare const merchantDevAppFixture: {
|
|
92
93
|
app_id: string;
|
|
93
94
|
display_name: string;
|
|
@@ -96,6 +97,7 @@ declare const merchantDevAppFixture: {
|
|
|
96
97
|
status: "draft";
|
|
97
98
|
allowed_origins: string[];
|
|
98
99
|
};
|
|
100
|
+
/** Negative fixture proving that the testing helper cannot rotate Production apps. */
|
|
99
101
|
declare const merchantProductionAppNegativeFixture: {
|
|
100
102
|
app_id: string;
|
|
101
103
|
display_name: string;
|
|
@@ -105,6 +107,7 @@ declare const merchantProductionAppNegativeFixture: {
|
|
|
105
107
|
allowed_origins: string[];
|
|
106
108
|
credential_version: number;
|
|
107
109
|
};
|
|
110
|
+
/** Read-projection fixture proving future templates remain forward-compatible. */
|
|
108
111
|
declare const merchantFutureTemplateProjectionFixture: {
|
|
109
112
|
app_id: string;
|
|
110
113
|
display_name: string;
|
|
@@ -119,14 +122,22 @@ type FactoConnectFixtureScenario = 'happy_path' | 'setup_required' | 'idempotenc
|
|
|
119
122
|
interface FactoConnectFixtureTransportOptions {
|
|
120
123
|
scenario?: FactoConnectFixtureScenario;
|
|
121
124
|
}
|
|
125
|
+
/** Contract-aligned Dev scenarios for zero-network consumer tests. */
|
|
122
126
|
declare const devScenarios: readonly ["approved", "declined_setup", "declined_limit", "payment_failed"];
|
|
127
|
+
/** Deterministic public Dev projections. They model contract data, not deployment availability. */
|
|
123
128
|
declare const devFixtures: Readonly<{
|
|
124
129
|
capabilities: DevCapabilities;
|
|
125
130
|
faucetTransfer: DevFaucetTransfer;
|
|
126
131
|
simulation: DevSimulation;
|
|
127
132
|
webhookTestDelivery: WebhookTestDeliveryAccepted;
|
|
128
133
|
}>;
|
|
134
|
+
/**
|
|
135
|
+
* Create a deterministic, in-memory transport for server SDK tests and demos.
|
|
136
|
+
* It never performs DNS resolution or network I/O and returns payloads through
|
|
137
|
+
* the same strict parsers used by the real client.
|
|
138
|
+
*/
|
|
129
139
|
declare function createFactoConnectFixtureTransport(options?: FactoConnectFixtureTransportOptions): FactoConnectTransport;
|
|
140
|
+
/** Alias named by `dev-sdk-surface-v1`; remains fully in-memory. */
|
|
130
141
|
declare const createFactoTestTransport: typeof createFactoConnectFixtureTransport;
|
|
131
142
|
|
|
132
143
|
export { type CreateMerchantDevAppRequest, type CredentialRotationResult, type FactoConnectFixtureScenario, type FactoConnectFixtureTransportOptions, MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS, type MerchantAppProjection, type MerchantCapabilityTemplate, type MerchantPartnerWorkspaceClient, MerchantPartnerWorkspaceMockError, type MerchantPartnerWorkspaceOperationId, type MerchantPartnerWorkspaceRequest, type PartnerSessionScope, type PartnerWorkspaceEnvironment, createFactoConnectFixtureTransport, createFactoTestTransport, createMerchantPartnerWorkspaceMock, devFixtures, devScenarios, merchantDevAppFixture, merchantFutureTemplateProjectionFixture, merchantProductionAppNegativeFixture };
|
package/dist/testing/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { FactoConnectTransport, DevCapabilities, DevFaucetTransfer, DevSimulation, WebhookTestDeliveryAccepted } from '../server/index.js';
|
|
2
|
-
import '
|
|
2
|
+
import '@facto-to/engine-wire';
|
|
3
3
|
|
|
4
4
|
declare const MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS: readonly ["listMerchantWorkspaceApps", "createMerchantDevApp", "rotateMerchantWorkspaceCredential"];
|
|
5
5
|
type MerchantPartnerWorkspaceOperationId = (typeof MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS)[number];
|
|
@@ -88,6 +88,7 @@ declare function createMerchantPartnerWorkspaceMock(options?: {
|
|
|
88
88
|
requests: MerchantPartnerWorkspaceRequest[];
|
|
89
89
|
};
|
|
90
90
|
|
|
91
|
+
/** Safe dev projection for Merchant Partner Workspace testing. */
|
|
91
92
|
declare const merchantDevAppFixture: {
|
|
92
93
|
app_id: string;
|
|
93
94
|
display_name: string;
|
|
@@ -96,6 +97,7 @@ declare const merchantDevAppFixture: {
|
|
|
96
97
|
status: "draft";
|
|
97
98
|
allowed_origins: string[];
|
|
98
99
|
};
|
|
100
|
+
/** Negative fixture proving that the testing helper cannot rotate Production apps. */
|
|
99
101
|
declare const merchantProductionAppNegativeFixture: {
|
|
100
102
|
app_id: string;
|
|
101
103
|
display_name: string;
|
|
@@ -105,6 +107,7 @@ declare const merchantProductionAppNegativeFixture: {
|
|
|
105
107
|
allowed_origins: string[];
|
|
106
108
|
credential_version: number;
|
|
107
109
|
};
|
|
110
|
+
/** Read-projection fixture proving future templates remain forward-compatible. */
|
|
108
111
|
declare const merchantFutureTemplateProjectionFixture: {
|
|
109
112
|
app_id: string;
|
|
110
113
|
display_name: string;
|
|
@@ -119,14 +122,22 @@ type FactoConnectFixtureScenario = 'happy_path' | 'setup_required' | 'idempotenc
|
|
|
119
122
|
interface FactoConnectFixtureTransportOptions {
|
|
120
123
|
scenario?: FactoConnectFixtureScenario;
|
|
121
124
|
}
|
|
125
|
+
/** Contract-aligned Dev scenarios for zero-network consumer tests. */
|
|
122
126
|
declare const devScenarios: readonly ["approved", "declined_setup", "declined_limit", "payment_failed"];
|
|
127
|
+
/** Deterministic public Dev projections. They model contract data, not deployment availability. */
|
|
123
128
|
declare const devFixtures: Readonly<{
|
|
124
129
|
capabilities: DevCapabilities;
|
|
125
130
|
faucetTransfer: DevFaucetTransfer;
|
|
126
131
|
simulation: DevSimulation;
|
|
127
132
|
webhookTestDelivery: WebhookTestDeliveryAccepted;
|
|
128
133
|
}>;
|
|
134
|
+
/**
|
|
135
|
+
* Create a deterministic, in-memory transport for server SDK tests and demos.
|
|
136
|
+
* It never performs DNS resolution or network I/O and returns payloads through
|
|
137
|
+
* the same strict parsers used by the real client.
|
|
138
|
+
*/
|
|
129
139
|
declare function createFactoConnectFixtureTransport(options?: FactoConnectFixtureTransportOptions): FactoConnectTransport;
|
|
140
|
+
/** Alias named by `dev-sdk-surface-v1`; remains fully in-memory. */
|
|
130
141
|
declare const createFactoTestTransport: typeof createFactoConnectFixtureTransport;
|
|
131
142
|
|
|
132
143
|
export { type CreateMerchantDevAppRequest, type CredentialRotationResult, type FactoConnectFixtureScenario, type FactoConnectFixtureTransportOptions, MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS, type MerchantAppProjection, type MerchantCapabilityTemplate, type MerchantPartnerWorkspaceClient, MerchantPartnerWorkspaceMockError, type MerchantPartnerWorkspaceOperationId, type MerchantPartnerWorkspaceRequest, type PartnerSessionScope, type PartnerWorkspaceEnvironment, createFactoConnectFixtureTransport, createFactoTestTransport, createMerchantPartnerWorkspaceMock, devFixtures, devScenarios, merchantDevAppFixture, merchantFutureTemplateProjectionFixture, merchantProductionAppNegativeFixture };
|
package/dist/testing/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var q=["listMerchantWorkspaceApps","createMerchantDevApp","rotateMerchantWorkspaceCredential"],L=new Set(["merchant_connect_dev","merchant_webhook_dev"]),d=class extends Error{status;constructor(t,i){super(t),this.name="MerchantPartnerWorkspaceMockError",this.status=i}};function j(e={}){let t=[],i=(e.initialApps??[]).map(x),s=new Set(e.authenticatedSession?.scopes??[]),u=e.now??(()=>new Date),o=new Map,r=new Map,n=i.length+1;return{client:{async listMerchantWorkspaceApps({environment:c}){if(t.push({operationId:"listMerchantWorkspaceApps",method:"GET",path:"/api/partner-workspace/merchant/apps",query:{environment:c}}),c!=="dev")throw new d("Environment filter is outside the mock server-derived context.",403);return{items:i.filter(h=>h.environment===c).map(x)}},async createMerchantDevApp({idempotencyKey:c,body:h}){let y=S(c),m=C(h,["display_name","capability_template","allowed_origins"]),k=I(m.display_name,"Display name",1,160);if(!z(m.capability_template))throw new d("Capability template is not approved for Merchant dev app creation.",400);let l={display_name:k,capability_template:m.capability_template,allowed_origins:U(m.allowed_origins)};t.push({operationId:"createMerchantDevApp",method:"POST",path:"/api/partner-workspace/merchant/apps",headers:{"Idempotency-Key":y},body:l});let p=K(l),g=o.get(y);if(g){if(g.fingerprint!==p)throw E("createMerchantDevApp");return x(g.response)}let w={app_id:`dev_mcid_mock_${String(n).padStart(2,"0")}`,display_name:l.display_name,environment:"dev",capability_template:l.capability_template,status:"draft",allowed_origins:[...l.allowed_origins]};return n+=1,i.push(w),o.set(y,{fingerprint:p,response:x(w)}),x(w)},async rotateMerchantWorkspaceCredential(c){let h=S(c.idempotencyKey),y=C(c.body,["reason"]),m=I(y.reason,"Rotation reason",3,500);t.push({operationId:"rotateMerchantWorkspaceCredential",method:"POST",path:`/api/partner-workspace/merchant/apps/${encodeURIComponent(c.appId)}/credential-rotations`,headers:{"Idempotency-Key":h},authorization:"partnerSession:step_up",body:{reason:m}});let k=G(c.appId,m),l=r.get(h);if(l){if(l.fingerprint!==k)throw E("rotateMerchantWorkspaceCredential");return{...l.response}}if(!s.has("step_up"))throw new d("Recent step-up authentication is required.",403);let p=i.find(F=>F.app_id===c.appId);if(!p)throw new d("Merchant app is not visible in the active server-derived context.",409);if(p.environment!=="dev")throw new d("Merchant app is outside the mock server-derived context.",403);let g=p.credential_version??0;p.credential_version=g+1;let w=new Date(u().getTime()+300*1e3).toISOString(),R={credential_id:`credential:${p.app_id}`,new_version:p.credential_version,old_version_expires_at:w,retrieval_mode:"protected_retrieval_handle",retrieval_handle:`mock-retrieval:${p.app_id}:${p.credential_version}`};return r.set(h,{fingerprint:k,response:{...R}}),R}},requests:t}}function x(e){return{...e,allowed_origins:[...e.allowed_origins]}}function z(e){return L.has(e)}function S(e){if(typeof e!="string")throw _("Idempotency-Key must contain between 16 and 128 characters.");let t=e.trim();if(t.length<16||t.length>128)throw _("Idempotency-Key must contain between 16 and 128 characters.");return t}function C(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw _("Request body must be an object.");let i=new Set(t);if(Reflect.ownKeys(e).some(s=>typeof s!="string"||!i.has(s)))throw _("Request body contains an unsupported property.");return e}function I(e,t,i,s){if(typeof e!="string")throw _(`${t} must be a string.`);let u=e.trim(),o=Array.from(u).length;if(o<i||o>s)throw _(`${t} must contain between ${i} and ${s} characters.`);return u}function U(e){if(!Array.isArray(e)||e.length>20)throw f("Allowed origins must be an array with at most 20 entries.");let t=[],i=new Set;for(let s of e){if(typeof s!="string"||s.length===0||/\s/.test(s))throw f("Each allowed origin must be a non-empty exact URL origin.");let u=/^(https?):\/\/([^/?#\\]+)\/?$/i.exec(s);if(!u)throw f("Allowed origins cannot include a path, query, or fragment.");let o;try{o=new URL(s)}catch{throw f("Allowed origin URL parsing failed.")}if(o.protocol!=="https:"&&o.protocol!=="http:"||o.username!==""||o.password!==""||o.pathname!=="/"||o.search!==""||o.hash!=="")throw f("Allowed origins must be credential-free exact HTTP(S) origins.");if(o.protocol==="http:"){let r=N(u[2]??"").toLowerCase();if(!(r==="localhost"||r==="127.0.0.1"||r==="[::1]"))throw f("Plain HTTP is allowed only for exact loopback origins.")}if(i.has(o.origin))throw f("Allowed origins must be unique after canonicalization.");i.add(o.origin),t.push(o.origin)}return t}function N(e){if(e.startsWith("[")){let i=e.indexOf("]");return i===-1?e:e.slice(0,i+1)}let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function f(e){return new d(e,400)}function _(e){return new d(e,400)}function K(e){return JSON.stringify({display_name:e.display_name,capability_template:e.capability_template,allowed_origins:[...e.allowed_origins].sort()})}function G(e,t){return JSON.stringify({app_id:e,reason:t})}function E(e){return new d(`Idempotency key was already used for a different ${e} request.`,409)}var $={app_id:"dev_mcid_fixture_01",display_name:"Fixture storefront",environment:"dev",capability_template:"merchant_connect_dev",status:"draft",allowed_origins:["https://merchant.example"]},Z={app_id:"production_mcid_fixture_01",display_name:"Production boundary fixture",environment:"production",capability_template:"merchant_connect_dev",status:"active",allowed_origins:["https://merchant.example"],credential_version:3},H={app_id:"app_fixture_future",display_name:"Future template fixture",environment:"dev",capability_template:"merchant_connect_dev_with_diagnostics",status:"active",allowed_origins:["https://merchant.example"],credential_version:1};var Y=Object.freeze(["approved","declined_setup","declined_limit","payment_failed"]),v=Object.freeze({capabilities:{environment:"dev",contractVersion:"2026-07-09",checkedAt:"2026-07-10T00:00:00.000Z",capabilities:[{name:"fixtures",status:"ready",evidenceLevel:"verified",reasonCode:null,verifiedAt:"2026-07-10T00:00:00.000Z",limits:{networkCalls:0}},...["synthetic_identity","faucet","simulation","money_loop","webhook_test_delivery"].map(e=>({name:e,status:"unavailable",evidenceLevel:"contract",reasonCode:"DEV_NOT_DEPLOYED",verifiedAt:null,limits:{}}))]},faucetTransfer:{faucetTransferId:"sft_fixture_1001",userLinkRef:"ul_fixture_buyer_01",amount:{amount:"10.00",currency:"USDC"},status:"accepted",createdAt:"2026-07-10T00:00:00.000Z"},simulation:{simulationId:"sim_fixture_1001",scenario:"approved",executionMode:"pre_admission",status:"accepted",reasonCode:null,authorizationRef:null,chargeRef:null,createdAt:"2026-07-10T00:00:00.000Z",updatedAt:"2026-07-10T00:00:00.000Z"},webhookTestDelivery:{eventId:"evt_fixturetestping1001",deliveryId:"wd_fixturetestping1001",status:"queued",createdAt:"2026-07-10T00:00:00.000Z"}}),b="2026-07-10T00:00:00.000Z",W="0x1111111111111111111111111111111111111111";function V(e={}){let t=e.scenario??"happy_path",i=0;return async(s,u)=>{let o=new URL(s),r=(u?.method??"GET").toUpperCase(),n=o.pathname;if(r==="POST"&&n==="/api/merchant/user-links/exchange")return a({appId:"app_fixture",userLinkRef:"ul_fixture_buyer_01",factoUserId:"user_fixture",factoServerWalletAddress:W,grantStatus:"active",pipelineReady:t!=="setup_required",scopes:["wallet.read","payments.write"]});if(r==="POST"&&n==="/api/merchant/payment-readiness")return a({appId:"app_fixture",userLinkRef:"ul_fixture_buyer_01",factoUserId:"user_fixture",factoServerWalletAddress:W,readinessScope:"account_default",chainId:84532,protocolId:"aave-v3",assetSymbol:"USDC",spendMode:"direct",pipelineReady:t!=="setup_required",...t==="setup_required"?{notReadyReason:"payment_route_not_provisioned"}:{}});if(r==="POST"&&n==="/api/merchant/checkout-sessions")return a({sessionId:"checkout_fixture",checkoutUrl:"https://dev.facto.to/checkout/checkout_fixture",status:"pending",amount:"9.99",assetSymbol:"USDC",orderRef:"order_fixture"});if(r==="GET"&&n.startsWith("/api/merchant/checkout-sessions/"))return a({sessionId:"checkout_fixture",status:"charged",amount:"9.99",assetSymbol:"USDC",orderRef:"order_fixture",chargeId:"charge_fixture",confirmedAt:b});if(r==="POST"&&n==="/api/merchant/authorization-sessions")return a(O("created"));if(r==="GET"&&n.startsWith("/api/merchant/authorization-sessions/"))return a(O("authorized"));if(r==="GET"&&n.startsWith("/api/merchant/payment-authorizations/"))return a(D());if(r==="POST"&&n==="/api/merchant/payment-options")return a({paymentOptions:[{paymentOptionId:"fpo_fixture",label:"Fixture Direct",ready:t!=="setup_required",isDefault:!0,chainId:84532,chainLabel:"Base Sepolia",protocolLabel:"Aave V3",assetSymbol:"USDC",spendMode:"direct",settlementPath:"direct",...t==="setup_required"?{blockingReason:"setup_required"}:{}}],defaultPaymentOptionId:"fpo_fixture"});if(r==="POST"&&n==="/api/merchant/payments")return t==="idempotency_conflict"?a({code:"idempotency_conflict",message:"fixture idempotency conflict"},409):a(A(t==="declined_before_money"?"declined":"charging"));if(r==="GET"&&n.startsWith("/api/merchant/payments/")){let M=t==="status_progression"?["charging","finalizing","succeeded"]:["succeeded"],c=M[Math.min(i,M.length-1)]??"succeeded";return i+=1,a(A(c))}return r==="DELETE"&&n.startsWith("/api/merchant/user-links/")?new Response(null,{status:204}):r==="GET"&&n==="/api/merchant/payments"?a({data:[A("succeeded")],hasMore:!1}):r==="GET"&&n==="/api/merchant/payment-authorizations"?a({data:[D()],hasMore:!1}):r==="POST"&&n==="/api/merchant/refunds"?a(P()):r==="GET"&&n==="/api/merchant/refunds"?a({data:[P()],hasMore:!1}):r==="GET"&&n.startsWith("/api/merchant/refunds/")?a(P()):r==="POST"&&n==="/api/merchant/webhook-endpoints"?a({...T(),secret:"whsec_fixture_only"}):r==="GET"&&n==="/api/dev/capabilities"?a(v.capabilities):r==="POST"&&n==="/api/dev/faucet/usdc"?a(v.faucetTransfer,202):r==="POST"&&n==="/api/dev/simulate/charge"?a(v.simulation,202):r==="GET"&&n.startsWith("/api/dev/simulations/")?a(v.simulation):r==="POST"&&n.endsWith("/test-delivery")&&n.startsWith("/api/merchant/webhook-endpoints/")?a(v.webhookTestDelivery,202):r==="GET"&&n==="/api/merchant/webhook-endpoints"?a({data:[T()]}):r==="POST"&&n.endsWith("/rotate-secret")&&n.startsWith("/api/merchant/webhook-endpoints/")?a({...T(),secret:"whsec_fixture_rotated"}):r==="GET"&&n.startsWith("/api/merchant/webhook-endpoints/")?a(T()):r==="DELETE"&&n.startsWith("/api/merchant/webhook-endpoints/")?new Response(null,{status:204}):a({code:"fixture_route_not_found",method:r,path:n},404)}}var Q=V;function O(e){return{sessionId:"mauth_fixture",authorizationUrl:"https://dev.facto.to/merchant-mandates/authorize?session=mauth_fixture",status:e,...e==="authorized"?{mandateId:"mandate_fixture"}:{},expiresAt:"2026-07-10T00:15:00.000Z",state:"state_fixture"}}function D(){return{mandateId:"mandate_fixture",appId:"app_fixture",status:"active",allowedUseCases:["immediate","recurring","metered"],limits:{perTxAmount:"100.00",periodAmount:"500.00",period:"monthly"},paymentPath:{ready:!0,summary:"Fixture payment path ready"},createdAt:b}}function A(e){return{paymentId:"mpay_fixture",mandateId:"mandate_fixture",merchantPaymentRef:"payment_fixture",status:e,amount:e==="declined"?"75.00":"9.99",currency:"USDC",useCase:e==="declined"?"metered":"recurring",...e==="declined"?{declineReason:"mandate_limit_exceeded"}:{},...e==="succeeded"?{chargeId:"charge_fixture",txHash:`0x${"1".repeat(64)}`,terminalAt:"2026-07-10T00:00:03.000Z"}:{},createdAt:b,updatedAt:"2026-07-10T00:00:03.000Z"}}function P(){return{refundId:"refund_fixture",paymentId:"mpay_fixture",status:"succeeded",amount:"9.99",currency:"USDC",reason:"requested_by_customer",merchantRefundRef:"merchant_refund_fixture",createdAt:b}}function T(){return{webhookEndpointId:"webhook_fixture",url:"https://merchant.example/facto-webhooks",enabledEvents:["payment.succeeded","payment.failed"],status:"enabled",createdAt:b}}function a(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"content-type":"application/json"}})}export{q as MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS,d as MerchantPartnerWorkspaceMockError,V as createFactoConnectFixtureTransport,Q as createFactoTestTransport,j as createMerchantPartnerWorkspaceMock,v as devFixtures,Y as devScenarios,$ as merchantDevAppFixture,H as merchantFutureTemplateProjectionFixture,Z as merchantProductionAppNegativeFixture};
|
|
1
|
+
var q=["listMerchantWorkspaceApps","createMerchantDevApp","rotateMerchantWorkspaceCredential"],L=new Set(["merchant_connect_dev","merchant_webhook_dev"]),d=class extends Error{status;constructor(t,i){super(t),this.name="MerchantPartnerWorkspaceMockError",this.status=i}};function j(e={}){let t=[],i=(e.initialApps??[]).map(x),s=new Set(e.authenticatedSession?.scopes??[]),u=e.now??(()=>new Date),o=new Map,r=new Map,n=i.length+1;return{client:{async listMerchantWorkspaceApps({environment:c}){if(t.push({operationId:"listMerchantWorkspaceApps",method:"GET",path:"/api/partner-workspace/merchant/apps",query:{environment:c}}),c!=="dev")throw new d("Environment filter is outside the mock server-derived context.",403);return{items:i.filter(h=>h.environment===c).map(x)}},async createMerchantDevApp({idempotencyKey:c,body:h}){let y=S(c),m=I(h,["display_name","capability_template","allowed_origins"]),k=C(m.display_name,"Display name",1,160);if(!z(m.capability_template))throw new d("Capability template is not approved for Merchant dev app creation.",400);let l={display_name:k,capability_template:m.capability_template,allowed_origins:U(m.allowed_origins)};t.push({operationId:"createMerchantDevApp",method:"POST",path:"/api/partner-workspace/merchant/apps",headers:{"Idempotency-Key":y},body:l});let p=K(l),g=o.get(y);if(g){if(g.fingerprint!==p)throw E("createMerchantDevApp");return x(g.response)}let w={app_id:`dev_mcid_mock_${String(n).padStart(2,"0")}`,display_name:l.display_name,environment:"dev",capability_template:l.capability_template,status:"draft",allowed_origins:[...l.allowed_origins]};return n+=1,i.push(w),o.set(y,{fingerprint:p,response:x(w)}),x(w)},async rotateMerchantWorkspaceCredential(c){let h=S(c.idempotencyKey),y=I(c.body,["reason"]),m=C(y.reason,"Rotation reason",3,500);t.push({operationId:"rotateMerchantWorkspaceCredential",method:"POST",path:`/api/partner-workspace/merchant/apps/${encodeURIComponent(c.appId)}/credential-rotations`,headers:{"Idempotency-Key":h},authorization:"partnerSession:step_up",body:{reason:m}});let k=G(c.appId,m),l=r.get(h);if(l){if(l.fingerprint!==k)throw E("rotateMerchantWorkspaceCredential");return{...l.response}}if(!s.has("step_up"))throw new d("Recent step-up authentication is required.",403);let p=i.find(F=>F.app_id===c.appId);if(!p)throw new d("Merchant app is not visible in the active server-derived context.",409);if(p.environment!=="dev")throw new d("Merchant app is outside the mock server-derived context.",403);let g=p.credential_version??0;p.credential_version=g+1;let w=new Date(u().getTime()+300*1e3).toISOString(),R={credential_id:`credential:${p.app_id}`,new_version:p.credential_version,old_version_expires_at:w,retrieval_mode:"protected_retrieval_handle",retrieval_handle:`mock-retrieval:${p.app_id}:${p.credential_version}`};return r.set(h,{fingerprint:k,response:{...R}}),R}},requests:t}}function x(e){return{...e,allowed_origins:[...e.allowed_origins]}}function z(e){return L.has(e)}function S(e){if(typeof e!="string")throw _("Idempotency-Key must contain between 16 and 128 characters.");let t=e.trim();if(t.length<16||t.length>128)throw _("Idempotency-Key must contain between 16 and 128 characters.");return t}function I(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw _("Request body must be an object.");let i=new Set(t);if(Reflect.ownKeys(e).some(s=>typeof s!="string"||!i.has(s)))throw _("Request body contains an unsupported property.");return e}function C(e,t,i,s){if(typeof e!="string")throw _(`${t} must be a string.`);let u=e.trim(),o=Array.from(u).length;if(o<i||o>s)throw _(`${t} must contain between ${i} and ${s} characters.`);return u}function U(e){if(!Array.isArray(e)||e.length>20)throw f("Allowed origins must be an array with at most 20 entries.");let t=[],i=new Set;for(let s of e){if(typeof s!="string"||s.length===0||/\s/.test(s))throw f("Each allowed origin must be a non-empty exact URL origin.");let u=/^(https?):\/\/([^/?#\\]+)\/?$/i.exec(s);if(!u)throw f("Allowed origins cannot include a path, query, or fragment.");let o;try{o=new URL(s)}catch{throw f("Allowed origin URL parsing failed.")}if(o.protocol!=="https:"&&o.protocol!=="http:"||o.username!==""||o.password!==""||o.pathname!=="/"||o.search!==""||o.hash!=="")throw f("Allowed origins must be credential-free exact HTTP(S) origins.");if(o.protocol==="http:"){let r=N(u[2]??"").toLowerCase();if(!(r==="localhost"||r==="127.0.0.1"||r==="[::1]"))throw f("Plain HTTP is allowed only for exact loopback origins.")}if(i.has(o.origin))throw f("Allowed origins must be unique after canonicalization.");i.add(o.origin),t.push(o.origin)}return t}function N(e){if(e.startsWith("[")){let i=e.indexOf("]");return i===-1?e:e.slice(0,i+1)}let t=e.lastIndexOf(":");return t===-1?e:e.slice(0,t)}function f(e){return new d(e,400)}function _(e){return new d(e,400)}function K(e){return JSON.stringify({display_name:e.display_name,capability_template:e.capability_template,allowed_origins:[...e.allowed_origins].sort()})}function G(e,t){return JSON.stringify({app_id:e,reason:t})}function E(e){return new d(`Idempotency key was already used for a different ${e} request.`,409)}var $={app_id:"dev_mcid_fixture_01",display_name:"Fixture storefront",environment:"dev",capability_template:"merchant_connect_dev",status:"draft",allowed_origins:["https://merchant.example"]},Z={app_id:"production_mcid_fixture_01",display_name:"Production boundary fixture",environment:"production",capability_template:"merchant_connect_dev",status:"active",allowed_origins:["https://merchant.example"],credential_version:3},H={app_id:"app_fixture_future",display_name:"Future template fixture",environment:"dev",capability_template:"merchant_connect_dev_with_diagnostics",status:"active",allowed_origins:["https://merchant.example"],credential_version:1};var Y=Object.freeze(["approved","declined_setup","declined_limit","payment_failed"]),v=Object.freeze({capabilities:{environment:"dev",contractVersion:"2026-07-09",checkedAt:"2026-07-10T00:00:00.000Z",capabilities:[{name:"fixtures",status:"ready",evidenceLevel:"verified",reasonCode:null,verifiedAt:"2026-07-10T00:00:00.000Z",limits:{networkCalls:0}},...["synthetic_identity","faucet","simulation","money_loop","webhook_test_delivery"].map(e=>({name:e,status:"unavailable",evidenceLevel:"contract",reasonCode:"DEV_NOT_DEPLOYED",verifiedAt:null,limits:{}}))]},faucetTransfer:{faucetTransferId:"sft_fixture_1001",userLinkRef:"ul_fixture_buyer_01",amount:{amount:"10.00",currency:"USDC"},status:"accepted",createdAt:"2026-07-10T00:00:00.000Z"},simulation:{simulationId:"sim_fixture_1001",scenario:"approved",executionMode:"pre_admission",status:"accepted",reasonCode:null,authorizationRef:null,chargeRef:null,createdAt:"2026-07-10T00:00:00.000Z",updatedAt:"2026-07-10T00:00:00.000Z"},webhookTestDelivery:{eventId:"evt_fixturetestping1001",deliveryId:"wd_fixturetestping1001",status:"queued",createdAt:"2026-07-10T00:00:00.000Z"}}),b="2026-07-10T00:00:00.000Z",W="0x1111111111111111111111111111111111111111";function V(e={}){let t=e.scenario??"happy_path",i=0;return async(s,u)=>{let o=new URL(s),r=(u?.method??"GET").toUpperCase(),n=o.pathname;if(r==="POST"&&n==="/api/merchant/user-links/exchange")return a({appId:"app_fixture",userLinkRef:"ul_fixture_buyer_01",factoUserId:"user_fixture",factoServerWalletAddress:W,grantStatus:"active",pipelineReady:t!=="setup_required",scopes:["wallet.read","payments.write"]});if(r==="POST"&&n==="/api/merchant/payment-readiness")return a({appId:"app_fixture",userLinkRef:"ul_fixture_buyer_01",factoUserId:"user_fixture",factoServerWalletAddress:W,selectedPipelineId:"pipeline_fixture",chainId:84532,protocolId:"aave-v3",assetSymbol:"USDC",spendMode:"direct",pipelineReady:t!=="setup_required",...t==="setup_required"?{notReadyReason:"payment_route_not_provisioned"}:{}});if(r==="POST"&&n==="/api/merchant/checkout-sessions")return a({sessionId:"checkout_fixture",checkoutUrl:"https://dev.facto.to/checkout/checkout_fixture",status:"pending",amount:"9.99",assetSymbol:"USDC",orderRef:"order_fixture"});if(r==="GET"&&n.startsWith("/api/merchant/checkout-sessions/"))return a({sessionId:"checkout_fixture",status:"charged",amount:"9.99",assetSymbol:"USDC",orderRef:"order_fixture",chargeId:"charge_fixture",confirmedAt:b});if(r==="POST"&&n==="/api/merchant/authorization-sessions")return a(O("created"));if(r==="GET"&&n.startsWith("/api/merchant/authorization-sessions/"))return a(O("authorized"));if(r==="GET"&&n.startsWith("/api/merchant/payment-authorizations/"))return a(D());if(r==="POST"&&n==="/api/merchant/payment-options")return a({paymentOptions:[{paymentOptionId:"fpo_fixture",label:"Fixture Direct",ready:t!=="setup_required",isDefault:!0,chainId:84532,chainLabel:"Base Sepolia",protocolLabel:"Aave V3",assetSymbol:"USDC",spendMode:"direct",settlementPath:"direct",...t==="setup_required"?{blockingReason:"setup_required"}:{}}],defaultPaymentOptionId:"fpo_fixture"});if(r==="POST"&&n==="/api/merchant/payments")return t==="idempotency_conflict"?a({code:"idempotency_conflict",message:"fixture idempotency conflict"},409):a(A(t==="declined_before_money"?"declined":"charging"));if(r==="GET"&&n.startsWith("/api/merchant/payments/")){let M=t==="status_progression"?["charging","finalizing","succeeded"]:["succeeded"],c=M[Math.min(i,M.length-1)]??"succeeded";return i+=1,a(A(c))}return r==="DELETE"&&n.startsWith("/api/merchant/user-links/")?new Response(null,{status:204}):r==="GET"&&n==="/api/merchant/payments"?a({data:[A("succeeded")],hasMore:!1}):r==="GET"&&n==="/api/merchant/payment-authorizations"?a({data:[D()],hasMore:!1}):r==="POST"&&n==="/api/merchant/refunds"?a(P()):r==="GET"&&n==="/api/merchant/refunds"?a({data:[P()],hasMore:!1}):r==="GET"&&n.startsWith("/api/merchant/refunds/")?a(P()):r==="POST"&&n==="/api/merchant/webhook-endpoints"?a({...T(),secret:"whsec_fixture_only"}):r==="GET"&&n==="/api/dev/capabilities"?a(v.capabilities):r==="POST"&&n==="/api/dev/faucet/usdc"?a(v.faucetTransfer,202):r==="POST"&&n==="/api/dev/simulate/charge"?a(v.simulation,202):r==="GET"&&n.startsWith("/api/dev/simulations/")?a(v.simulation):r==="POST"&&n.endsWith("/test-delivery")&&n.startsWith("/api/merchant/webhook-endpoints/")?a(v.webhookTestDelivery,202):r==="GET"&&n==="/api/merchant/webhook-endpoints"?a({data:[T()]}):r==="POST"&&n.endsWith("/rotate-secret")&&n.startsWith("/api/merchant/webhook-endpoints/")?a({...T(),secret:"whsec_fixture_rotated"}):r==="GET"&&n.startsWith("/api/merchant/webhook-endpoints/")?a(T()):r==="DELETE"&&n.startsWith("/api/merchant/webhook-endpoints/")?new Response(null,{status:204}):a({code:"fixture_route_not_found",method:r,path:n},404)}}var Q=V;function O(e){return{sessionId:"mauth_fixture",authorizationUrl:"https://dev.facto.to/merchant-mandates/authorize?session=mauth_fixture",status:e,...e==="authorized"?{mandateId:"mandate_fixture"}:{},expiresAt:"2026-07-10T00:15:00.000Z",state:"state_fixture"}}function D(){return{mandateId:"mandate_fixture",appId:"app_fixture",status:"active",allowedUseCases:["immediate","recurring","metered"],limits:{perTxAmount:"100.00",periodAmount:"500.00",period:"monthly"},paymentPath:{ready:!0,summary:"Fixture payment path ready"},createdAt:b}}function A(e){return{paymentId:"mpay_fixture",mandateId:"mandate_fixture",merchantPaymentRef:"payment_fixture",status:e,amount:e==="declined"?"75.00":"9.99",currency:"USDC",useCase:e==="declined"?"metered":"recurring",...e==="declined"?{declineReason:"mandate_limit_exceeded"}:{},...e==="succeeded"?{chargeId:"charge_fixture",txHash:`0x${"1".repeat(64)}`,terminalAt:"2026-07-10T00:00:03.000Z"}:{},createdAt:b,updatedAt:"2026-07-10T00:00:03.000Z"}}function P(){return{refundId:"refund_fixture",paymentId:"mpay_fixture",status:"succeeded",amount:"9.99",currency:"USDC",reason:"requested_by_customer",merchantRefundRef:"merchant_refund_fixture",createdAt:b}}function T(){return{webhookEndpointId:"webhook_fixture",url:"https://merchant.example/facto-webhooks",enabledEvents:["payment.succeeded","payment.failed"],status:"enabled",createdAt:b}}function a(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"content-type":"application/json"}})}export{q as MERCHANT_PARTNER_WORKSPACE_OPERATION_IDS,d as MerchantPartnerWorkspaceMockError,V as createFactoConnectFixtureTransport,Q as createFactoTestTransport,j as createMerchantPartnerWorkspaceMock,v as devFixtures,Y as devScenarios,$ as merchantDevAppFixture,H as merchantFutureTemplateProjectionFixture,Z as merchantProductionAppNegativeFixture};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@facto-to/connect",
|
|
3
|
-
"version": "0.0.1-
|
|
3
|
+
"version": "0.0.1-beta1",
|
|
4
4
|
"description": "Facto Connect SDK for linking partner users to Facto accounts and payment routes.",
|
|
5
5
|
"homepage": "https://facto.to",
|
|
6
6
|
"author": "Facto (https://facto.to)",
|
|
@@ -89,18 +89,15 @@
|
|
|
89
89
|
"prepublishOnly": "npm run build"
|
|
90
90
|
},
|
|
91
91
|
"devDependencies": {
|
|
92
|
-
"@facto-to/chains": "0.0.1-
|
|
92
|
+
"@facto-to/chains": "0.0.1-beta1",
|
|
93
93
|
"@facto-to/engine-wire": "0.2.0",
|
|
94
|
-
"@types/node": "^
|
|
95
|
-
"jsdom": "^
|
|
94
|
+
"@types/node": "^25.9.3",
|
|
95
|
+
"jsdom": "^27.1.0",
|
|
96
96
|
"tsup": "^8.5.0",
|
|
97
97
|
"typescript": "^5.9.3",
|
|
98
|
-
"vitest": "^
|
|
98
|
+
"vitest": "^3.2.1"
|
|
99
99
|
},
|
|
100
100
|
"publishConfig": {
|
|
101
101
|
"access": "restricted"
|
|
102
|
-
},
|
|
103
|
-
"engines": {
|
|
104
|
-
"node": ">=20.9.0"
|
|
105
102
|
}
|
|
106
103
|
}
|
|
@@ -1,114 +0,0 @@
|
|
|
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 };
|