@facto-to/connect 0.0.1-beta.1 → 0.0.1-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +128 -20
- package/dist/browser/index.cjs +5 -6
- package/dist/browser/index.d.cts +1 -31
- package/dist/browser/index.d.ts +1 -31
- package/dist/browser/index.js +4 -5
- package/dist/index.d-DE9GmLfU.d.cts +114 -0
- package/dist/index.d-DE9GmLfU.d.ts +114 -0
- package/dist/react/index.cjs +0 -1
- package/dist/react/index.js +0 -1
- package/dist/server/index.cjs +1 -2
- package/dist/server/index.d.cts +33 -227
- package/dist/server/index.d.ts +33 -227
- package/dist/server/index.js +1 -2
- package/dist/testing/index.cjs +1 -2
- package/dist/testing/index.d.cts +1 -12
- package/dist/testing/index.d.ts +1 -12
- package/dist/testing/index.js +1 -2
- package/package.json +51 -17
- package/dist/browser/index.cjs.map +0 -1
- package/dist/browser/index.js.map +0 -1
- package/dist/react/index.cjs.map +0 -1
- package/dist/react/index.js.map +0 -1
- package/dist/server/index.cjs.map +0 -1
- package/dist/server/index.js.map +0 -1
- package/dist/testing/index.cjs.map +0 -1
- package/dist/testing/index.js.map +0 -1
package/dist/server/index.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{createHmac as ce,timingSafeEqual as he}from"crypto";var Y=["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 Z=["payment_route_not_provisioned","protocol_config_incomplete"];function K(t){return t==="sandbox"?"dev":t}var N=Object.freeze({dev:"https://dev-api.facto.to",production:"https://api.facto.to"}),T=Object.freeze({dev:"https://dev.facto.to",production:"https://app.facto.to"}),h=Object.freeze({exchangeLinkCode:"/api/merchant/user-links/exchange",paymentCapability:"/api/merchant/payment-readiness",checkoutSessions:"/api/merchant/checkout-sessions",authorizationSessions:"/api/merchant/authorization-sessions",paymentAuthorizations:"/api/merchant/payment-authorizations",paymentOptions:"/api/merchant/payment-options",payments:"/api/merchant/payments"}),b=class extends Error{code;retryable;status;details;retryAfterSeconds;constructor(e,n,a){super(n),this.name="FactoConnectServerError",this.code=e,this.retryable=a.retryable,this.status=a.status,this.details=a.details,this.retryAfterSeconds=a.retryAfterSeconds}};function Ce(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 Re(t,e){return t<=0?Promise.resolve():new Promise((n,a)=>{if(e?.aborted){a(new b("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}));return}let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),a(new b("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}))};e?.addEventListener("abort",s,{once:!0})})}async function be(t,e={}){let n=e.maxRetries??2,a=e.baseDelayMs??200,o=e.maxDelayMs??5e3,s=e.respectRetryAfter??!0,c=e.sleep??Re,u=0;for(;;)try{return await t()}catch(l){if(!(l instanceof b)||!l.retryable||u>=n)throw l;u+=1;let r=s&&typeof l.retryAfterSeconds=="number"?l.retryAfterSeconds*1e3:void 0,i=Math.min(o,a*2**(u-1)),y=i*.25*Math.random(),U=r??i+y;e.onRetry?.({attempt:u,error:l,delayMs:U}),await c(U,e.signal)}}function Se(t){t.appId||m("appId is required"),t.state||m("state is required"),t.nonce||m("nonce is required"),t.hostedConnectUrl||m("hostedConnectUrl is required and has no implicit default: pass the Hosted Connect origin for the target environment (e.g. FACTO_CONNECT_HOSTED_URLS.dev)");let e=B(t.hostedConnectUrl);_(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 Ae(t){let e=Te(t),n=`Basic ${Tt(`${e.clientId}:${e.clientSecret}`)}`,a=(r,i)=>S(e,r,{code:i.code,state:i.state,nonce:i.nonce},n,Xe),o=(r,i)=>S(e,r,Qe(e,i),n,et),s=(r,i)=>S(e,r,{appId:e.appId,externalCustomerRef:i.externalCustomerRef,requestedUseCases:i.requestedUseCases,defaultLimits:i.defaultLimits,returnUrl:i.returnUrl,state:i.state,...i.customerEmail===void 0?{}:{customerEmail:i.customerEmail},...i.customerUsername===void 0?{}:{customerUsername:i.customerUsername}},n,oe),c=(r,i)=>R(e,`${r}/${encodeURIComponent(i)}`,n,oe),u=(r,i)=>R(e,`${r}/${encodeURIComponent(i)}`,n,se),l=(r,i)=>{let y={mandateId:i.mandateId,merchantPaymentRef:i.merchantPaymentRef,amount:i.amount,currency:i.currency,useCase:i.useCase};return i.paymentOptionId!==void 0&&(y.paymentOptionId=i.paymentOptionId),i.description!==void 0&&(y.description=i.description),i.metadata!==void 0&&(y.metadata=i.metadata),S(e,r,y,n,D,{"Idempotency-Key":i.idempotencyKey},[402])},p=(r,i)=>R(e,`${r}/${encodeURIComponent(i)}`,n,D);return{createHostedConnectUrl(r){let i=r.hostedConnectUrl??e.hostedConnectUrl;if(r.hostedConnectUrl!==void 0){let y=_(r.hostedConnectUrl,T,"hostedConnectUrl",!0);y!==void 0&&y!==e.environment&&m("hostedConnectUrl conflicts with the configured environment")}return Se({appId:e.appId,state:r.state,nonce:r.nonce,customerEmail:r.customerEmail,customerUsername:r.customerUsername,hostedConnectUrl:i})},exchangeUserLinkCode(r){return a(h.exchangeLinkCode,r)},getPaymentReadiness(r){return o(h.paymentCapability,r)},createAuthorizationSession(r){return s(h.authorizationSessions,r)},getAuthorizationSession(r){return c(h.authorizationSessions,r)},getPaymentAuthorization(r){return u(h.paymentAuthorizations,r)},createMerchantPayment(r){return l(h.payments,r)},getMerchantPayment(r){return p(h.payments,r)},exchangeLinkCode(r){return a(h.exchangeLinkCode,r)},getPaymentCapability(r){return o(h.paymentCapability,r)},createCheckoutSession(r){return r.userLinkRef!==void 0&&v(r.userLinkRef,"ul_","userLinkRef"),S(e,h.checkoutSessions,{...r.userLinkRef!==void 0?{userLinkRef:r.userLinkRef}:{app_id:e.appId,facto_server_wallet_address:r.factoServerWalletAddress},amount:r.amount,asset_symbol:r.assetSymbol,order_ref:r.orderRef,return_url:r.returnUrl},n,tt)},getCheckoutSession(r){return R(e,`${h.checkoutSessions}/${encodeURIComponent(r)}`,n,nt)},createMandateAuthorizationSession(r){return s(h.authorizationSessions,r)},getMandateAuthorizationSession(r){return c(h.authorizationSessions,r)},getMerchantMandate(r){return u(h.paymentAuthorizations,r)},listPaymentOptions(r){return r.userLinkRef!==void 0&&v(r.userLinkRef,"ul_","userLinkRef"),S(e,h.paymentOptions,{...r.userLinkRef!==void 0?{userLinkRef:r.userLinkRef}:{appId:e.appId,grantRef:r.grantRef},...r.amount!==void 0?{amount:r.amount}:{},...r.assetSymbol!==void 0?{assetSymbol:r.assetSymbol}:{}},n,ot)},createMandatePayment(r){return l(h.payments,r)},getMandatePayment(r){return p(h.payments,r)},onStatus(r,i,y){return _e(()=>R(e,`${h.payments}/${encodeURIComponent(r)}`,n,D),i,y)},revokeUserLink(r){return te(e,`/api/merchant/user-links/${encodeURIComponent(r)}`,n)},listMerchantPayments(r={}){return R(e,F("/api/merchant/payments",{limit:r.limit,startingAfter:r.startingAfter,createdAfter:r.createdAfter,createdBefore:r.createdBefore,authorizationId:r.authorizationId,status:r.status}),n,i=>W(i,D))},listPaymentAuthorizations(r={}){return R(e,F("/api/merchant/payment-authorizations",{limit:r.limit,startingAfter:r.startingAfter,userLinkRef:r.userLinkRef,status:r.status}),n,i=>W(i,se))},createRefund(r){let i={paymentId:r.paymentId};return r.amount!==void 0&&(i.amount=r.amount),r.reason!==void 0&&(i.reason=r.reason),r.merchantRefundRef!==void 0&&(i.merchantRefundRef=r.merchantRefundRef),S(e,"/api/merchant/refunds",i,n,z,{"Idempotency-Key":r.idempotencyKey},[402])},getRefund(r){return R(e,`/api/merchant/refunds/${encodeURIComponent(r)}`,n,z)},listRefunds(r={}){return R(e,F("/api/merchant/refunds",{limit:r.limit,startingAfter:r.startingAfter,paymentId:r.paymentId}),n,i=>W(i,z))},createWebhookEndpoint(r){return S(e,"/api/merchant/webhook-endpoints",{url:r.url,enabledEvents:r.enabledEvents},n,ne)},listWebhookEndpoints(){return R(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(V)})},getWebhookEndpoint(r){return R(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n,V)},deleteWebhookEndpoint(r){return te(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}`,n)},rotateWebhookSecret(r){return S(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r)}/rotate-secret`,{},n,ne)},getDevCapabilities(){return L(e,"getDevCapabilities"),R(e,"/api/dev/capabilities",n,Ke)},fundDevUser(r){return L(e,"fundDevUser"),Q(r.userLinkRef),X(r.amount),ee(r.idempotencyKey),S(e,"/api/dev/faucet/usdc",{userLinkRef:r.userLinkRef,amount:r.amount},n,Ge,{"Idempotency-Key":r.idempotencyKey})},simulateDevCharge(r){return L(e,"simulateDevCharge"),Q(r.userLinkRef),r.cardRef!==void 0&&v(r.cardRef,"card_","cardRef"),X(r.amount),xe(r.scenario),r.merchantReference!==void 0&&(typeof r.merchantReference!="string"||r.merchantReference.length>120)&&m("merchantReference must not exceed 120 characters"),ee(r.idempotencyKey),S(e,"/api/dev/simulate/charge",{userLinkRef:r.userLinkRef,...r.cardRef===void 0?{}:{cardRef:r.cardRef},amount:r.amount,scenario:r.scenario,...r.merchantReference===void 0?{}:{merchantReference:r.merchantReference}},n,re,{"Idempotency-Key":r.idempotencyKey})},getDevSimulation(r){return L(e,"getDevSimulation"),v(r,"sim_","simulationId"),R(e,`/api/dev/simulations/${encodeURIComponent(r)}`,n,re)},sendWebhookTestDelivery(r){return ke(e),Me(r.webhookEndpointId),r.message!==void 0&&(typeof r.message!="string"||r.message.length>120)&&m("webhook test message must not exceed 120 characters"),S(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(r.webhookEndpointId)}/test-delivery`,r.message===void 0?{}:{message:r.message},n,Ye)}}}var Ie=new Set(["declined","succeeded","paid_via_coverage","failed","canceled"]);function ve(t){return Ie.has(t)}async function _e(t,e,n={}){let a=Math.max(0,n.initialIntervalMs??1e3),o=Math.max(a,n.maxIntervalMs??8e3),s=n.backoffFactor??1.5,c=n.timeoutMs??3e5,u=n.signal,l=Date.now()+c,p=a,r;for(;;){Ee(u);let i=await t();if(i.status!==r&&(r=i.status,e(i)),ve(i.status))return i;let y=l-Date.now();if(y<=0)return i;await we(Math.min(p,y),u),p=Math.min(p*s,o)}}function Ee(t){if(t?.aborted)throw new b("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 b("FACTO_STATUS_POLL_ABORTED","mandate payment polling aborted",{retryable:!1}))};if(e){if(e.aborted){clearTimeout(o),s();return}e.addEventListener("abort",s,{once:!0})}})}var Pe=Object.freeze(["dev","production","sandbox"]);function Te(t){t.appId||m("appId is required"),t.clientId||m("clientId is required"),t.clientSecret||m("clientSecret is required");let e=t.environment;(e===void 0||!Pe.includes(e))&&m("environment is required and must be 'dev', 'production', or 'sandbox' ('sandbox' is the documented public test environment name and targets the same dev endpoints \u2014 ADR-0077). 'staging' and the former 'custom' selector are retired: pass explicit apiBaseUrl and hostedConnectUrl overrides (valid with any environment) for a local, private, or staging deployment. There is no implicit default; the legacy production fallback over /api/external/* routes was removed. See https://docs.facto.to/reference/sdk"),t.transport!==void 0&&t.fetch!==void 0&&m("provide either transport or fetch, not both"),t.timeoutMs!==void 0&&(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<=0)&&m("timeoutMs must be a positive safe integer");let n=t.apiBaseUrl?_(t.apiBaseUrl,N,"apiBaseUrl",!1):void 0,a=t.hostedConnectUrl?_(t.hostedConnectUrl,T,"hostedConnectUrl",!0):void 0;n!==void 0&&a!==void 0&&n!==a&&m("apiBaseUrl and hostedConnectUrl target different Facto environments");let o=e,s=K(o);for(let p of[n,a])p!==void 0&&p!==s&&m("environment selector conflicts with a published Facto endpoint");let c=B(t.apiBaseUrl??N[s]),u=B(t.hostedConnectUrl??T[s]),l=_(c,N,"apiBaseUrl",!1);return _(u,T,"hostedConnectUrl",!0),Ue(t.clientId,l),{appId:t.appId,clientId:t.clientId,clientSecret:t.clientSecret,environment:o,apiBaseUrl:c,hostedConnectUrl:u,transport:t.transport??t.fetch??((p,r)=>globalThis.fetch(p,r)),...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.retry===void 0?{}:{retry:t.retry},...t.signal===void 0?{}:{signal:t.signal}}}function L(t,e){K(t.environment)!=="dev"&&m(`${e} is available only in the sandbox/dev environment`)}function ke(t){K(t.environment)!=="dev"&&m("sendWebhookTestDelivery is available only in the sandbox/dev environment")}function v(t,e,n){(typeof t!="string"||!new RegExp(`^${e}[A-Za-z0-9_-]+$`).test(t))&&m(`${n} must be an opaque ${e} reference`)}function Q(t){v(t,"ul_","userLinkRef")}function Me(t){(typeof t!="string"||!/^we_[A-Za-z0-9]+$/.test(t))&&m("webhookEndpointId must be an opaque we_ reference")}function X(t){(typeof t!="object"||t===null||t.currency!=="USDC"||typeof t.amount!="string"||!/^[0-9]+(?:\.[0-9]{1,6})?$/.test(t.amount))&&m("Dev amount must be a USDC decimal with at most six fractional digits")}function xe(t){(typeof t!="string"||!le.includes(t))&&m("unknown Dev simulation scenario")}function ee(t){(typeof t!="string"||t.trim()!==t||t.length<16||t.length>255)&&m("idempotencyKey must be 16 to 255 non-whitespace-trimmed characters")}function Ue(t,e){let n=e==="dev",a=e==="production";t.startsWith("dev_")&&e!==void 0&&!n&&m("a dev credential can target only the sandbox/dev environment"),(n||a)&&(t.startsWith("staging_")||t.startsWith("test_")||t.startsWith("lab_")||t.startsWith("sandbox_"))&&m("internal or legacy (staging_/test_/lab_/sandbox_) credentials cannot target a published Facto environment")}function _(t,e,n,a){let o;try{o=new URL(t)}catch{m(`${n} must be an absolute URL`)}let s=o.hostname.toLowerCase().replace(/\.$/,"");for(let c of["dev","production"]){let u=new URL(e[c]);if(s!==u.hostname.toLowerCase())continue;let l=o.pathname==="/"||a&&o.pathname==="/connect";return(o.origin!==u.origin||o.username!==""||o.password!==""||!l||o.search!==""||o.hash!=="")&&m(`${n} is not the exact published ${c} endpoint`),c}}async function S(t,e,n,a,o,s={},c=[]){let u=await ue(t,async()=>{let l=await j(t,`${t.apiBaseUrl}${e}`,{method:"POST",headers:{authorization:a,"content-type":"application/json",...s},body:JSON.stringify(n)});if(!l.ok&&!c.includes(l.status))throw await J(l);return l},s["Idempotency-Key"]!==void 0);try{return o(await u.json())}catch(l){throw new b("FACTO_ENGINE_RESPONSE_INVALID","Facto Engine returned an invalid response",{retryable:!1,details:l})}}async function R(t,e,n,a){let o=await ue(t,async()=>{let s=await j(t,`${t.apiBaseUrl}${e}`,{method:"GET",headers:{authorization:n}});if(!s.ok)throw await J(s);return s},!0);try{return a(await o.json())}catch(s){throw new b("FACTO_ENGINE_RESPONSE_INVALID","Facto Engine returned an invalid response",{retryable:!1,details:s})}}async function te(t,e,n){let a=await j(t,`${t.apiBaseUrl}${e}`,{method:"DELETE",headers:{authorization:n}});if(!a.ok)throw await J(a)}async function J(t){return new b("FACTO_ENGINE_REQUEST_FAILED",`Facto Engine request failed with status ${t.status}`,{retryable:t.status===429||t.status>=500,status:t.status,details:await Pt(t),retryAfterSeconds:Ce(t)})}function ue(t,e,n){return n?be(e,{...t.retry,signal:t.signal??t.retry?.signal}):e()}function j(t,e,n){return t.timeoutMs===void 0?t.transport(e,{...n,signal:t.signal}):Le(t,e,n)}function Le(t,e,n){let a=new AbortController,o=()=>a.abort();return t.signal?.aborted?Promise.reject(new b("FACTO_REQUEST_ABORTED","Facto Engine request aborted",{retryable:!1})):(t.signal?.addEventListener("abort",o,{once:!0}),new Promise((s,c)=>{let u=setTimeout(()=>{a.abort(),c(new b("FACTO_REQUEST_ABORTED","Facto Engine request timed out",{retryable:!1}))},t.timeoutMs);t.transport(e,{...n,signal:a.signal}).then(s,c).finally(()=>{clearTimeout(u),t.signal?.removeEventListener("abort",o)})}))}function F(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 W(t,e){let n=g(t),a=n.data;if(!Array.isArray(a))throw new Error("expected data array");return{data:a.map(e),hasMore:w(n,"hasMore")}}var De=["pending","succeeded","failed"],Oe=["requested_by_customer","duplicate","fraudulent","other"];function Ne(t,e){let n=t[e];if(typeof n!="string"||!De.includes(n))throw new Error(`expected refund status at ${e}`);return n}function Fe(t,e){let n=t[e];if(n!==void 0){if(typeof n!="string"||!Oe.includes(n))throw new Error(`expected refund reason at ${e}`);return n}}function z(t){let e=g(t),n=Fe(e,"reason"),a=A(e,"merchantRefundRef");return{refundId:d(e,"refundId"),paymentId:d(e,"paymentId"),status:Ne(e,"status"),amount:d(e,"amount"),currency:d(e,"currency"),...n===void 0?{}:{reason:n},...a===void 0?{}:{merchantRefundRef:a},createdAt:d(e,"createdAt")}}var We=["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 ze(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"||!We.includes(a))throw new Error(`unknown webhook event type: ${String(a)}`);return a})}function V(t){let e=g(t),n=e.status;if(n!=="enabled"&&n!=="disabled")throw new Error("expected webhook endpoint status");return{webhookEndpointId:d(e,"webhookEndpointId"),url:d(e,"url"),enabledEvents:ze(e,"enabledEvents"),status:n,createdAt:d(e,"createdAt")}}function ne(t){let e=V(t),n=g(t);return{...e,secret:d(n,"secret")}}var O=["fixtures","synthetic_identity","faucet","simulation","money_loop","webhook_test_delivery"],He=["unavailable","degraded","ready"],$e=["contract","implemented","deployed","verified"],le=["approved","declined_setup","declined_limit","payment_failed"],qe=["pre_admission","onchain_test_assets"],Ve=["accepted","processing","succeeded","failed","declined"],Be=["accepted","broadcast","confirmed","failed"];function Ke(t){let e=g(t),n=e.capabilities;if(!Array.isArray(n)||n.length!==O.length)throw new Error("expected exactly six Dev capabilities");let a=n.map(Je),o=new Set(a.map(s=>s.name));if(o.size!==O.length)throw new Error("expected each Dev capability exactly once");for(let s of O)if(!o.has(s))throw new Error(`missing Dev capability: ${s}`);return{environment:x(e,"environment","dev"),contractVersion:x(e,"contractVersion","2026-07-09"),capabilities:a,checkedAt:d(e,"checkedAt")}}function Je(t){let e=g(t),n=C(e,"name",O,"Dev capability name"),a=C(e,"status",He,"Dev capability status"),o=C(e,"evidenceLevel",$e,"Dev evidence level"),s=E(e,"reasonCode"),c=E(e,"verifiedAt");if(a==="ready"&&(o!=="verified"||c===null))throw new Error("ready Dev capability requires verified evidence");let u=Ze(e,"limits");return{name:n,status:a,evidenceLevel:o,...s===void 0?{}:{reasonCode:s},...c===void 0?{}:{verifiedAt:c},...u===void 0?{}:{limits:u}}}function je(t){let e=g(t),n=d(e,"amount");if(!/^[0-9]+(?:\.[0-9]{1,6})?$/.test(n))throw new Error("expected Dev USDC decimal amount");return{amount:n,currency:x(e,"currency","USDC")}}function Ge(t){let e=g(t);return{faucetTransferId:M(e,"faucetTransferId","sft_"),userLinkRef:M(e,"userLinkRef","ul_"),amount:je(e.amount),status:C(e,"status",Be,"Dev faucet status"),createdAt:d(e,"createdAt")}}function re(t){let e=g(t);return{simulationId:M(e,"simulationId","sim_"),scenario:C(e,"scenario",le,"Dev scenario"),executionMode:C(e,"executionMode",qe,"Dev execution mode"),status:C(e,"status",Ve,"Dev simulation status"),reasonCode:H(e,"reasonCode"),authorizationRef:H(e,"authorizationRef"),chargeRef:H(e,"chargeRef"),createdAt:d(e,"createdAt"),updatedAt:d(e,"updatedAt")}}function Ye(t){let e=g(t);return{eventId:ae(e,"eventId","evt_"),deliveryId:ae(e,"deliveryId","wd_"),status:x(e,"status","queued"),createdAt:d(e,"createdAt")}}function Ze(t,e){if(t[e]===void 0)return;let n=g(t[e]);for(let a of Object.values(n))if(a!==null&&typeof a!="string"&&typeof a!="number"&&typeof a!="boolean")throw new Error(`expected scalar Dev limit at ${e}`);return n}function M(t,e,n){let a=d(t,e);if(!new RegExp(`^${n}[A-Za-z0-9_-]+$`).test(a))throw new Error(`expected opaque ${e}`);return a}function ae(t,e,n){let a=d(t,e);if(!new RegExp(`^${n}[A-Za-z0-9]+$`).test(a))throw new Error(`expected opaque ${e}`);return a}function Qe(t,e){return e.userLinkRef===void 0&&e.factoServerWalletAddress===void 0&&m("payment readiness requires userLinkRef, factoServerWalletAddress, or both"),e.userLinkRef!==void 0&&v(e.userLinkRef,"ul_","userLinkRef"),e.factoServerWalletAddress!==void 0&&typeof e.factoServerWalletAddress!="string"&&m("factoServerWalletAddress must be a string"),{...e.userLinkRef===void 0?{}:{userLinkRef:e.userLinkRef},...e.factoServerWalletAddress===void 0?{}:{app_id:t.appId,facto_server_wallet_address:e.factoServerWalletAddress}}}function k(t,e){let n=t[e];if(n==null)return n;if(typeof n!="string"||n.length===0)throw new Error(`expected non-empty string or null at ${e}`);return n}function Xe(t){let e=g(t),n=k(e,"cardRef"),a=k(e,"factoUserId"),o=k(e,"factoServerWalletAddress");if(n!=null&&(v(n,"card_","cardRef"),a!=null||o!=null))throw new Error("synthetic Dev links must not expose canonical identity");return{appId:d(e,"appId"),userLinkRef:M(e,"userLinkRef","ul_"),grantStatus:d(e,"grantStatus"),pipelineReady:w(e,"pipelineReady"),scopes:wt(e,"scopes"),...n===void 0?{}:{cardRef:n},...a===void 0?{}:{factoUserId:a},...o===void 0?{}:{factoServerWalletAddress:o}}}function et(t){let e=g(t),n=w(e,"pipelineReady"),a=e.notReadyReason,o=a==null?a:C(e,"notReadyReason",Z,"payment readiness not-ready reason");if(n&&o!==void 0&&o!==null)throw new Error("expected notReadyReason only when pipelineReady is false");let s=k(e,"factoUserId"),c=k(e,"factoServerWalletAddress");return{appId:d(e,"appId"),userLinkRef:M(e,"userLinkRef","ul_"),selectedPipelineId:d(e,"selectedPipelineId"),chainId:fe(e,"chainId"),protocolId:d(e,"protocolId"),assetSymbol:d(e,"assetSymbol"),spendMode:d(e,"spendMode"),pipelineReady:n,...o===void 0?{}:{notReadyReason:o},...s===void 0?{}:{factoUserId:s},...c===void 0?{}:{factoServerWalletAddress:c}}}function tt(t){let e=g(t);return{sessionId:d(e,"sessionId"),checkoutUrl:d(e,"checkoutUrl"),status:x(e,"status","pending"),amount:d(e,"amount"),assetSymbol:d(e,"assetSymbol"),orderRef:E(e,"orderRef")}}function nt(t){let e=g(t);return{sessionId:d(e,"sessionId"),status:Rt(e,"status"),amount:d(e,"amount"),assetSymbol:d(e,"assetSymbol"),orderRef:E(e,"orderRef"),chargeId:E(e,"chargeId"),confirmedAt:E(e,"confirmedAt")}}function oe(t){let e=g(t),n=A(e,"mandateId"),a=A(e,"userLinkRef");return{sessionId:d(e,"sessionId"),authorizationUrl:d(e,"authorizationUrl"),status:It(e,"status"),...n===void 0?{}:{mandateId:n},...a===void 0?{}:{userLinkRef:a},expiresAt:d(e,"expiresAt"),state:d(e,"state")}}function se(t){let e=g(t),n=A(e,"expiresAt");return{mandateId:d(e,"mandateId"),appId:d(e,"appId"),status:At(e,"status"),allowedUseCases:Et(e,"allowedUseCases"),limits:ut(e.limits),paymentPath:lt(e.paymentPath),createdAt:d(e,"createdAt"),...n===void 0?{}:{expiresAt:n}}}var rt="direct",at="defaultPaymentOptionId";function ot(t){let e=g(t);ge(e,"payment options");let n=e.paymentOptions;if(!Array.isArray(n))throw new Error("expected paymentOptions array");let a=n.map(dt).filter(c=>c.settlementPath===rt),o=mt(e,at),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 it(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 dt(t){let e=g(t);ge(e,"payment option");let n=A(e,"blockingReason"),a=d(e,"assetSymbol"),o=d(e,"chainLabel"),s=d(e,"protocolLabel"),{settlementPath:c,spendMode:u}=it(e);return{paymentOptionId:me(e,"paymentOptionId"),label:ct({assetSymbol:a,protocolLabel:s,chainLabel:o},d(e,"label")),ready:w(e,"ready"),isDefault:w(e,"isDefault"),chainId:fe(e,"chainId"),chainLabel:o,protocolLabel:s,assetSymbol:a,spendMode:u,settlementPath:c,...n===void 0?{}:{blockingReason:n}}}function ct(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 D(t){let e=g(t),n=A(e,"chargeId"),a=A(e,"txHash"),o=_t(e,"declineReason"),s=ft(e,"finalityEtaSeconds"),c=A(e,"terminalAt"),u=A(e,"updatedAt");return{paymentId:d(e,"paymentId"),mandateId:d(e,"mandateId"),merchantPaymentRef:d(e,"merchantPaymentRef"),status:vt(e,"status"),amount:d(e,"amount"),currency:d(e,"currency"),useCase:bt(e,"useCase"),...n===void 0?{}:{chargeId:n},...a===void 0?{}:{txHash:a},...o===void 0?{}:{declineReason:o},...s===void 0?{}:{finalityEtaSeconds:s},...c===void 0?{}:{terminalAt:c},createdAt:d(e,"createdAt"),...u===void 0?{}:{updatedAt:u}}}function ut(t){let e=g(t);return{perTxAmount:d(e,"perTxAmount"),periodAmount:d(e,"periodAmount"),period:St(e,"period")}}function lt(t){let e=g(t),n=A(e,"blockingReason");return{ready:w(e,"ready"),summary:d(e,"summary"),...n===void 0?{}:{blockingReason:n}}}function g(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("expected object");return t}function d(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`expected non-empty string at ${e}`);return n}function A(t,e){let n=t[e];if(n!==void 0){if(typeof n!="string"||n.length===0)throw new Error(`expected non-empty string at ${e}`);return n}}function me(t,e){let n=d(t,e);if(!n.startsWith("fpo_"))throw new Error(`expected opaque Facto payment option id at ${e}`);return n}function mt(t,e){if(!(t[e]===void 0||t[e]===null))return me(t,e)}function x(t,e,n){if(t[e]!==n)throw new Error(`expected ${n} at ${e}`);return n}function w(t,e){let n=t[e];if(typeof n!="boolean")throw new Error(`expected boolean at ${e}`);return n}function fe(t,e){let n=t[e];if(typeof n!="number"||!Number.isFinite(n))throw new Error(`expected finite number at ${e}`);return n}function ft(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"],pe=["immediate","recurring","top_up","metered"],gt=["daily","weekly","monthly"],yt=["pending","active","paused","revoked","expired","suspended"],ht=["created","authorized","declined","expired"],Ct=["accepted","declined","charging","finalizing","succeeded","paid_via_coverage","failed","canceled"];function Rt(t,e){let n=t[e];if(typeof n!="string"||!pt.includes(n))throw new Error(`expected checkout status at ${e}`);return n}function bt(t,e){return C(t,e,pe,"mandate use case")}function St(t,e){return C(t,e,gt,"mandate limit period")}function At(t,e){return C(t,e,yt,"mandate status")}function It(t,e){return C(t,e,ht,"mandate authorization status")}function vt(t,e){return C(t,e,Ct,"mandate payment status")}function _t(t,e){if(t[e]!==void 0)return C(t,e,Y,"mandate decline reason")}function Et(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"||!pe.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 H(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 ge(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 Pt(t){try{return await t.json()}catch{return await t.text().catch(()=>null)}}function B(t){return t.replace(/\/+$/,"")}function m(t){throw new b("FACTO_CONFIG_INVALID",t,{retryable:!1})}function Tt(t){let e=globalThis.btoa;if(e)return e(t);let n=globalThis.Buffer;if(n)return n.from(t).toString("base64");m("No base64 encoder is available in this runtime")}function Jt(t,e,n=Math.floor(Date.now()/1e3)){e||m("webhook secret is required"),(!Number.isSafeInteger(n)||n<0)&&m("webhook timestamp must be a non-negative safe integer");let a=ce("sha256",e).update(`${n}.`).update(t).digest("hex");return`t=${n},v1=${a}`}function jt(t,e,n,a=300){let o=e.split(",").map(l=>l.trim()),s,c=[];for(let l of o){let p=l.indexOf("=");if(p===-1)continue;let r=l.slice(0,p),i=l.slice(p+1);r==="t"?s=Number(i):r==="v1"&&c.push(i)}if(s===void 0||!Number.isFinite(s)||Math.abs(Date.now()/1e3-s)>a||c.length===0)return!1;let u=ce("sha256",n).update(`${s}.`).update(t).digest();return c.some(l=>{let p;try{p=Buffer.from(l,"hex")}catch{return!1}return p.length===u.length&&he(p,u)})}var f=class extends Error{code;details;constructor(e,n,a={}){super(n),this.name="FactoConnectHintError",this.code=e,this.details=a.details}},kt="facto";async function Gt(t){if(t===null||typeof t!="object")throw new f("FACTO_HINT_INPUT_INVALID","verifyFactoCardProgramConnectHint requires an input object");let e=q(t.connectHint,"connectHint"),n=q(t.audience,"audience"),a=t.issuer===void 0?kt:q(t.issuer,"issuer"),o=Ft(t.clockToleranceSeconds),s=Math.floor(Wt(t.now)/1e3),{headerB64:c,payloadB64:u,signature:l}=Mt(e),p=G(ie(c,"header"),"FACTO_HINT_MALFORMED","connect hint header");if(p.alg!=="EdDSA")throw new f("FACTO_HINT_UNSUPPORTED_ALG","connect hint JWS alg must be EdDSA",{details:{alg:p.alg}});let r=typeof p.kid=="string"?p.kid:void 0,i=await xt(t.jwks),y=Dt(i,r),U=Ht(`${c}.${u}`);if(!await Ot(U,l,y))throw new f("FACTO_HINT_SIGNATURE_INVALID","connect hint signature does not verify against the Facto JWKS");let I=Nt(ie(u,"payload"));if(I.iss!==a)throw new f("FACTO_HINT_ISSUER_MISMATCH","connect hint issuer mismatch",{details:{expected:a,actual:I.iss}});if(I.aud!==n)throw new f("FACTO_HINT_AUDIENCE_MISMATCH","connect hint audience mismatch",{details:{expected:n,actual:I.aud}});if(s>I.exp+o)throw new f("FACTO_HINT_EXPIRED","connect hint has expired",{details:{exp:I.exp,now:s}});return{programRef:I.program_ref,pairwiseSubject:I.sub,nonce:I.nonce,expiresAt:new Date(I.exp*1e3).toISOString()}}function Mt(t){let e=t.split(".");if(e.length!==3)throw new f("FACTO_HINT_MALFORMED","connect hint is not a compact JWS (expected three segments)");let[n,a,o]=e;if(!n||!a||!o)throw new f("FACTO_HINT_MALFORMED","connect hint has an empty JWS segment");return{headerB64:n,payloadB64:a,signature:ye(o,"signature")}}function ie(t,e){let n=new TextDecoder().decode(ye(t,e));try{return JSON.parse(n)}catch(a){throw new f("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid JSON`,{details:a})}}async function xt(t){if(t==null)throw new f("FACTO_HINT_INPUT_INVALID","jwks is required");return $(typeof t=="function"?await t():typeof t=="string"?await Ut(t):t)}async function Ut(t){let e;try{e=await fetch(t,{method:"GET",headers:{accept:"application/json"}})}catch(n){throw new f("FACTO_HINT_JWKS_INVALID",`failed to fetch Facto JWKS from ${t}`,{details:n})}if(!e.ok)throw new f("FACTO_HINT_JWKS_INVALID",`Facto JWKS request failed with status ${e.status}`,{details:{status:e.status}});try{return await e.json()}catch(n){throw new f("FACTO_HINT_JWKS_INVALID","Facto JWKS response was not valid JSON",{details:n})}}function $(t){let e=G(t,"FACTO_HINT_JWKS_INVALID","JWKS");if(!Array.isArray(e.keys))throw new f("FACTO_HINT_JWKS_INVALID",'JWKS "keys" must be an array');return{keys:e.keys.map(Lt)}}function Lt(t){let e=typeof t=="object"&&t!==null?t:{};return{kty:typeof e.kty=="string"?e.kty:"",crv:typeof e.crv=="string"?e.crv:"",x:typeof e.x=="string"?e.x:"",...typeof e.kid=="string"?{kid:e.kid}:{},...typeof e.alg=="string"?{alg:e.alg}:{},...typeof e.use=="string"?{use:e.use}:{}}}function Dt(t,e){let n=t.keys.filter(a=>a.kty==="OKP"&&a.crv==="Ed25519"&&a.x.length>0);if(n.length===0)throw new f("FACTO_HINT_JWKS_INVALID","Facto JWKS has no usable Ed25519 signing key");if(e!==void 0){let a=n.filter(o=>o.kid===e);if(a.length>0)return a}return n}async function Ot(t,e,n){let a=$t();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 Nt(t){let e=G(t,"FACTO_HINT_CLAIMS_INVALID","connect hint claims");return{iss:P(e,"iss"),aud:P(e,"aud"),sub:P(e,"sub"),program_ref:P(e,"program_ref"),nonce:P(e,"nonce"),iat:de(e,"iat"),exp:de(e,"exp")}}function q(t,e){if(typeof t!="string"||t.length===0)throw new f("FACTO_HINT_INPUT_INVALID",`${e} must be a non-empty string`);return t}function Ft(t){if(t===void 0)return 0;if(typeof t!="number"||!Number.isFinite(t)||t<0)throw new f("FACTO_HINT_INPUT_INVALID","clockToleranceSeconds must be a non-negative finite number");return t}function Wt(t){if(t===void 0)return Date.now();if(t instanceof Date){let e=t.getTime();if(Number.isNaN(e))throw new f("FACTO_HINT_INPUT_INVALID","now is an invalid Date");return e}if(typeof t=="number"&&Number.isFinite(t))return t;throw new f("FACTO_HINT_INPUT_INVALID","now must be a Date or unix milliseconds number")}function G(t,e,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new f(e,`${n} must be a JSON object`);return t}function P(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new f("FACTO_HINT_CLAIMS_INVALID",`connect hint claim "${e}" must be a non-empty string`);return n}function de(t,e){let n=t[e];if(typeof n!="number"||!Number.isFinite(n))throw new f("FACTO_HINT_CLAIMS_INVALID",`connect hint claim "${e}" must be a finite number`);return n}function ye(t,e){if(!/^[A-Za-z0-9_-]*$/.test(t))throw new f("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid base64url`);let n=t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4);return zt(n,e)}function zt(t,e){let n=globalThis.atob;if(n){let o;try{o=n(t)}catch(c){throw new f("FACTO_HINT_MALFORMED",`connect hint ${e} is not valid base64url`,{details:c})}let s=new Uint8Array(o.length);for(let c=0;c<o.length;c+=1)s[c]=o.charCodeAt(c);return s}let a=globalThis.Buffer;if(a)return new Uint8Array(a.from(t,"base64"));throw new f("FACTO_HINT_INPUT_INVALID","No base64 decoder is available in this runtime")}function Ht(t){let e=new TextEncoder().encode(t),n=new Uint8Array(e.length);return n.set(e),n}function $t(){let t=globalThis.crypto;if(t?.subtle)return t.subtle;throw new f("FACTO_HINT_INPUT_INVALID","Web Crypto (crypto.subtle) is not available in this runtime")}var Yt=Ae;export{N as FACTO_CONNECT_API_BASE_URLS,T as FACTO_CONNECT_HOSTED_URLS,f as FactoConnectHintError,b as FactoConnectServerError,Se as buildHostedConnectUrl,Ae as createFactoConnectServer,Yt as default,ve as isTerminalMandatePaymentStatus,Jt as signWebhookPayload,Gt as verifyFactoCardProgramConnectHint,jt as verifyWebhookSignature,be as withServerRetry};
|
|
2
|
-
//# sourceMappingURL=index.js.map
|
|
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};
|
package/dist/testing/index.cjs
CHANGED
|
@@ -1,2 +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=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"}})}
|
|
2
|
-
//# sourceMappingURL=index.cjs.map
|
|
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"}})}
|
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 '../index.d-DE9GmLfU.cjs';
|
|
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,7 +88,6 @@ declare function createMerchantPartnerWorkspaceMock(options?: {
|
|
|
88
88
|
requests: MerchantPartnerWorkspaceRequest[];
|
|
89
89
|
};
|
|
90
90
|
|
|
91
|
-
/** Safe dev projection for Merchant Partner Workspace testing. */
|
|
92
91
|
declare const merchantDevAppFixture: {
|
|
93
92
|
app_id: string;
|
|
94
93
|
display_name: string;
|
|
@@ -97,7 +96,6 @@ declare const merchantDevAppFixture: {
|
|
|
97
96
|
status: "draft";
|
|
98
97
|
allowed_origins: string[];
|
|
99
98
|
};
|
|
100
|
-
/** Negative fixture proving that the testing helper cannot rotate Production apps. */
|
|
101
99
|
declare const merchantProductionAppNegativeFixture: {
|
|
102
100
|
app_id: string;
|
|
103
101
|
display_name: string;
|
|
@@ -107,7 +105,6 @@ declare const merchantProductionAppNegativeFixture: {
|
|
|
107
105
|
allowed_origins: string[];
|
|
108
106
|
credential_version: number;
|
|
109
107
|
};
|
|
110
|
-
/** Read-projection fixture proving future templates remain forward-compatible. */
|
|
111
108
|
declare const merchantFutureTemplateProjectionFixture: {
|
|
112
109
|
app_id: string;
|
|
113
110
|
display_name: string;
|
|
@@ -122,22 +119,14 @@ type FactoConnectFixtureScenario = 'happy_path' | 'setup_required' | 'idempotenc
|
|
|
122
119
|
interface FactoConnectFixtureTransportOptions {
|
|
123
120
|
scenario?: FactoConnectFixtureScenario;
|
|
124
121
|
}
|
|
125
|
-
/** Contract-aligned Dev scenarios for zero-network consumer tests. */
|
|
126
122
|
declare const devScenarios: readonly ["approved", "declined_setup", "declined_limit", "payment_failed"];
|
|
127
|
-
/** Deterministic public Dev projections. They model contract data, not deployment availability. */
|
|
128
123
|
declare const devFixtures: Readonly<{
|
|
129
124
|
capabilities: DevCapabilities;
|
|
130
125
|
faucetTransfer: DevFaucetTransfer;
|
|
131
126
|
simulation: DevSimulation;
|
|
132
127
|
webhookTestDelivery: WebhookTestDeliveryAccepted;
|
|
133
128
|
}>;
|
|
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
|
-
*/
|
|
139
129
|
declare function createFactoConnectFixtureTransport(options?: FactoConnectFixtureTransportOptions): FactoConnectTransport;
|
|
140
|
-
/** Alias named by `dev-sdk-surface-v1`; remains fully in-memory. */
|
|
141
130
|
declare const createFactoTestTransport: typeof createFactoConnectFixtureTransport;
|
|
142
131
|
|
|
143
132
|
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 '../index.d-DE9GmLfU.js';
|
|
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,7 +88,6 @@ declare function createMerchantPartnerWorkspaceMock(options?: {
|
|
|
88
88
|
requests: MerchantPartnerWorkspaceRequest[];
|
|
89
89
|
};
|
|
90
90
|
|
|
91
|
-
/** Safe dev projection for Merchant Partner Workspace testing. */
|
|
92
91
|
declare const merchantDevAppFixture: {
|
|
93
92
|
app_id: string;
|
|
94
93
|
display_name: string;
|
|
@@ -97,7 +96,6 @@ declare const merchantDevAppFixture: {
|
|
|
97
96
|
status: "draft";
|
|
98
97
|
allowed_origins: string[];
|
|
99
98
|
};
|
|
100
|
-
/** Negative fixture proving that the testing helper cannot rotate Production apps. */
|
|
101
99
|
declare const merchantProductionAppNegativeFixture: {
|
|
102
100
|
app_id: string;
|
|
103
101
|
display_name: string;
|
|
@@ -107,7 +105,6 @@ declare const merchantProductionAppNegativeFixture: {
|
|
|
107
105
|
allowed_origins: string[];
|
|
108
106
|
credential_version: number;
|
|
109
107
|
};
|
|
110
|
-
/** Read-projection fixture proving future templates remain forward-compatible. */
|
|
111
108
|
declare const merchantFutureTemplateProjectionFixture: {
|
|
112
109
|
app_id: string;
|
|
113
110
|
display_name: string;
|
|
@@ -122,22 +119,14 @@ type FactoConnectFixtureScenario = 'happy_path' | 'setup_required' | 'idempotenc
|
|
|
122
119
|
interface FactoConnectFixtureTransportOptions {
|
|
123
120
|
scenario?: FactoConnectFixtureScenario;
|
|
124
121
|
}
|
|
125
|
-
/** Contract-aligned Dev scenarios for zero-network consumer tests. */
|
|
126
122
|
declare const devScenarios: readonly ["approved", "declined_setup", "declined_limit", "payment_failed"];
|
|
127
|
-
/** Deterministic public Dev projections. They model contract data, not deployment availability. */
|
|
128
123
|
declare const devFixtures: Readonly<{
|
|
129
124
|
capabilities: DevCapabilities;
|
|
130
125
|
faucetTransfer: DevFaucetTransfer;
|
|
131
126
|
simulation: DevSimulation;
|
|
132
127
|
webhookTestDelivery: WebhookTestDeliveryAccepted;
|
|
133
128
|
}>;
|
|
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
|
-
*/
|
|
139
129
|
declare function createFactoConnectFixtureTransport(options?: FactoConnectFixtureTransportOptions): FactoConnectTransport;
|
|
140
|
-
/** Alias named by `dev-sdk-surface-v1`; remains fully in-memory. */
|
|
141
130
|
declare const createFactoTestTransport: typeof createFactoConnectFixtureTransport;
|
|
142
131
|
|
|
143
132
|
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,2 +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=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};
|
|
2
|
-
//# sourceMappingURL=index.js.map
|
|
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};
|
package/package.json
CHANGED
|
@@ -1,7 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@facto-to/connect",
|
|
3
|
-
"version": "0.0.1-beta.
|
|
3
|
+
"version": "0.0.1-beta.5",
|
|
4
4
|
"description": "Facto Connect SDK for linking partner users to Facto accounts and payment routes.",
|
|
5
|
+
"homepage": "https://facto.to",
|
|
6
|
+
"author": "Facto (https://facto.to)",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"facto",
|
|
9
|
+
"payments",
|
|
10
|
+
"connect",
|
|
11
|
+
"stablecoin",
|
|
12
|
+
"checkout",
|
|
13
|
+
"merchant",
|
|
14
|
+
"sdk"
|
|
15
|
+
],
|
|
5
16
|
"repository": {
|
|
6
17
|
"type": "git",
|
|
7
18
|
"url": "git+https://github.com/Facto-to/sdk.git",
|
|
@@ -14,24 +25,44 @@
|
|
|
14
25
|
"types": "./dist/browser/index.d.ts",
|
|
15
26
|
"exports": {
|
|
16
27
|
".": {
|
|
17
|
-
"
|
|
18
|
-
|
|
19
|
-
|
|
28
|
+
"import": {
|
|
29
|
+
"types": "./dist/browser/index.d.ts",
|
|
30
|
+
"default": "./dist/browser/index.js"
|
|
31
|
+
},
|
|
32
|
+
"require": {
|
|
33
|
+
"types": "./dist/browser/index.d.cts",
|
|
34
|
+
"default": "./dist/browser/index.cjs"
|
|
35
|
+
}
|
|
20
36
|
},
|
|
21
37
|
"./server": {
|
|
22
|
-
"
|
|
23
|
-
|
|
24
|
-
|
|
38
|
+
"import": {
|
|
39
|
+
"types": "./dist/server/index.d.ts",
|
|
40
|
+
"default": "./dist/server/index.js"
|
|
41
|
+
},
|
|
42
|
+
"require": {
|
|
43
|
+
"types": "./dist/server/index.d.cts",
|
|
44
|
+
"default": "./dist/server/index.cjs"
|
|
45
|
+
}
|
|
25
46
|
},
|
|
26
47
|
"./testing": {
|
|
27
|
-
"
|
|
28
|
-
|
|
29
|
-
|
|
48
|
+
"import": {
|
|
49
|
+
"types": "./dist/testing/index.d.ts",
|
|
50
|
+
"default": "./dist/testing/index.js"
|
|
51
|
+
},
|
|
52
|
+
"require": {
|
|
53
|
+
"types": "./dist/testing/index.d.cts",
|
|
54
|
+
"default": "./dist/testing/index.cjs"
|
|
55
|
+
}
|
|
30
56
|
},
|
|
31
57
|
"./react": {
|
|
32
|
-
"
|
|
33
|
-
|
|
34
|
-
|
|
58
|
+
"import": {
|
|
59
|
+
"types": "./dist/react/index.d.ts",
|
|
60
|
+
"default": "./dist/react/index.js"
|
|
61
|
+
},
|
|
62
|
+
"require": {
|
|
63
|
+
"types": "./dist/react/index.d.cts",
|
|
64
|
+
"default": "./dist/react/index.cjs"
|
|
65
|
+
}
|
|
35
66
|
},
|
|
36
67
|
"./package.json": "./package.json"
|
|
37
68
|
},
|
|
@@ -58,15 +89,18 @@
|
|
|
58
89
|
"prepublishOnly": "npm run build"
|
|
59
90
|
},
|
|
60
91
|
"devDependencies": {
|
|
61
|
-
"@facto-to/chains": "0.0.1-beta.
|
|
92
|
+
"@facto-to/chains": "0.0.1-beta.5",
|
|
62
93
|
"@facto-to/engine-wire": "0.2.0",
|
|
63
|
-
"@types/node": "^
|
|
64
|
-
"jsdom": "^
|
|
94
|
+
"@types/node": "^26.4.0",
|
|
95
|
+
"jsdom": "^30.0.1",
|
|
65
96
|
"tsup": "^8.5.0",
|
|
66
97
|
"typescript": "^5.9.3",
|
|
67
|
-
"vitest": "^
|
|
98
|
+
"vitest": "^4.1.11"
|
|
68
99
|
},
|
|
69
100
|
"publishConfig": {
|
|
70
101
|
"access": "restricted"
|
|
102
|
+
},
|
|
103
|
+
"engines": {
|
|
104
|
+
"node": ">=20.9.0"
|
|
71
105
|
}
|
|
72
106
|
}
|