@facto-to/connect 0.0.1-beta.5 → 0.0.1-beta2
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 +1 -84
- 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 +303 -9
- package/dist/server/index.d.ts +303 -9
- 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 le,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","payment_option_not_pinned","idempotency_conflict"];var Q=["payment_route_not_provisioned","protocol_config_incomplete"];var be=["psp_connect_sandbox","psp_mandate_sandbox"],X={psp_connect_sandbox:["readiness.read","authorizations.request"],psp_mandate_sandbox:["readiness.read","authorizations.request","payments.execute","refunds.execute"]};function Se(t){return X[t].includes("payments.execute")}var Re={dev:{clientIdPrefix:"dev_pspid_",clientSecretPrefix:"dev_pspsk_"},lab:{clientIdPrefix:"lab_pspid_"}},Ae="psp";function _e(t,e){return{...t,...e.ref===void 0?{}:{subMerchantRef:e.ref},...e.displayName===void 0?{}:{subMerchantDisplayName:e.displayName}}}function Ie(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"}),T=Object.freeze({dev:"https://dev.facto.to",production:"https://app.facto.to"}),Ee=Object.freeze({dev:Object.freeze(["dev_mcid_","dev_pspid_","dev_cpid_"]),production:Object.freeze(["mcid_","pspid_","cpid_"])});function Pe(t){if(typeof t=="string"){for(let e of["dev","production"])for(let n of Ee[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"}),S=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 we(t){let e=t.headers.get("retry-after");if(!e)return;let n=Number(e.trim());return Number.isFinite(n)&&n>=0?n:void 0}function Te(t,e){return t<=0?Promise.resolve():new Promise((n,a)=>{if(e?.aborted){a(new S("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}));return}let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),a(new S("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}))};e?.addEventListener("abort",s,{once:!0})})}async function Me(t,e={}){let n=e.maxRetries??2,a=e.baseDelayMs??200,o=e.maxDelayMs??5e3,s=e.respectRetryAfter??!0,d=e.sleep??Te,u=0;for(;;)try{return await t()}catch(m){if(!(m instanceof S)||!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)),g=i*.25*Math.random(),L=r??i+g;e.onRetry?.({attempt:u,error:m,delayMs:L}),await d(L,e.signal)}}function ke(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)");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 xe(t){let e=We(t),n=`Basic ${Wt(`${e.clientId}:${e.clientSecret}`)}`,a=(r,i)=>R(e,r,{code:i.code,state:i.state,nonce:i.nonce},n,ct),o=(r,i)=>R(e,r,dt(e,i),n,ut),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,ie),d=(r,i)=>b(e,`${r}/${encodeURIComponent(i)}`,n,ie),u=(r,i)=>b(e,`${r}/${encodeURIComponent(i)}`,n,de),m=(r,i)=>{let g={mandateId:i.mandateId,merchantPaymentRef:i.merchantPaymentRef,amount:i.amount,currency:i.currency,useCase:i.useCase};return i.paymentOptionId!==void 0&&(g.paymentOptionId=i.paymentOptionId),i.description!==void 0&&(g.description=i.description),i.metadata!==void 0&&(g.metadata=i.metadata),R(e,r,g,n,U,{"Idempotency-Key":i.idempotencyKey},[402])},y=(r,i)=>b(e,`${r}/${encodeURIComponent(i)}`,n,U);return{createHostedConnectUrl(r){let i=r.hostedConnectUrl??e.hostedConnectUrl;if(r.hostedConnectUrl!==void 0){let g=v(r.hostedConnectUrl,T,"hostedConnectUrl",!0);g!==void 0&&g!==F(e.environment)&&l("hostedConnectUrl conflicts with the configured environment")}return ke({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 y(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,lt)},getCheckoutSession(r){return b(e,`${h.checkoutSessions}/${encodeURIComponent(r)}`,n,mt)},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,yt)},createMandatePayment(r){return m(h.payments,r)},getMandatePayment(r){return y(h.payments,r)},onStatus(r,i,g){return Ue(()=>b(e,`${h.payments}/${encodeURIComponent(r)}`,n,U),i,g)},revokeUserLink(r){return re(e,`/api/merchant/user-links/${encodeURIComponent(r)}`,n)},listMerchantPayments(r={}){return b(e,z("/api/merchant/payments",{limit:r.limit,startingAfter:r.startingAfter,createdAfter:r.createdAfter,createdBefore:r.createdBefore,authorizationId:r.authorizationId,status:r.status}),n,i=>H(i,U))},listPaymentAuthorizations(r={}){return b(e,z("/api/merchant/payment-authorizations",{limit:r.limit,startingAfter:r.startingAfter,userLinkRef:r.userLinkRef,status:r.status}),n,i=>H(i,de))},createRefund(r){let i={paymentId:r.paymentId};return r.amount!==void 0&&(i.amount=r.amount),r.reason!==void 0&&(i.reason=r.reason),r.merchantRefundRef!==void 0&&(i.merchantRefundRef=r.merchantRefundRef),R(e,"/api/merchant/refunds",i,n,$,{"Idempotency-Key":r.idempotencyKey},[402])},getRefund(r){return b(e,`/api/merchant/refunds/${encodeURIComponent(r)}`,n,$)},listRefunds(r={}){return b(e,z("/api/merchant/refunds",{limit:r.limit,startingAfter:r.startingAfter,paymentId:r.paymentId}),n,i=>H(i,$))},createWebhookEndpoint(r){return R(e,"/api/merchant/webhook-endpoints",{url:r.url,enabledEvents:r.enabledEvents},n,ae)},listWebhookEndpoints(){return b(e,"/api/merchant/webhook-endpoints",n,r=>{let g=f(r).data;if(!Array.isArray(g))throw new Error("expected data array");return g.map(K)})},getWebhookEndpoint(r){return b(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n,K)},deleteWebhookEndpoint(r){return re(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n)},rotateWebhookSecret(r){return R(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}/rotate-secret`,{},n,ae)},getDevCapabilities(){return N(e,"getDevCapabilities"),b(e,"/api/dev/capabilities",n,nt)},fundDevUser(r){return N(e,"fundDevUser"),ee(r.userLinkRef),te(r.amount),ne(r.idempotencyKey),R(e,"/api/dev/faucet/usdc",{userLinkRef:r.userLinkRef,amount:r.amount},n,ot,{"Idempotency-Key":r.idempotencyKey})},simulateDevCharge(r){return N(e,"simulateDevCharge"),ee(r.userLinkRef),r.cardRef!==void 0&&I(r.cardRef,"card_","cardRef"),te(r.amount),$e(r.scenario),r.merchantReference!==void 0&&(typeof r.merchantReference!="string"||r.merchantReference.length>120)&&l("merchantReference must not exceed 120 characters"),ne(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,oe,{"Idempotency-Key":r.idempotencyKey})},getDevSimulation(r){return N(e,"getDevSimulation"),I(r,"sim_","simulationId"),b(e,`/api/dev/simulations/${encodeURIComponent(r)}`,n,oe)},sendWebhookTestDelivery(r){return ze(e),He(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,st)}}}var Le=new Set(["declined","succeeded","paid_via_coverage","failed","canceled"]);function Ne(t){return Le.has(t)}async function Ue(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,y=a,r;for(;;){Oe(u);let i=await t();if(i.status!==r&&(r=i.status,e(i)),Ne(i.status))return i;let g=m-Date.now();if(g<=0)return i;await De(Math.min(y,g),u),y=Math.min(y*s,o)}}function Oe(t){if(t?.aborted)throw new S("FACTO_STATUS_POLL_ABORTED","mandate payment polling aborted",{retryable:!1})}function De(t,e){return new Promise((n,a)=>{let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),a(new S("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 Fe=Object.freeze(["dev","production","sandbox"]);function We(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&&!Fe.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/reference/sdk"),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?v(t.apiBaseUrl,W,"apiBaseUrl",!1):void 0,a=t.hostedConnectUrl?v(t.hostedConnectUrl,T,"hostedConnectUrl",!0):void 0;n!==void 0&&a!==void 0&&n!==a&&l("apiBaseUrl and hostedConnectUrl target different Facto environments");let o=Pe(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/reference/sdk");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]),m=J(t.hostedConnectUrl??T[d]),y=v(u,W,"apiBaseUrl",!1);return v(m,T,"hostedConnectUrl",!0),qe(t.clientId,y),{appId:t.appId,clientId:t.clientId,clientSecret:t.clientSecret,environment:s,apiBaseUrl:u,hostedConnectUrl:m,transport:t.transport??t.fetch??((r,i)=>globalThis.fetch(r,i)),...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.retry===void 0?{}:{retry:t.retry},...t.signal===void 0?{}:{signal:t.signal}}}function N(t,e){F(t.environment)!=="dev"&&l(`${e} is available only in the sandbox/dev environment`)}function ze(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 ee(t){I(t,"ul_","userLinkRef")}function He(t){(typeof t!="string"||!/^we_[A-Za-z0-9]+$/.test(t))&&l("webhookEndpointId must be an opaque we_ reference")}function te(t){(typeof t!="object"||t===null||t.currency!=="USDC"||typeof t.amount!="string"||!/^[0-9]+(?:\.[0-9]{1,6})?$/.test(t.amount))&&l("Dev amount must be a USDC decimal with at most six fractional digits")}function $e(t){(typeof t!="string"||!pe.includes(t))&&l("unknown Dev simulation scenario")}function ne(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 qe(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 v(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 m=o.pathname==="/"||a&&o.pathname==="/connect";return(o.origin!==u.origin||o.username!==""||o.password!==""||!m||o.search!==""||o.hash!=="")&&l(`${n} is not the exact published ${d} endpoint`),d}}async function R(t,e,n,a,o,s={},d=[]){let u=await me(t,async()=>{let m=await Y(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 S("FACTO_ENGINE_RESPONSE_INVALID","Facto Engine returned an invalid response",{retryable:!1,details:m})}}async function b(t,e,n,a){let o=await me(t,async()=>{let s=await Y(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 S("FACTO_ENGINE_RESPONSE_INVALID","Facto Engine returned an invalid response",{retryable:!1,details:s})}}async function re(t,e,n){let a=await Y(t,`${t.apiBaseUrl}${e}`,{method:"DELETE",headers:{authorization:n}});if(!a.ok)throw await j(a)}async function j(t){return new S("FACTO_ENGINE_REQUEST_FAILED",`Facto Engine request failed with status ${t.status}`,{retryable:t.status===429||t.status>=500,status:t.status,details:await Ft(t),retryAfterSeconds:we(t)})}function me(t,e,n){return n?Me(e,{...t.retry,signal:t.signal??t.retry?.signal}):e()}function Y(t,e,n){return t.timeoutMs===void 0?t.transport(e,{...n,signal:t.signal}):Ve(t,e,n)}function Ve(t,e,n){let a=new AbortController,o=()=>a.abort();return t.signal?.aborted?Promise.reject(new S("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 S("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 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=f(t),a=n.data;if(!Array.isArray(a))throw new Error("expected data array");return{data:a.map(e),hasMore:P(n,"hasMore")}}var Be=["pending","succeeded","failed"],Ke=["requested_by_customer","duplicate","fraudulent","other"];function Je(t,e){let n=t[e];if(typeof n!="string"||!Be.includes(n))throw new Error(`expected refund status at ${e}`);return n}function je(t,e){let n=t[e];if(n!==void 0){if(typeof n!="string"||!Ke.includes(n))throw new Error(`expected refund reason at ${e}`);return n}}function $(t){let e=f(t),n=je(e,"reason"),a=A(e,"merchantRefundRef");return{refundId:c(e,"refundId"),paymentId:c(e,"paymentId"),status:Je(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 Ye=["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 Ge(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"||!Ye.includes(a))throw new Error(`unknown webhook event type: ${String(a)}`);return a})}function K(t){let e=f(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:Ge(e,"enabledEvents"),status:n,createdAt:c(e,"createdAt")}}function ae(t){let e=K(t),n=f(t);return{...e,secret:c(n,"secret")}}var D=["fixtures","synthetic_identity","faucet","simulation","money_loop","webhook_test_delivery"],Ze=["unavailable","degraded","ready"],Qe=["contract","implemented","deployed","verified"],pe=["approved","declined_setup","declined_limit","payment_failed"],Xe=["pre_admission","onchain_test_assets"],et=["accepted","processing","succeeded","failed","declined"],tt=["accepted","broadcast","confirmed","failed"];function nt(t){let e=f(t),n=e.capabilities;if(!Array.isArray(n)||n.length!==D.length)throw new Error("expected exactly six Dev capabilities");let a=n.map(rt),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 rt(t){let e=f(t),n=C(e,"name",D,"Dev capability name"),a=C(e,"status",Ze,"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=it(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 at(t){let e=f(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 ot(t){let e=f(t);return{faucetTransferId:k(e,"faucetTransferId","sft_"),userLinkRef:k(e,"userLinkRef","ul_"),amount:at(e.amount),status:C(e,"status",tt,"Dev faucet status"),createdAt:c(e,"createdAt")}}function oe(t){let e=f(t);return{simulationId:k(e,"simulationId","sim_"),scenario:C(e,"scenario",pe,"Dev scenario"),executionMode:C(e,"executionMode",Xe,"Dev execution mode"),status:C(e,"status",et,"Dev simulation status"),reasonCode:q(e,"reasonCode"),authorizationRef:q(e,"authorizationRef"),chargeRef:q(e,"chargeRef"),createdAt:c(e,"createdAt"),updatedAt:c(e,"updatedAt")}}function st(t){let e=f(t);return{eventId:se(e,"eventId","evt_"),deliveryId:se(e,"deliveryId","wd_"),status:x(e,"status","queued"),createdAt:c(e,"createdAt")}}function it(t,e){if(t[e]===void 0)return;let n=f(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 k(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 se(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 dt(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 M(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 ct(t){let e=f(t),n=M(e,"cardRef"),a=M(e,"factoUserId"),o=M(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:k(e,"userLinkRef","ul_"),grantStatus:c(e,"grantStatus"),pipelineReady:P(e,"pipelineReady"),scopes:Dt(e,"scopes"),...n===void 0?{}:{cardRef:n},...a===void 0?{}:{factoUserId:a},...o===void 0?{}:{factoServerWalletAddress:o}}}function ut(t){let e=f(t),n=P(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=M(e,"factoUserId"),d=M(e,"factoServerWalletAddress");return{appId:c(e,"appId"),userLinkRef:k(e,"userLinkRef","ul_"),selectedPipelineId:c(e,"selectedPipelineId"),chainId:ye(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 lt(t){let e=f(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 mt(t){let e=f(t);return{sessionId:c(e,"sessionId"),status:Tt(e,"status"),amount:c(e,"amount"),assetSymbol:c(e,"assetSymbol"),orderRef:E(e,"orderRef"),chargeId:E(e,"chargeId"),confirmedAt:E(e,"confirmedAt")}}function ie(t){let e=f(t),n=A(e,"mandateId"),a=A(e,"userLinkRef");return{sessionId:c(e,"sessionId"),authorizationUrl:c(e,"authorizationUrl"),status:Lt(e,"status"),...n===void 0?{}:{mandateId:n},...a===void 0?{}:{userLinkRef:a},expiresAt:c(e,"expiresAt"),state:c(e,"state")}}function de(t){let e=f(t),n=A(e,"expiresAt");return{mandateId:c(e,"mandateId"),appId:c(e,"appId"),status:xt(e,"status"),allowedUseCases:Ot(e,"allowedUseCases"),limits:St(e.limits),paymentPath:Rt(e.paymentPath),createdAt:c(e,"createdAt"),...n===void 0?{}:{expiresAt:n}}}var pt="direct",ft="defaultPaymentOptionId";function yt(t){let e=f(t);he(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===pt),o=At(e,ft),s=gt(a,o);return{paymentOptions:a,...s===void 0?{}:{selectedPaymentOptionId:s}}}function gt(t,e){return e!==void 0&&t.some(a=>a.paymentOptionId===e)?e:(t.find(a=>a.ready)??t[0])?.paymentOptionId}function ht(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=f(t);he(e,"payment option");let n=A(e,"blockingReason"),a=c(e,"assetSymbol"),o=c(e,"chainLabel"),s=c(e,"protocolLabel"),{settlementPath:d,spendMode:u}=ht(e);return{paymentOptionId:fe(e,"paymentOptionId"),label:bt({assetSymbol:a,protocolLabel:s,chainLabel:o},c(e,"label")),ready:P(e,"ready"),isDefault:P(e,"isDefault"),chainId:ye(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 U(t){let e=f(t),n=A(e,"chargeId"),a=A(e,"txHash"),o=Ut(e,"declineReason"),s=_t(e,"finalityEtaSeconds"),d=A(e,"terminalAt"),u=A(e,"updatedAt");return{paymentId:c(e,"paymentId"),mandateId:c(e,"mandateId"),merchantPaymentRef:c(e,"merchantPaymentRef"),status:Nt(e,"status"),amount:c(e,"amount"),currency:c(e,"currency"),useCase:Mt(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 St(t){let e=f(t);return{perTxAmount:c(e,"perTxAmount"),periodAmount:c(e,"periodAmount"),period:kt(e,"period")}}function Rt(t){let e=f(t),n=A(e,"blockingReason");return{ready:P(e,"ready"),summary:c(e,"summary"),...n===void 0?{}:{blockingReason:n}}}function f(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 At(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 P(t,e){let n=t[e];if(typeof n!="boolean")throw new Error(`expected boolean at ${e}`);return n}function ye(t,e){let n=t[e];if(typeof n!="number"||!Number.isFinite(n))throw new Error(`expected finite number at ${e}`);return n}function _t(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 It=["pending","charged","expired","cancelled"],ge=["immediate","recurring","top_up","metered"],vt=["daily","weekly","monthly"],Et=["pending","active","paused","revoked","expired","suspended"],Pt=["created","authorized","declined","expired"],wt=["accepted","declined","charging","finalizing","succeeded","paid_via_coverage","failed","canceled"];function Tt(t,e){let n=t[e];if(typeof n!="string"||!It.includes(n))throw new Error(`expected checkout status at ${e}`);return n}function Mt(t,e){return C(t,e,ge,"mandate use case")}function kt(t,e){return C(t,e,vt,"mandate limit period")}function xt(t,e){return C(t,e,Et,"mandate status")}function Lt(t,e){return C(t,e,Pt,"mandate authorization status")}function Nt(t,e){return C(t,e,wt,"mandate payment status")}function Ut(t,e){if(t[e]!==void 0)return C(t,e,Z,"mandate decline reason")}function Ot(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 q(t,e){let n=t[e];if(n===null)return null;if(typeof n!="string")throw new Error(`expected required string or null at ${e}`);return n}function Dt(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 he(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 Ft(t){try{return await t.json()}catch{return await t.text().catch(()=>null)}}function J(t){return t.replace(/\/+$/,"")}function l(t){throw new S("FACTO_CONFIG_INVALID",t,{retryable:!1})}function Wt(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 on(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=le("sha256",e).update(`${n}.`).update(t).digest("hex");return`t=${n},v1=${a}`}function sn(t,e,n,a=300){n||l("webhook secret is required");let o=e.split(",").map(m=>m.trim()),s,d=[];for(let m of o){let y=m.indexOf("=");if(y===-1)continue;let r=m.slice(0,y),i=m.slice(y+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=le("sha256",n).update(`${s}.`).update(t).digest();return d.some(m=>{let y;try{y=Buffer.from(m,"hex")}catch{return!1}return y.length===u.length&&ve(y,u)})}var p=class extends Error{code;details;constructor(e,n,a={}){super(n),this.name="FactoConnectHintError",this.code=e,this.details=a.details}},zt="facto";async function dn(t){if(t===null||typeof t!="object")throw new p("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?zt:B(t.issuer,"issuer"),o=Yt(t.clockToleranceSeconds),s=Math.floor(Gt(t.now)/1e3),{headerB64:d,payloadB64:u,signature:m}=Ht(e),y=G(ce(d,"header"),"FACTO_HINT_MALFORMED","connect hint header");if(y.alg!=="EdDSA")throw new p("FACTO_HINT_UNSUPPORTED_ALG","connect hint JWS alg must be EdDSA",{details:{alg:y.alg}});let r=typeof y.kid=="string"?y.kid:void 0,i=await $t(t.jwks),g=Kt(i,r),L=Qt(`${d}.${u}`);if(!await Jt(L,m,g))throw new p("FACTO_HINT_SIGNATURE_INVALID","connect hint signature does not verify against the Facto JWKS");let _=jt(ce(u,"payload"));if(_.iss!==a)throw new p("FACTO_HINT_ISSUER_MISMATCH","connect hint issuer mismatch",{details:{expected:a,actual:_.iss}});if(_.aud!==n)throw new p("FACTO_HINT_AUDIENCE_MISMATCH","connect hint audience mismatch",{details:{expected:n,actual:_.aud}});if(s>_.exp+o)throw new p("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 Ht(t){let e=t.split(".");if(e.length!==3)throw new p("FACTO_HINT_MALFORMED","connect hint is not a compact JWS (expected three segments)");let[n,a,o]=e;if(!n||!a||!o)throw new p("FACTO_HINT_MALFORMED","connect hint has an empty JWS segment");return{headerB64:n,payloadB64:a,signature:Ce(o,"signature")}}function ce(t,e){let n=new TextDecoder().decode(Ce(t,e));try{return JSON.parse(n)}catch(a){throw new p("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid JSON`,{details:a})}}async function $t(t){if(t==null)throw new p("FACTO_HINT_INPUT_INVALID","jwks is required");return V(typeof t=="function"?await t():typeof t=="string"?await Vt(t):t)}var qt=5e3,O=64*1024;async function Vt(t){let e;try{e=new URL(t)}catch{throw new p("FACTO_HINT_JWKS_INVALID",`JWKS url is not a valid URL: ${t}`)}if(e.protocol!=="https:")throw new p("FACTO_HINT_JWKS_INVALID",`JWKS url must use https: (got ${e.protocol})`,{details:{protocol:e.protocol}});let n=new AbortController,a=setTimeout(()=>n.abort(),qt),o,s;try{try{o=await fetch(t,{method:"GET",headers:{accept:"application/json"},redirect:"follow",signal:n.signal})}catch(u){throw new p("FACTO_HINT_JWKS_INVALID",`failed to fetch Facto JWKS from ${t}`,{details:u})}if(!o.ok)throw new p("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 p("FACTO_HINT_JWKS_INVALID",`Facto JWKS response exceeds ${O} bytes`,{details:{contentLength:d}});try{s=await o.text()}catch(u){throw new p("FACTO_HINT_JWKS_INVALID","Facto JWKS response could not be read",{details:u})}}finally{clearTimeout(a)}if(s.length>O)throw new p("FACTO_HINT_JWKS_INVALID",`Facto JWKS response exceeds ${O} bytes`,{details:{bytes:s.length}});try{return JSON.parse(s)}catch(d){throw new p("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 p("FACTO_HINT_JWKS_INVALID",'JWKS "keys" must be an array');return{keys:e.keys.map(Bt)}}function Bt(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 Kt(t,e){let n=t.keys.filter(a=>a.kty==="OKP"&&a.crv==="Ed25519"&&a.x.length>0);if(n.length===0)throw new p("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 Jt(t,e,n){let a=Xt();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 jt(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:ue(e,"iat"),exp:ue(e,"exp")}}function B(t,e){if(typeof t!="string"||t.length===0)throw new p("FACTO_HINT_INPUT_INVALID",`${e} must be a non-empty string`);return t}function Yt(t){if(t===void 0)return 0;if(typeof t!="number"||!Number.isFinite(t)||t<0)throw new p("FACTO_HINT_INPUT_INVALID","clockToleranceSeconds must be a non-negative finite number");return t}function Gt(t){if(t===void 0)return Date.now();if(t instanceof Date){let e=t.getTime();if(Number.isNaN(e))throw new p("FACTO_HINT_INPUT_INVALID","now is an invalid Date");return e}if(typeof t=="number"&&Number.isFinite(t))return t;throw new p("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 p(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 p("FACTO_HINT_CLAIMS_INVALID",`connect hint claim "${e}" must be a non-empty string`);return n}function ue(t,e){let n=t[e];if(typeof n!="number"||!Number.isFinite(n))throw new p("FACTO_HINT_CLAIMS_INVALID",`connect hint claim "${e}" must be a finite number`);return n}function Ce(t,e){if(!/^[A-Za-z0-9_-]*$/.test(t))throw new p("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid base64url`);let n=t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4);return Zt(n,e)}function Zt(t,e){let n=globalThis.atob;if(n){let o;try{o=n(t)}catch(d){throw new p("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 p("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 Xt(){let t=globalThis.crypto;if(t?.subtle)return t.subtle;throw new p("FACTO_HINT_INPUT_INVALID","Web Crypto (crypto.subtle) is not available in this runtime")}var cn=xe;export{W as FACTO_CONNECT_API_BASE_URLS,T as FACTO_CONNECT_HOSTED_URLS,p as FactoConnectHintError,S as FactoConnectServerError,be as PSP_CAPABILITY_TEMPLATES,Re as PSP_CREDENTIAL_KEYSPACE,X as PSP_CREDENTIAL_SCOPES,Ae as PSP_PARTNER_ROLE_TYPE,ke as buildHostedConnectUrl,Se as carriesMoneyVerb,xe as createFactoConnectServer,cn as default,Pe as factoConnectEnvironmentFromClientId,Ne as isTerminalMandatePaymentStatus,on as signWebhookPayload,Ie as subMerchantOf,dn as verifyFactoCardProgramConnectHint,sn as verifyWebhookSignature,Me as withServerRetry,_e as withSubMerchant};
|
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-beta2",
|
|
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-beta2",
|
|
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
|
}
|