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

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.
Files changed (38) hide show
  1. package/README.md +140 -81
  2. package/dist/browser/index.cjs +29 -20
  3. package/dist/browser/index.d.cts +1 -31
  4. package/dist/browser/index.d.ts +1 -31
  5. package/dist/browser/index.js +28 -19
  6. package/dist/card-transport-Zh-6EMPi.d.cts +63 -0
  7. package/dist/card-transport-Zh-6EMPi.d.ts +63 -0
  8. package/dist/chunk-2WJ3CACP.js +1 -0
  9. package/dist/chunk-MSUNZ66U.js +2 -0
  10. package/dist/cli/index.cjs +6 -0
  11. package/dist/cli/index.d.cts +1 -0
  12. package/dist/cli/index.d.ts +1 -0
  13. package/dist/cli/index.js +5 -0
  14. package/dist/index.d-BikZSd0p.d.cts +1030 -0
  15. package/dist/index.d-BikZSd0p.d.ts +1030 -0
  16. package/dist/react/index.cjs +0 -1
  17. package/dist/react/index.js +0 -1
  18. package/dist/server/card-connect-admin-client.cjs +2 -0
  19. package/dist/server/card-connect-admin-client.d.cts +318 -0
  20. package/dist/server/card-connect-admin-client.d.ts +318 -0
  21. package/dist/server/card-connect-admin-client.js +1 -0
  22. package/dist/server/index.cjs +1 -2
  23. package/dist/server/index.d.cts +1186 -291
  24. package/dist/server/index.d.ts +1186 -291
  25. package/dist/server/index.js +1 -2
  26. package/dist/testing/index.cjs +1 -2
  27. package/dist/testing/index.d.cts +2 -12
  28. package/dist/testing/index.d.ts +2 -12
  29. package/dist/testing/index.js +1 -2
  30. package/package.json +64 -17
  31. package/dist/browser/index.cjs.map +0 -1
  32. package/dist/browser/index.js.map +0 -1
  33. package/dist/react/index.cjs.map +0 -1
  34. package/dist/react/index.js.map +0 -1
  35. package/dist/server/index.cjs.map +0 -1
  36. package/dist/server/index.js.map +0 -1
  37. package/dist/testing/index.cjs.map +0 -1
  38. package/dist/testing/index.js.map +0 -1
@@ -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{a as jt,b as Ee,d as qn}from"../chunk-2WJ3CACP.js";import{createHmac as Fr,timingSafeEqual as _i}from"node:crypto";var Nt=["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 Dt=["payment_route_not_provisioned","protocol_config_incomplete"],Mt=["account_default","mandate_pinned"];var Ln="/.well-known/facto/card/connect/jwks.json",w=class extends Error{code;details;constructor(e,n,r={}){super(n),this.name="FactoIntentTokenError",this.code=e,this.details=r.details}},Zr="facto",eo={dev:"https://dev-api.facto.to",sandbox:"https://dev-api.facto.to",production:"https://api.facto.to"};var no=["dev","sandbox","production"];function to(t){return ro(t,no)}async function ro(t,e){if(t===null||typeof t!="object")throw new w("FACTO_INTENT_TOKEN_INPUT_INVALID","verifyCardIntentToken requires an input object");let n=Kn(t.intentToken,"intentToken"),r=Kn(t.audience,"audience"),o=t.issuer===void 0?Zr:Kn(t.issuer,"issuer"),a=fo(t.clockToleranceSeconds),s=Math.floor(Ro(t.nowMs)/1e3),{headerB64:d,payloadB64:u,signature:l}=io(n),i=Fn(Ut(d,"header"),"FACTO_INTENT_TOKEN_MALFORMED","intent token header");if(i.alg!=="EdDSA")throw new w("FACTO_INTENT_TOKEN_UNSUPPORTED_ALG","intent token JWS alg must be EdDSA",{details:{alg:i.alg}});let p=typeof i.kid=="string"?i.kid:void 0,g=oo(t,e),v=await ao(g),M=lo(v,p),b=ho(`${d}.${u}`);if(!await po(b,l,M))throw new w("FACTO_INTENT_TOKEN_SIGNATURE_INVALID","intent token signature does not verify against the Facto JWKS");let I=mo(Ut(u,"payload"));if(I.iss!==o)throw new w("FACTO_INTENT_TOKEN_ISSUER_MISMATCH","intent token issuer mismatch",{details:{expected:o,actual:I.iss}});if(I.aud!==r)throw new w("FACTO_INTENT_TOKEN_AUDIENCE_MISMATCH","intent token audience mismatch",{details:{expected:r,actual:I.aud}});if(s>I.exp+a)throw new w("FACTO_INTENT_TOKEN_EXPIRED","intent token has expired",{details:{exp:I.exp,now:s}});return{programId:I.program_id,pairwiseSubject:I.sub,nonce:I.nonce,expiresAt:new Date(I.exp*1e3).toISOString()}}function oo(t,e){if(t.jwks!==void 0&&t.jwks!==null)return t.jwks;if(typeof t.apiBaseUrl=="string"&&t.apiBaseUrl.length>0){let n;try{n=new URL(t.apiBaseUrl)}catch{throw new w("FACTO_INTENT_TOKEN_JWKS_INVALID",`apiBaseUrl is not a valid URL: ${t.apiBaseUrl}`)}if(n.username||n.password||n.search||n.hash||n.pathname!=="/"&&n.pathname!=="")throw new w("FACTO_INTENT_TOKEN_JWKS_INVALID","apiBaseUrl must be a bare origin without path, query, or credentials");return`${n.origin}${Ln}`}if(t.environment!==void 0){let n=e.find(r=>r===t.environment);if(n===void 0)throw new w("FACTO_INTENT_TOKEN_INPUT_INVALID",`environment must be one of ${e.map(r=>`'${r}'`).join(", ")}`);return`${eo[n]}${Ln}`}throw new w("FACTO_INTENT_TOKEN_INPUT_INVALID","jwks, apiBaseUrl, or environment is required")}function io(t){let e=t.split(".");if(e.length!==3)throw new w("FACTO_INTENT_TOKEN_MALFORMED","intent token is not a compact JWS (expected three segments)");let[n,r,o]=e;if(!n||!r||!o)throw new w("FACTO_INTENT_TOKEN_MALFORMED","intent token has an empty JWS segment");return{headerB64:n,payloadB64:r,signature:$t(o,"signature")}}function Ut(t,e){let n=new TextDecoder().decode($t(t,e));try{return JSON.parse(n)}catch(r){throw new w("FACTO_INTENT_TOKEN_MALFORMED",`intent token ${e} is not valid JSON`,{details:r})}}async function ao(t){return $n(typeof t=="function"?await t():typeof t=="string"?await co(t):t)}var so=5e3,hn=64*1024;async function co(t){let e;try{e=new URL(t)}catch{throw new w("FACTO_INTENT_TOKEN_JWKS_INVALID",`JWKS url is not a valid URL: ${t}`)}if(e.protocol!=="https:")throw new w("FACTO_INTENT_TOKEN_JWKS_INVALID",`JWKS url must use https: (got ${e.protocol})`,{details:{protocol:e.protocol}});let n=new AbortController,r=setTimeout(()=>n.abort(),so),o,a;try{try{o=await fetch(t,{method:"GET",headers:{accept:"application/json"},redirect:"follow",signal:n.signal})}catch(d){throw new w("FACTO_INTENT_TOKEN_JWKS_INVALID",`failed to fetch Facto JWKS from ${t}`,{details:d})}if(!o.ok)throw new w("FACTO_INTENT_TOKEN_JWKS_INVALID",`Facto JWKS request failed with status ${o.status}`,{details:{status:o.status}});let s=Number(o.headers.get("content-length"));if(Number.isFinite(s)&&s>hn)throw new w("FACTO_INTENT_TOKEN_JWKS_INVALID",`Facto JWKS response exceeds ${hn} bytes`,{details:{contentLength:s}});try{a=await o.text()}catch(d){throw new w("FACTO_INTENT_TOKEN_JWKS_INVALID","Facto JWKS response could not be read",{details:d})}}finally{clearTimeout(r)}if(a.length>hn)throw new w("FACTO_INTENT_TOKEN_JWKS_INVALID",`Facto JWKS response exceeds ${hn} bytes`,{details:{bytes:a.length}});try{return JSON.parse(a)}catch(s){throw new w("FACTO_INTENT_TOKEN_JWKS_INVALID","Facto JWKS response was not valid JSON",{details:s})}}function $n(t){let e=Fn(t,"FACTO_INTENT_TOKEN_JWKS_INVALID","JWKS");if(!Array.isArray(e.keys))throw new w("FACTO_INTENT_TOKEN_JWKS_INVALID",'JWKS "keys" must be an array');return{keys:e.keys.map(uo)}}function uo(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 lo(t,e){let n=t.keys.filter(r=>r.kty==="OKP"&&r.crv==="Ed25519"&&r.x.length>0);if(n.length===0)throw new w("FACTO_INTENT_TOKEN_JWKS_INVALID","Facto JWKS has no usable Ed25519 signing key");if(e!==void 0){let r=n.filter(o=>o.kid===e);if(r.length>0)return r}return n}async function po(t,e,n){let r=go();for(let o of n){let a;try{a=await r.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:o.x},{name:"Ed25519"},!1,["verify"])}catch{continue}try{if(await r.verify({name:"Ed25519"},a,e,t))return!0}catch{continue}}return!1}function mo(t){let e=Fn(t,"FACTO_INTENT_TOKEN_CLAIMS_INVALID","intent token claims"),n=e.program_id,r=e.program_ref;if(typeof n=="string"&&n.length>0&&typeof r=="string"&&r.length>0&&n!==r)throw new w("FACTO_INTENT_TOKEN_CLAIMS_INVALID",'intent token claims "program_id" and "program_ref" must match when both are present');let o=typeof n=="string"&&n.length>0?n:Je(e,"program_ref");return{iss:Je(e,"iss"),aud:Je(e,"aud"),sub:Je(e,"sub"),program_id:o,nonce:Je(e,"nonce"),iat:qt(e,"iat"),exp:qt(e,"exp")}}function Kn(t,e){if(typeof t!="string"||t.length===0)throw new w("FACTO_INTENT_TOKEN_INPUT_INVALID",`${e} must be a non-empty string`);return t}function fo(t){if(t===void 0)return 0;if(typeof t!="number"||!Number.isFinite(t)||t<0)throw new w("FACTO_INTENT_TOKEN_INPUT_INVALID","clockToleranceSeconds must be a non-negative finite number");return t}function Ro(t){if(t===void 0)return Date.now();if(t instanceof Date){let e=t.getTime();if(Number.isNaN(e))throw new w("FACTO_INTENT_TOKEN_INPUT_INVALID","nowMs is an invalid Date");return e}if(typeof t=="number"&&Number.isFinite(t))return t;throw new w("FACTO_INTENT_TOKEN_INPUT_INVALID","nowMs must be a Date or unix milliseconds number")}function Fn(t,e,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new w(e,`${n} must be a JSON object`);return t}function Je(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new w("FACTO_INTENT_TOKEN_CLAIMS_INVALID",`intent token claim "${e}" must be a non-empty string`);return n}function qt(t,e){let n=t[e];if(typeof n!="number"||!Number.isFinite(n))throw new w("FACTO_INTENT_TOKEN_CLAIMS_INVALID",`intent token claim "${e}" must be a finite number`);return n}function $t(t,e){if(!/^[A-Za-z0-9_-]*$/.test(t))throw new w("FACTO_INTENT_TOKEN_MALFORMED",`intent token ${e} is not valid base64url`);let n=t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4);return yo(n,e)}function yo(t,e){let n=globalThis.atob;if(n){let o;try{o=n(t)}catch(s){throw new w("FACTO_INTENT_TOKEN_MALFORMED",`intent token ${e} is not valid base64url`,{details:s})}let a=new Uint8Array(o.length);for(let s=0;s<o.length;s+=1)a[s]=o.charCodeAt(s);return a}let r=globalThis.Buffer;if(r)return new Uint8Array(r.from(t,"base64"));throw new w("FACTO_INTENT_TOKEN_INPUT_INVALID","No base64 decoder is available in this runtime")}function ho(t){let e=new TextEncoder().encode(t),n=new Uint8Array(e.length);return n.set(e),n}function go(){let t=globalThis.crypto;if(t?.subtle)return t.subtle;throw new w("FACTO_INTENT_TOKEN_INPUT_INVALID","Web Crypto (crypto.subtle) is not available in this runtime")}var Eo=["psp_connect_sandbox","psp_mandate_sandbox","psp_billing_sandbox"],Kt={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 Co(t){return Kt[t].includes("payments.execute")}var So={dev:{clientIdPrefix:"dev_pspid_",clientSecretPrefix:"dev_pspsk_"},test:{clientIdPrefix:"test_pspid_"},lab:{clientIdPrefix:"lab_pspid_"}},_o="psp";function wo(t,e){return{...t,...e.ref===void 0?{}:{subMerchantRef:e.ref},...e.displayName===void 0?{}:{subMerchantDisplayName:e.displayName}}}function Po(t){return{...t.subMerchantRef==null?{}:{ref:t.subMerchantRef},...t.subMerchantDisplayName==null?{}:{displayName:t.subMerchantDisplayName}}}import{createHash as vo,randomUUID as zt}from"node:crypto";var Io="9223372036854775807",To=9223372036854775807n,Ao=/^(0|[1-9][0-9]{0,18})$/,Oo=/^sha256:[0-9a-f]{64}$/,bo=Object.freeze(["sessionId","session","token","accessToken","refreshToken","bearerToken","authorization","ephemeralSession","ephemeralSessionId","cookie","jwt"]),_=class extends Error{code="ENTERPRISE_JOURNAL_VALIDATION_ERROR";constructor(e){super(e),this.name="EnterpriseJournalValidationError"}},pe=class extends Error{code="ENTERPRISE_JOURNAL_CONFLICT_ERROR";idempotencyKey;conflictingField;constructor(e,n){super(`Idempotency key "${e}" conflicts with existing frozen journal envelope on "${n}".`),this.name="EnterpriseJournalConflictError",this.idempotencyKey=e,this.conflictingField=n}},ee=class extends Error{code="ENTERPRISE_JOURNAL_ACCESS_DENIED";constructor(e){super(`Enterprise command journal access denied: ${e}.`),this.name="EnterpriseJournalAccessDeniedError"}},T=class extends Error{code="ENTERPRISE_JOURNAL_INTEGRITY_ERROR";constructor(e){super(`Enterprise command journal integrity check failed: ${e}.`),this.name="EnterpriseJournalIntegrityError"}},Ae=class extends Error{code="ENTERPRISE_JOURNAL_STORE_ERROR";constructor(e,n){super(e,n),this.name="EnterpriseJournalStoreError"}};function we(t){if(!(t instanceof Uint8Array))throw new _("canonicalRequestBytes must be a Uint8Array.");return`sha256:${vo("sha256").update(t).digest("hex")}`}function Ye(t,e){if(typeof t!="string")throw new _(`${e} must be a decimal string, received ${typeof t}.`);if(!Ao.test(t))throw new _(`${e} must be a canonical non-negative decimal integer string without leading zeros.`);let n=BigInt(t);if(n<0n||n>To)throw new _(`${e} exceeds PostgreSQL BIGINT non-negative range (0..${Io}).`)}function ne(t,e="casTriple"){if(!Array.isArray(t)||t.length!==3)throw new _(`${e} must be a 3-element tuple of non-negative BIGINT decimal strings.`);let[n,r,o]=t;return Ye(n,`${e}[0]`),Ye(r,`${e}[1]`),Ye(o,`${e}[2]`),Object.freeze([n,r,o])}function D(t,e,n=_){if(typeof t!="string"||t.length===0||t.trim()!==t)throw new n(`${e} must be a non-empty string without leading or trailing whitespace.`)}function Lt(t){let e=t.toLowerCase();if(e.startsWith("bearer ")||e.startsWith("basic "))return!0;let n=t.split(".");return!!(n.length===3&&n.every(r=>r.length>=8))}function _e(t,e=_){if(typeof t!="object"||t===null||Array.isArray(t))throw new e("ownerScope must be a non-null plain object.");let n=t;for(let a of bo)if(a in n&&n[a]!==void 0)throw new e(`ownerScope must not contain ephemeral session or token field "${a}".`);let r=new Set(["audience","principalId","appId","organizationId","targetRealm","opaqueIdentityRef"]);for(let a of Object.keys(n))if(!r.has(a))throw new e(`ownerScope contains unsupported field "${a}".`);D(n.audience,"ownerScope.audience",e),D(n.principalId,"ownerScope.principalId",e),D(n.appId,"ownerScope.appId",e),D(n.organizationId,"ownerScope.organizationId",e),D(n.targetRealm,"ownerScope.targetRealm",e);for(let[a,s]of[["ownerScope.audience",n.audience],["ownerScope.principalId",n.principalId],["ownerScope.appId",n.appId],["ownerScope.organizationId",n.organizationId],["ownerScope.targetRealm",n.targetRealm]])if(Lt(s))throw new e(`${a} must not carry a bearer or JWT token value.`);if(n.opaqueIdentityRef!==void 0&&(D(n.opaqueIdentityRef,"ownerScope.opaqueIdentityRef",e),Lt(n.opaqueIdentityRef)))throw new e("ownerScope.opaqueIdentityRef must not carry a bearer or JWT token.");let o=n.opaqueIdentityRef===void 0?{audience:n.audience,principalId:n.principalId,appId:n.appId,organizationId:n.organizationId,targetRealm:n.targetRealm}:{audience:n.audience,principalId:n.principalId,appId:n.appId,organizationId:n.organizationId,targetRealm:n.targetRealm,opaqueIdentityRef:n.opaqueIdentityRef};return Object.freeze(o)}function Bt(t){return t.map(e=>`${e.length}:${e}`).join("|")}function Bn(t){let e=_e(t);return Bt([e.audience,e.principalId,e.appId,e.organizationId,e.targetRealm])}function Qe(t,e){D(e,"idempotencyKey");let n=Bn(t);return`enterprise-journal:v1:${Bt([n,e])}`}function Wn(t,e){return t.audience===e.audience&&t.principalId===e.principalId&&t.appId===e.appId&&t.organizationId===e.organizationId&&t.targetRealm===e.targetRealm}function Xe(t){let e=new Uint8Array(t.byteLength);return e.set(t),e}function ko(t,e){if(t.byteLength!==e.byteLength)return!1;for(let n=0;n<t.byteLength;n+=1)if(t[n]!==e[n])return!1;return!0}function xo(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new _("envelope must be a non-null plain object.");let e=t,n=_e(e.ownerScope);if(D(e.commandRef,"envelope.commandRef"),D(e.idempotencyKey,"envelope.idempotencyKey"),D(e.kind,"envelope.kind"),D(e.scopeRef,"envelope.scopeRef"),D(e.businessRef,"envelope.businessRef"),!(e.canonicalRequestBytes instanceof Uint8Array)||e.canonicalRequestBytes.byteLength===0)throw new _("envelope.canonicalRequestBytes must be a non-empty Uint8Array.");let r=Xe(e.canonicalRequestBytes);if(D(e.inputDigest,"envelope.inputDigest"),!Oo.test(e.inputDigest))throw new _('envelope.inputDigest must be formatted as "sha256:<64 lowercase hex chars>".');let o=we(r);if(e.inputDigest!==o)throw new _(`envelope.inputDigest (${e.inputDigest}) does not match canonicalRequestBytes digest (${o}).`);let a=ne(e.casTriple,"envelope.casTriple");return Object.freeze({ownerScope:n,commandRef:e.commandRef,idempotencyKey:e.idempotencyKey,kind:e.kind,scopeRef:e.scopeRef,businessRef:e.businessRef,canonicalRequestBytes:r,inputDigest:e.inputDigest,casTriple:a})}function gn(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw new _("caller context must be a non-null object.");let n=t,r=_e(n.ownerScope);if(D(n.sessionId,"caller.sessionId"),typeof n.authEpoch!="number"||!Number.isSafeInteger(n.authEpoch)||n.authEpoch<0)throw new _("caller.authEpoch must be a non-negative safe integer.");if(typeof n.canRead!="boolean"||typeof n.canExecute!="boolean")throw new _("caller.canRead and caller.canExecute must be booleans.");if(!n.canRead)throw new ee("caller session does not have read permission");if(e&&!n.canExecute)throw new ee("caller session does not have execute permission");return Object.freeze({ownerScope:r,sessionId:n.sessionId,authEpoch:n.authEpoch,canRead:n.canRead,canExecute:n.canExecute})}var jo=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,No=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function Do(t){return t%4===0&&t%100!==0||t%400===0}function Sn(t){if(typeof t!="string"||t.length===0||t.trim()!==t)return!1;let e=No.exec(t);if(e===null)return!1;let n=Number(e[1]),r=Number(e[2]),o=Number(e[3]),a=Number(e[4]),s=Number(e[5]),d=Number(e[6]),u=e[8],l=e[9]!==void 0?Number(e[9]):0,i=e[10]!==void 0?Number(e[10]):0;if(r<1||r>12)return!1;let p=[31,Do(n)?29:28,31,30,31,30,31,31,30,31,30,31][r-1];return o<1||o>p||a<0||a>23||s<0||s>59||d<0||d>59||u!==void 0&&(l<0||l>23||i<0||i>59)?!1:Number.isFinite(Date.parse(t))}function Mo(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64")}function Uo(t,e){if(typeof t!="string"||t.length===0||t.length%4!==0||!jo.test(t))throw new T("persisted canonicalRequestBytesBase64 is not valid base64.");let n=Buffer.from(t,"base64");if(n.byteLength!==e||n.toString("base64")!==t)throw new T("persisted canonicalRequestBytesBase64 length or canonical encoding mismatch.");return Xe(new Uint8Array(n.buffer,n.byteOffset,n.byteLength))}function Re(t){let e=_e(t.envelope.ownerScope,T),n;try{n=ne(t.envelope.casTriple,"persisted.envelope.casTriple")}catch(s){throw new T(s instanceof Error?s.message:"invalid persisted casTriple")}let r;if(t.state.resolvedOutcome!==void 0){let s=t.state.resolvedOutcome;if(D(s.completionRef,"persisted.state.resolvedOutcome.completionRef",T),D(s.observedAtIso,"persisted.state.resolvedOutcome.observedAtIso",T),!Sn(s.observedAtIso))throw new T("persisted.state.resolvedOutcome.observedAtIso must be a valid ISO-8601 timestamp.");let d;if(s.currentResourceCasTriple!==void 0)try{d=ne(s.currentResourceCasTriple,"persisted.state.resolvedOutcome.currentResourceCasTriple")}catch(u){throw new T(u instanceof Error?u.message:"invalid persisted resolvedOutcome.currentResourceCasTriple")}r=Object.freeze({completionRef:s.completionRef,observedAtIso:s.observedAtIso,...d===void 0?{}:{currentResourceCasTriple:d}})}let o=Object.freeze({ownerScope:e,commandRef:t.envelope.commandRef,idempotencyKey:t.envelope.idempotencyKey,kind:t.envelope.kind,scopeRef:t.envelope.scopeRef,businessRef:t.envelope.businessRef,canonicalRequestBytesBase64:t.envelope.canonicalRequestBytesBase64,canonicalRequestByteLength:t.envelope.canonicalRequestByteLength,inputDigest:t.envelope.inputDigest,casTriple:n}),a=Object.freeze({status:t.state.status,firstPostMarked:!0,firstPostPermitToken:t.state.firstPostPermitToken,sendAttempted:t.state.sendAttempted,...t.state.lastObservationKind===void 0?{}:{lastObservationKind:t.state.lastObservationKind},...r===void 0?{}:{resolvedOutcome:r}});return Object.freeze({schemaVersion:1,storageKey:t.storageKey,revision:t.revision,envelope:o,state:a})}function le(t,e,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new T("persisted record must be a non-null object");let r=t;if(r.schemaVersion!==1)throw new T(`unsupported schemaVersion "${String(r.schemaVersion)}"`);if(typeof r.revision!="number"||!Number.isSafeInteger(r.revision)||r.revision<1)throw new T("persisted revision must be a positive integer");if(typeof r.envelope!="object"||r.envelope===null)throw new T("persisted envelope is missing");if(typeof r.state!="object"||r.state===null)throw new T("persisted state is missing");let o=_e(r.envelope.ownerScope,T);if(!Wn(o,e))throw new ee("caller owner partition does not match journal entry owner partition");if(D(r.envelope.commandRef,"persisted.envelope.commandRef",T),D(r.envelope.idempotencyKey,"persisted.envelope.idempotencyKey",T),n!==void 0&&r.envelope.idempotencyKey!==n)throw new T("persisted idempotencyKey does not match requested lookup key");if(D(r.envelope.kind,"persisted.envelope.kind",T),D(r.envelope.scopeRef,"persisted.envelope.scopeRef",T),D(r.envelope.businessRef,"persisted.envelope.businessRef",T),D(r.envelope.inputDigest,"persisted.envelope.inputDigest",T),typeof r.envelope.canonicalRequestByteLength!="number"||!Number.isSafeInteger(r.envelope.canonicalRequestByteLength)||r.envelope.canonicalRequestByteLength<=0)throw new T("persisted canonicalRequestByteLength must be a positive integer");let a=Uo(r.envelope.canonicalRequestBytesBase64,r.envelope.canonicalRequestByteLength);if(we(a)!==r.envelope.inputDigest)throw new T("persisted canonicalRequestBytes digest does not match persisted inputDigest");let d=Qe(o,r.envelope.idempotencyKey);if(r.storageKey!==d)throw new T("persisted storageKey does not match derived owner+idempotencyKey storageKey");if(r.state.firstPostMarked!==!0)throw new T("persisted state must have firstPostMarked=true");if(D(r.state.firstPostPermitToken,"persisted.state.firstPostPermitToken",T),typeof r.state.sendAttempted!="boolean")throw new T("persisted state.sendAttempted must be a boolean");if(r.state.status!=="send_permitted"&&r.state.status!=="unknown"&&r.state.status!=="parked"&&r.state.status!=="resolved")throw new T("persisted state.status is invalid");if(r.state.status==="resolved"&&r.state.resolvedOutcome===void 0)throw new T('persisted state.status="resolved" requires resolvedOutcome');let u=Re(r),l=Object.freeze({ownerScope:u.envelope.ownerScope,commandRef:u.envelope.commandRef,idempotencyKey:u.envelope.idempotencyKey,kind:u.envelope.kind,scopeRef:u.envelope.scopeRef,businessRef:u.envelope.businessRef,canonicalRequestBytes:a,inputDigest:u.envelope.inputDigest,casTriple:u.envelope.casTriple});return{record:u,decodedEnvelope:l}}function zn(t,e){if(!Wn(t.ownerScope,e.ownerScope))throw new ee("incoming envelope owner partition does not match existing entry owner partition");if(t.ownerScope.opaqueIdentityRef!==void 0&&e.ownerScope.opaqueIdentityRef!==void 0&&t.ownerScope.opaqueIdentityRef!==e.ownerScope.opaqueIdentityRef)throw new pe(e.idempotencyKey,"ownerScope.opaqueIdentityRef");if(t.commandRef!==e.commandRef)throw new pe(e.idempotencyKey,"commandRef");if(t.kind!==e.kind)throw new pe(e.idempotencyKey,"kind");if(t.scopeRef!==e.scopeRef)throw new pe(e.idempotencyKey,"scopeRef");if(t.businessRef!==e.businessRef)throw new pe(e.idempotencyKey,"businessRef");if(t.inputDigest!==e.inputDigest)throw new pe(e.idempotencyKey,"inputDigest");if(!ko(t.canonicalRequestBytes,e.canonicalRequestBytes))throw new pe(e.idempotencyKey,"canonicalRequestBytes");if(t.casTriple[0]!==e.casTriple[0]||t.casTriple[1]!==e.casTriple[1]||t.casTriple[2]!==e.casTriple[2])throw new pe(e.idempotencyKey,"casTriple")}function Ft(t,e){if(typeof e!="object"||e===null||Array.isArray(e))return{closed:!1,observationKind:"corrupted_or_unclosed"};let n=e;if(n.kind==="accepted_pending")return{closed:!1,observationKind:"accepted_pending"};if(n.kind==="missing_original")return{closed:!1,observationKind:"missing_original"};if(n.kind==="corrupted_or_unclosed")return{closed:!1,observationKind:"corrupted_or_unclosed"};if(n.kind!=="completed")return{closed:!1,observationKind:"corrupted_or_unclosed"};if(n.commandRef!==t.commandRef||n.idempotencyKey!==t.idempotencyKey||n.commandKind!==t.kind||n.scopeRef!==t.scopeRef||n.businessRef!==t.businessRef||n.inputDigest!==t.inputDigest)return{closed:!1,observationKind:"mismatched_identity_or_digest"};let r;try{r=ne(n.originalCasTriple,"observation.originalCasTriple")}catch{return{closed:!1,observationKind:"invalid_original_cas"}}if(r[0]!==t.casTriple[0]||r[1]!==t.casTriple[1]||r[2]!==t.casTriple[2])return{closed:!1,observationKind:"mismatched_original_cas"};let o;if(n.currentResourceCasTriple!==void 0)try{o=ne(n.currentResourceCasTriple,"observation.currentResourceCasTriple")}catch{return{closed:!1,observationKind:"invalid_current_resource_cas"}}return typeof n.completionRef!="string"||n.completionRef.trim().length===0||!Sn(n.observedAtIso)?{closed:!1,observationKind:"missing_completion_evidence"}:{closed:!0,observationKind:"completed",resolvedOutcome:Object.freeze({completionRef:n.completionRef,observedAtIso:n.observedAtIso,...o===void 0?{}:{currentResourceCasTriple:o}})}}function X(t,e){let n=t.state.status==="send_permitted"?"unknown":t.state.status;return Object.freeze({storageKey:t.storageKey,revision:t.revision,envelope:Object.freeze({...e,ownerScope:_e(e.ownerScope),canonicalRequestBytes:Xe(e.canonicalRequestBytes),casTriple:ne(e.casTriple)}),status:n,firstPostMarked:!0,firstPostPermitToken:t.state.firstPostPermitToken,sendAttempted:t.state.sendAttempted,shouldPollPending:n==="unknown"||n==="parked",grantsExecutionAuthority:!1,...t.state.lastObservationKind===void 0?{}:{lastObservationKind:t.state.lastObservationKind},...t.state.resolvedOutcome===void 0?{}:{resolvedOutcome:t.state.resolvedOutcome}})}var En=class{store;constructor(e){if(typeof e!="object"||e===null||typeof e.store!="object"||e.store===null||e.store.durabilityContract!=="atomic-durable-cas-v1"||typeof e.store.load!="function"||typeof e.store.compareAndSwap!="function")throw new _('EnterpriseCommandJournalCore requires an injected store implementing durabilityContract="atomic-durable-cas-v1".');this.store=e.store}async executeCommand(e){if(typeof e!="object"||e===null||typeof e.sendOnce!="function")throw new _("executeCommand requires caller, envelope, and sendOnce callback.");let n=e.sendOnce,r=gn(e.caller,!0),o=xo(e.envelope);if(!Wn(r.ownerScope,o.ownerScope))throw new ee("caller ownerScope does not match command envelope ownerScope");let a=Qe(o.ownerScope,o.idempotencyKey),s;try{s=await this.store.load(a)}catch(I){throw new Ae("Failed to load journal entry prior to first-POST reservation.",{cause:I})}if(s!==null){let{record:I,decodedEnvelope:q}=le(s,r.ownerScope,o.idempotencyKey);return zn(q,o),{snapshot:X(I,q),sendInvoked:!1}}let d=`permit_${zt()}`,u=Re({schemaVersion:1,storageKey:a,revision:1,envelope:{ownerScope:o.ownerScope,commandRef:o.commandRef,idempotencyKey:o.idempotencyKey,kind:o.kind,scopeRef:o.scopeRef,businessRef:o.businessRef,canonicalRequestBytesBase64:Mo(o.canonicalRequestBytes),canonicalRequestByteLength:o.canonicalRequestBytes.byteLength,inputDigest:o.inputDigest,casTriple:o.casTriple},state:{status:"send_permitted",firstPostMarked:!0,firstPostPermitToken:d,sendAttempted:!1}}),l;try{l=await this.store.compareAndSwap({storageKey:a,expectedRevision:null,nextRecord:Re(u)})}catch(I){throw new Ae("Durable first-POST reservation failed or outcome unknown; send was not invoked.",{cause:I})}if(typeof l!="object"||l===null||typeof l.applied!="boolean")throw new Ae("Store returned malformed CAS receipt; send was not invoked.");if(!l.applied){let I=l.currentRecord!==null?l.currentRecord:await this.store.load(a);if(I===null)throw new Ae("Store rejected first-POST reservation without an existing record; send was not invoked.");let{record:q,decodedEnvelope:Z}=le(I,r.ownerScope,o.idempotencyKey);return zn(Z,o),{snapshot:X(q,Z),sendInvoked:!1}}let{record:i,decodedEnvelope:p}=le(l.record,r.ownerScope,o.idempotencyKey);if(zn(p,o),i.state.firstPostPermitToken!==d||i.state.status!=="send_permitted"||i.state.sendAttempted!==!1)return{snapshot:X(i,p),sendInvoked:!1};let g,v=!1;try{g=await n({envelope:Object.freeze({...p,canonicalRequestBytes:Xe(p.canonicalRequestBytes)}),firstPostPermitToken:d})}catch{v=!0}let M=v?{closed:!1,observationKind:"send_exception_or_timeout"}:Ft(p,g),b=Re({schemaVersion:1,storageKey:a,revision:i.revision+1,envelope:i.envelope,state:{status:M.closed?"resolved":"unknown",firstPostMarked:!0,firstPostPermitToken:d,sendAttempted:!0,lastObservationKind:M.observationKind,...M.closed?{resolvedOutcome:M.resolvedOutcome}:{}}});try{let I=await this.store.compareAndSwap({storageKey:a,expectedRevision:i.revision,nextRecord:Re(b)});if(I&&I.applied){let{record:q,decodedEnvelope:Z}=le(I.record,r.ownerScope,o.idempotencyKey);return{snapshot:X(q,Z),sendInvoked:!0}}}catch{}let V=Re({...b,state:{status:"unknown",firstPostMarked:!0,firstPostPermitToken:d,sendAttempted:!0,lastObservationKind:M.closed?"post_send_persist_unconfirmed":M.observationKind}});return{snapshot:X(V,p),sendInvoked:!0}}async loadEntry(e){if(typeof e!="object"||e===null)throw new _("loadEntry requires caller and idempotencyKey.");let n=gn(e.caller,!1),r=e.idempotencyKey;D(r,"idempotencyKey");let o=Qe(n.ownerScope,r),a=await this.store.load(o);if(a===null)return null;let{record:s,decodedEnvelope:d}=le(a,n.ownerScope,r);return X(s,d)}async parkEntry(e){if(typeof e!="object"||e===null)throw new _("parkEntry requires caller and idempotencyKey.");let n=gn(e.caller,!1),r=e.idempotencyKey;D(r,"idempotencyKey");let o=Qe(n.ownerScope,r),a=await this.store.load(o);if(a===null)throw new _(`Cannot park missing journal entry for idempotencyKey "${r}".`);let{record:s,decodedEnvelope:d}=le(a,n.ownerScope,r);if(s.state.status==="resolved"||s.state.status==="parked")return X(s,d);let u=Re({schemaVersion:1,storageKey:o,revision:s.revision+1,envelope:s.envelope,state:{status:"parked",firstPostMarked:!0,firstPostPermitToken:s.state.firstPostPermitToken,sendAttempted:!0,...s.state.lastObservationKind===void 0?{}:{lastObservationKind:s.state.lastObservationKind}}}),l=await this.store.compareAndSwap({storageKey:o,expectedRevision:s.revision,nextRecord:Re(u)});if(l.applied){let{record:i,decodedEnvelope:p}=le(l.record,n.ownerScope,r);return X(i,p)}if(l.currentRecord!==null){let{record:i,decodedEnvelope:p}=le(l.currentRecord,n.ownerScope,r);return X(i,p)}return X(s,d)}async recoverCommand(e){if(typeof e!="object"||e===null||typeof e.lookup!="function")throw new _("recoverCommand requires caller, idempotencyKey, and read-only lookup callback.");let n=e.lookup,r=gn(e.caller,!1),o=e.idempotencyKey;D(o,"idempotencyKey");let a=Qe(r.ownerScope,o),s=await this.store.load(a);if(s===null)throw new _(`Cannot recover unknown journal key "${o}": no persisted original envelope.`);let{record:d,decodedEnvelope:u}=le(s,r.ownerScope,o),l,i=!1;try{l=await n({envelope:Object.freeze({...u,canonicalRequestBytes:Xe(u.canonicalRequestBytes)})})}catch{i=!0}let p=i?{closed:!1,observationKind:"lookup_exception_or_timeout"}:Ft(u,l);if(d.state.status==="resolved"){if(p.closed&&(p.resolvedOutcome.completionRef!==d.state.resolvedOutcome.completionRef||p.resolvedOutcome.observedAtIso!==d.state.resolvedOutcome.observedAtIso))throw new T("Read-only recovery conflicts with the original closed receipt.");return{snapshot:X(d,u),lookupInvoked:!0}}let g=Re({schemaVersion:1,storageKey:a,revision:d.revision+1,envelope:d.envelope,state:{status:p.closed?"resolved":"unknown",firstPostMarked:!0,firstPostPermitToken:d.state.firstPostPermitToken,sendAttempted:!0,lastObservationKind:p.observationKind,...p.closed?{resolvedOutcome:p.resolvedOutcome}:{}}}),v=await this.store.compareAndSwap({storageKey:a,expectedRevision:d.revision,nextRecord:Re(g)});if(v.applied){let{record:M,decodedEnvelope:b}=le(v.record,r.ownerScope,o);return{snapshot:X(M,b),lookupInvoked:!0}}if(v.currentRecord!==null){let{record:M,decodedEnvelope:b}=le(v.currentRecord,r.ownerScope,o);return{snapshot:X(M,b),lookupInvoked:!0}}return{snapshot:X(g,u),lookupInvoked:!0}}};function qo(t){let e=structuredClone(t),n=r=>{if(!(typeof r!="object"||r===null||Object.isFrozen(r))){Object.freeze(r);for(let o of Object.keys(r))n(r[o])}};return n(e),e}var Cn=class{activeOwnerScope;activeOwnerPartitionKey;activeSessionId;activeAuthEpoch;activeContextGeneration=1;nextTicketCounter=1;appliedTicketWatermark=0;currentProjection=null;issuedTickets=new Map;consumedTicketIds=new Set;constructor(e){let n=_e(e.ownerScope);if(D(e.sessionId,"initialContext.sessionId"),typeof e.authEpoch!="number"||!Number.isSafeInteger(e.authEpoch)||e.authEpoch<0)throw new _("initialContext.authEpoch must be a non-negative safe integer.");this.activeOwnerScope=n,this.activeOwnerPartitionKey=Bn(n),this.activeSessionId=e.sessionId,this.activeAuthEpoch=e.authEpoch}issueTicket(e){let n;if(e!==void 0){if(!Number.isSafeInteger(e)||e<this.nextTicketCounter)throw new _(`explicitTicketNumber must be a safe integer >= ${String(this.nextTicketCounter)} (strictly monotonic, no reuse).`);n=e,this.nextTicketCounter=e+1}else n=this.nextTicketCounter,this.nextTicketCounter+=1;let r=Object.freeze({ticketId:`proj_ticket_${zt()}`,ticketNumber:n,capturedContextGeneration:this.activeContextGeneration,capturedOwnerScope:this.activeOwnerScope,capturedOwnerPartitionKey:this.activeOwnerPartitionKey,capturedSessionId:this.activeSessionId,capturedAuthEpoch:this.activeAuthEpoch});return this.issuedTickets.set(r.ticketId,r),r}switchContext(e){let n=_e(e.ownerScope);if(D(e.sessionId,"nextContext.sessionId"),typeof e.authEpoch!="number"||!Number.isSafeInteger(e.authEpoch)||e.authEpoch<0)throw new _("nextContext.authEpoch must be a non-negative safe integer.");this.activeOwnerScope=n,this.activeOwnerPartitionKey=Bn(n),this.activeSessionId=e.sessionId,this.activeAuthEpoch=e.authEpoch,this.activeContextGeneration+=1,this.appliedTicketWatermark=0,this.currentProjection=null}getProjection(){return this.currentProjection}getAppliedTicketWatermark(){return this.appliedTicketWatermark}applyResponse(e,n){if(typeof e!="object"||e===null||typeof e.ticketId!="string"||this.consumedTicketIds.has(e.ticketId))return{applied:!1,reason:"duplicate_or_unknown_ticket",projection:this.currentProjection,watermarkTicket:this.appliedTicketWatermark};let r=this.issuedTickets.get(e.ticketId);return r===void 0||r.ticketNumber!==e.ticketNumber||r.capturedContextGeneration!==e.capturedContextGeneration||r.capturedOwnerPartitionKey!==e.capturedOwnerPartitionKey||r.capturedSessionId!==e.capturedSessionId||r.capturedAuthEpoch!==e.capturedAuthEpoch?{applied:!1,reason:"duplicate_or_unknown_ticket",projection:this.currentProjection,watermarkTicket:this.appliedTicketWatermark}:(this.consumedTicketIds.add(e.ticketId),r.capturedContextGeneration!==this.activeContextGeneration||r.capturedOwnerPartitionKey!==this.activeOwnerPartitionKey||r.capturedSessionId!==this.activeSessionId||r.capturedAuthEpoch!==this.activeAuthEpoch?{applied:!1,reason:"context_mismatch",projection:this.currentProjection,watermarkTicket:this.appliedTicketWatermark}:r.ticketNumber<=this.appliedTicketWatermark?{applied:!1,reason:"stale_ticket",projection:this.currentProjection,watermarkTicket:this.appliedTicketWatermark}:n.status===401||n.status===403?(this.appliedTicketWatermark=r.ticketNumber,this.currentProjection=null,{applied:!0,action:"cleared_projection",projection:null,watermarkTicket:this.appliedTicketWatermark}):n.status===200?n.bodyValid?(this.appliedTicketWatermark=r.ticketNumber,this.currentProjection=qo(n.projection),{applied:!0,action:"updated_projection",projection:this.currentProjection,watermarkTicket:this.appliedTicketWatermark}):{applied:!1,reason:"corrupted_ok_body",projection:this.currentProjection,watermarkTicket:this.appliedTicketWatermark}:{applied:!1,reason:"corrupted_ok_body",projection:this.currentProjection,watermarkTicket:this.appliedTicketWatermark})}};import{createHash as Ko}from"node:crypto";var Ze="facto.enterprise-command.v1",Vn="enterprise-scope:v1:",Hn="efcreduce_",_n=Object.freeze(["create_or_transition_source_hold","bind_or_transition_guarantee","record_prefund_or_partner_fact","apply_qualified_cash","dispatch_or_observe_execution_family","settle_commercial_reduction"]),Wt=Object.freeze(["bind_or_transition_guarantee","apply_qualified_cash","dispatch_or_observe_execution_family"]),$o=Object.freeze(["create_or_transition_source_hold","record_prefund_or_partner_fact","settle_commercial_reduction"]);function wn(t){return Wt.includes(t)}var Gn=Object.freeze(["source_holds","guarantee_links","prefund_partner_facts","cash_applications","execution_families","commercial_reductions"]),Jn=Object.freeze(["source_observation_unconfirmed","source_observation_expired","unclosed_unknown_hold_or_attempt","prefund_observation_unconfirmed","prefund_observation_expired","unresolved_reorganization","cash_basis_disputed_or_revoked","qualification_unconfirmed","reconciliation_required","current_snapshot_unavailable","pending_commit_observation"]),Qn=Object.freeze(["erc20","native_gas","fiat_minor"]),Yn=Object.freeze(["credit_vault_v1","compound_v2","aave_v3","morpho_blue","custody_direct"]),Xn=Object.freeze(["merchant_mandate_charge","partner_settlement_observation","partner_payout_order","credit_vault_protocol_receipt","consumer_direct_transfer_receipt","partner_funding_capture","original_execution_initiation_observation","original_execution_unused_observation"]),Zn=Object.freeze(["active","executing","unknown","settled_verified_effect","released_verified_unused","expired_verified_unused"]),et=Object.freeze(["settled_verified_effect","released_verified_unused","expired_verified_unused"]),nt=Object.freeze(["active","fulfilled","released_unused","expired_unused"]),tt=Object.freeze(["prefund_deposit_observation","partner_actual_capture_principal","partner_settlement_debit","partner_payout_disbursement"]),rt=Object.freeze(["none","active","fulfilled","released_unused","expired_unused","unknown"]),en=Object.freeze(["awaiting_trusted_observation","effect_unconfirmed","evidence_expired","outbound_result_unknown","provisional_effect","unresolved_reorganization","reconciliation_required"]),nn=Object.freeze(["none","planned","dispatch_claimed","awaiting_user_signature","relayer_submitted","broadcast_confirmed","settled_verified_effect"]),tn=Object.freeze(["none","active","fulfilled","released_unused","expired_unused"]),Oe=Object.freeze(["none","pending","partially_confirmed","confirmed","failed_no_effect"]),Ue=Object.freeze(["qualified","not_qualified","unknown"]),Pn=Object.freeze(["operation_pending","external_outcome_unknown","closure_not_confirmed","original_operation_not_observed"]),ot=Object.freeze(["none","planned","dispatch_claimed","awaiting_user_signature","relayer_submitted","broadcast_confirmed","unknown","settled_verified_effect"]),it=Object.freeze(["complete","incomplete"]),rn=Object.freeze(["open_unclosed_command","missing_original_observation","outbound_dispatch_in_doubt","commit_outcome_unknown","target_closure_unconfirmed","awaiting_user_signature","awaiting_trusted_observation"]),at=Object.freeze(["unauthenticated_session","authority_grant_expired_at_commit","source_quote_expired_at_commit","risk_cap_expired_at_commit","authority_grant_revoked","scope_binding_revoked","cross_audience_or_owner_forbidden","current_session_expired_or_revoked","current_read_authority_denied"]),st=Object.freeze(["invalid_uint256_or_schema","cas_context_revision_mismatch","cas_source_revision_mismatch","cas_budget_revision_mismatch","shared_prefund_cash_exhausted","app_service_allocation_exceeded","period_limit_exceeded","per_tx_limit_exceeded","shared_risk_cap_exceeded","reserve_floor_breached","native_gas_reserve_insufficient","source_effective_available_insufficient","unknown_hold_release_forbidden","command_input_digest_mismatch","producer_verification_failed","caller_valid_until_exceeds_grant","cash_application_exceeds_collected_or_principal","commercial_decision_fact_unavailable","commercial_decision_already_settled","commercial_reduction_exceeds_actual_capture_or_limit","commercial_reduction_net_not_conserved","PF_CAS_CONFLICT","original_input_conflict","source_or_authority_unavailable","verified_execution_plan_mismatch"]);var Qt="115792089237316195423570985008687907853269984665640564039457584007913129639935",Lo=(1n<<256n)-1n,Fo=/^(0|[1-9][0-9]{0,77})$/,zo=/^[A-Za-z0-9][A-Za-z0-9._:-]{1,126}[A-Za-z0-9]$/,Bo=/^[0-9a-f]{64}$/,Wo=/^sha256:([0-9a-f]{64})$/,Vo=/^(0x[0-9a-fA-F]{40}|NATIVE|FIAT:[A-Z]{3})$/,Ho=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,sn=Object.freeze({create_or_transition_source_hold:"/api/merchant/enterprise-funds/purchases/{purchaseRef}/intents/{economicIntentRef}/commands/{commandRef}/holds",record_prefund_or_partner_fact:"/api/merchant/enterprise-funds/purchases/{purchaseRef}/intents/{economicIntentRef}/commands/{commandRef}/partner-facts",settle_commercial_reduction:"/api/merchant/enterprise-funds/purchases/{purchaseRef}/intents/{economicIntentRef}/commands/{commandRef}/commercial-reductions"}),Yt="/api/merchant/enterprise-funds/purchases/{purchaseRef}/intents/{economicIntentRef}/commands/{commandRef}",Xt=Object.freeze({create_or_transition_source_hold:"source_holds",bind_or_transition_guarantee:"guarantee_links",record_prefund_or_partner_fact:"prefund_partner_facts",apply_qualified_cash:"cash_applications",dispatch_or_observe_execution_family:"execution_families",settle_commercial_reduction:"commercial_reductions"}),c=class extends _{wireCode="ENTERPRISE_WIRE_VALIDATION_ERROR";constructor(e){super(e),this.name="EnterpriseWireValidationError"}};function Go(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n>=55296&&n<=56319){let r=e+1<t.length?t.charCodeAt(e+1):0;if(r<56320||r>57343)return!0;e+=1}else if(n>=56320&&n<=57343)return!0}return!1}function z(t,e){if(typeof t!="string")throw new c(`${e} must be a string.`);if(Go(t))throw new c(`${e} contains an invalid lone UTF-16 surrogate code unit.`)}function E(t,e,n,r=[]){if(typeof t!="object"||t===null||Array.isArray(t))throw new c(`${e} must be a non-null plain JSON object.`);let o=Object.getPrototypeOf(t);if(o!==Object.prototype&&o!==null)throw new c(`${e} must be a plain JSON object.`);let a=t,s=new Set([...n,...r]);for(let d of Object.keys(a))if(!s.has(d))throw new c(`${e} contains unexpected property "${d}" (additionalProperties: false).`);for(let d of n)if(!(d in a)||a[d]===void 0)throw new c(`${e} is missing required property "${d}".`);return a}function y(t,e){if(z(t,e),t.length<3||t.length>128||!zo.test(t))throw new c(`${e} must match ScopedObjectRef (3..128 chars, ^[A-Za-z0-9][A-Za-z0-9._:-]{1,126}[A-Za-z0-9]$).`)}function ae(t,e){if(z(t,e),!Bo.test(t))throw new c(`${e} must be a bare 64-character lowercase hexadecimal SHA-256 digest.`)}function dt(t,e="wireInputDigest"){return ae(t,e),`sha256:${t}`}function Zt(t,e="coreInputDigest"){z(t,e);let n=Wo.exec(t);if(!n)throw new c(`${e} must be a single-prefixed "sha256:<64 lowercase hex>" digest.`);return n[1]}function x(t,e){if(typeof t!="string")throw new c(`${e} must be a UInt256 decimal string, received ${typeof t}.`);if(!Fo.test(t))throw new c(`${e} must be a canonical non-negative base-10 integer string without leading zeros.`);let n=BigInt(t);if(n<0n||n>Lo)throw new c(`${e} exceeds UInt256 range (0..${Qt}).`)}function Vt(t,e){if(x(t,e),t==="0")throw new c(`${e} must not be "0".`)}function $(t,e){Ye(t,e)}function se(t,e){if(z(t,e),!Sn(t))throw new c(`${e} must be a valid ISO-8601 date-time string with explicit timezone.`)}function on(t,e,n,r){if(typeof t!="number"||!Number.isSafeInteger(t)||t<n||t>r)throw new c(`${e} must be a safe integer in range ${String(n)}..${String(r)}.`)}function U(t,e,n){if(typeof t!="string"||!e.includes(t))throw new c(`${n} must be one of [${e.join(", ")}].`)}function Jo(t,e){let n=0,r=0;for(;n<t.length&&r<e.length;){let o=t.codePointAt(n),a=e.codePointAt(r);if(o!==a)return o-a;n+=o>65535?2:1,r+=a>65535?2:1}return t.length-e.length}function Ht(t,e){z(t,e);let n='"';for(let r=0;r<t.length;r+=1){let o=t.charCodeAt(r);o===34?n+='\\"':o===92?n+="\\\\":o===8?n+="\\b":o===9?n+="\\t":o===10?n+="\\n":o===12?n+="\\f":o===13?n+="\\r":o<=31?n+=`\\u00${o.toString(16).padStart(2,"0")}`:n+=t[r]}return n+='"',n}function an(t,e="canonicalValue"){if(t===null)return"null";if(typeof t=="boolean")return t?"true":"false";if(typeof t=="string")return Ht(t,e);if(typeof t=="number"){if(!Number.isSafeInteger(t))throw new c(`${e} must be a JS-safe integer number token without fraction or exponent.`);return Object.is(t,-0)?"0":t.toString(10)}if(Array.isArray(t))return`[${t.map((r,o)=>an(r,`${e}[${String(o)}]`)).join(",")}]`;if(typeof t=="object"){let n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw new c(`${e} must be a plain JSON object.`);let r=t,o=Object.keys(r);for(let s of o)if(z(s,`${e}.<key>`),r[s]===void 0)throw new c(`${e}.${s} must not be undefined in canonical JSON object.`);return o.sort(Jo),`{${o.map(s=>`${Ht(s,`${e}.<key>`)}:${an(r[s],`${e}.${s}`)}`).join(",")}}`}throw new c(`${e} has unsupported type "${typeof t}" for canonical JSON.`)}function vn(t,e="canonicalObject"){let n=an(t,e),r=new TextEncoder().encode(n),o=new Uint8Array(r.byteLength);return o.set(r),{canonicalJson:n,canonicalBytes:o}}function In(t,e){y(e,"configuredAppId");let n=E(t,"ownerScope",["targetRealm","organizationId"],["appId","audience","principalId"]);if(z(n.targetRealm,"ownerScope.targetRealm"),n.targetRealm.length<1||n.targetRealm.length>128||n.targetRealm.trim()!==n.targetRealm)throw new c("ownerScope.targetRealm must be a non-empty trimmed string of 1..128 characters.");if(z(n.organizationId,"ownerScope.organizationId"),!Ho.test(n.organizationId))throw new c("ownerScope.organizationId must be a valid UUID.");let r=`merchant_app:${e}`;if(n.appId!==void 0&&(z(n.appId,"ownerScope.appId"),n.appId!==e))throw new c(`ownerScope.appId "${n.appId}" does not match configured server appId "${e}".`);if(n.audience!==void 0&&n.audience!=="merchant_s2s")throw new c(`ownerScope.audience must be "merchant_s2s", received "${String(n.audience)}".`);if(n.principalId!==void 0&&(z(n.principalId,"ownerScope.principalId"),n.principalId!==r))throw new c(`ownerScope.principalId must be "${r}", received "${n.principalId}".`);return Object.freeze({targetRealm:n.targetRealm,organizationId:n.organizationId,appId:e,audience:"merchant_s2s",principalId:r})}function er(t){let e=E(t,"ownerScope",["targetRealm","organizationId","appId","audience","principalId"]);return y(e.appId,"ownerScope.appId"),In(e,e.appId)}function be(t,e,n){y(e,"path.purchaseRef"),y(n,"path.economicIntentRef");let r=[t.targetRealm,t.organizationId,t.appId,e,n];return`${Vn}${an(r,"scopeRefTuple")}`}function qe(t){let e=E(t,"path",["purchaseRef","economicIntentRef","commandRef"]);return y(e.purchaseRef,"path.purchaseRef"),y(e.economicIntentRef,"path.economicIntentRef"),y(e.commandRef,"path.commandRef"),Object.freeze({purchaseRef:e.purchaseRef,economicIntentRef:e.economicIntentRef,commandRef:e.commandRef})}function nr(t,e){let n=qe(e);if(wn(t))throw new c(`commandKind "${t}" is server-derived and has no public merchant POST route; the Engine creates it from chain observation or Partner-confirmed capture.`);let r=sn[t];if(!r)throw new c(`Unsupported commandKind "${String(t)}".`);return r.replace("{purchaseRef}",encodeURIComponent(n.purchaseRef)).replace("{economicIntentRef}",encodeURIComponent(n.economicIntentRef)).replace("{commandRef}",encodeURIComponent(n.commandRef))}function tr(t){let e=qe(t);return Yt.replace("{purchaseRef}",encodeURIComponent(e.purchaseRef)).replace("{economicIntentRef}",encodeURIComponent(e.economicIntentRef)).replace("{commandRef}",encodeURIComponent(e.commandRef))}function rr(t){y(t,"commandRef");let e=Ko("sha256").update(t,"utf8").digest("hex");return`${Hn}${e}`}function ve(t,e){let n=E(t,e,["assetKind","chainId","assetAddress","decimals"]);if(U(n.assetKind,Qn,`${e}.assetKind`),on(n.chainId,`${e}.chainId`,0,9007199254740991),z(n.assetAddress,`${e}.assetAddress`),!Vo.test(n.assetAddress))throw new c(`${e}.assetAddress must match ^(0x[0-9a-fA-F]{40}|NATIVE|FIAT:[A-Z]{3})$.`);return on(n.decimals,`${e}.decimals`,0,18),Object.freeze({assetKind:n.assetKind,chainId:n.chainId,assetAddress:n.assetAddress,decimals:n.decimals})}function Gt(t,e){let n=E(t,e,["chainId","protocolId","sourceAssetId","sourceDecimals","protectedResourceRef","positionDigest"]);if(on(n.chainId,`${e}.chainId`,1,9007199254740991),U(n.protocolId,Yn,`${e}.protocolId`),z(n.sourceAssetId,`${e}.sourceAssetId`),n.sourceAssetId.length<2||n.sourceAssetId.length>96)throw new c(`${e}.sourceAssetId must be 2..96 characters.`);if(on(n.sourceDecimals,`${e}.sourceDecimals`,0,18),z(n.protectedResourceRef,`${e}.protectedResourceRef`),n.protectedResourceRef.length<2||n.protectedResourceRef.length>128)throw new c(`${e}.protectedResourceRef must be 2..128 characters.`);return ae(n.positionDigest,`${e}.positionDigest`),Object.freeze({chainId:n.chainId,protocolId:n.protocolId,sourceAssetId:n.sourceAssetId,sourceDecimals:n.sourceDecimals,protectedResourceRef:n.protectedResourceRef,positionDigest:n.positionDigest})}function Pe(t,e){let n=E(t,e,["expectedContextRevision","expectedSourceRevision","expectedBudgetRevision"]);return $(n.expectedContextRevision,`${e}.expectedContextRevision`),$(n.expectedSourceRevision,`${e}.expectedSourceRevision`),$(n.expectedBudgetRevision,`${e}.expectedBudgetRevision`),Object.freeze({expectedContextRevision:n.expectedContextRevision,expectedSourceRevision:n.expectedSourceRevision,expectedBudgetRevision:n.expectedBudgetRevision})}function Jt(t,e){let n=E(t,e,["prefundAccountRef","riskCapRef","allocationRef","budgetEpoch","expectedAllocationRevision"]);return y(n.prefundAccountRef,`${e}.prefundAccountRef`),y(n.riskCapRef,`${e}.riskCapRef`),y(n.allocationRef,`${e}.allocationRef`),$(n.budgetEpoch,`${e}.budgetEpoch`),$(n.expectedAllocationRevision,`${e}.expectedAllocationRevision`),Object.freeze({prefundAccountRef:n.prefundAccountRef,riskCapRef:n.riskCapRef,allocationRef:n.allocationRef,budgetEpoch:n.budgetEpoch,expectedAllocationRevision:n.expectedAllocationRevision})}function ct(t,e){let n=E(t,e,["producerKind","providerAuthority","upstreamRecordRef","externalEffectRef","evidenceDigest"],["callerRequestedValidUntil"]);return U(n.producerKind,Xn,`${e}.producerKind`),y(n.providerAuthority,`${e}.providerAuthority`),y(n.upstreamRecordRef,`${e}.upstreamRecordRef`),y(n.externalEffectRef,`${e}.externalEffectRef`),ae(n.evidenceDigest,`${e}.evidenceDigest`),n.callerRequestedValidUntil!==void 0&&se(n.callerRequestedValidUntil,`${e}.callerRequestedValidUntil`),Object.freeze({producerKind:n.producerKind,providerAuthority:n.providerAuthority,upstreamRecordRef:n.upstreamRecordRef,externalEffectRef:n.externalEffectRef,evidenceDigest:n.evidenceDigest,...n.callerRequestedValidUntil===void 0?{}:{callerRequestedValidUntil:n.callerRequestedValidUntil}})}function ut(t,e="requestBody"){if(typeof t!="object"||t===null||Array.isArray(t))throw new c(`${e} must be a non-null plain object.`);let n=t;U(n.commandKind,_n,`${e}.commandKind`);let r;switch(n.inputDigest!==void 0&&(ae(n.inputDigest,`${e}.inputDigest`),r=n.inputDigest),n.commandKind){case"create_or_transition_source_hold":{let o=E(t,e,["commandKind","cas","sourceRoot","holdRef","targetHoldState","settlementAsset","heldUnitsRaw","heldCashRaw","scaleNumerator","scaleDenominator","slippageBufferBps","quoteExpiresAt","authorityGrantRef","scopeBindingRef","commandRef"],["inputDigest","producerVerification"]),a=Pe(o.cas,`${e}.cas`),s=Gt(o.sourceRoot,`${e}.sourceRoot`);y(o.holdRef,`${e}.holdRef`),U(o.targetHoldState,Zn,`${e}.targetHoldState`);let d=ve(o.settlementAsset,`${e}.settlementAsset`);if(x(o.heldUnitsRaw,`${e}.heldUnitsRaw`),x(o.heldCashRaw,`${e}.heldCashRaw`),x(o.scaleNumerator,`${e}.scaleNumerator`),Vt(o.scaleDenominator,`${e}.scaleDenominator`),on(o.slippageBufferBps,`${e}.slippageBufferBps`,0,1e4),se(o.quoteExpiresAt,`${e}.quoteExpiresAt`),y(o.authorityGrantRef,`${e}.authorityGrantRef`),y(o.scopeBindingRef,`${e}.scopeBindingRef`),y(o.commandRef,`${e}.commandRef`),et.includes(o.targetHoldState)&&o.producerVerification===void 0)throw new c(`${e}.producerVerification is required when targetHoldState is "${o.targetHoldState}".`);let l=o.producerVerification===void 0?void 0:ct(o.producerVerification,`${e}.producerVerification`),i=Object.freeze({commandKind:"create_or_transition_source_hold",cas:a,sourceRoot:s,holdRef:o.holdRef,targetHoldState:o.targetHoldState,settlementAsset:d,heldUnitsRaw:o.heldUnitsRaw,heldCashRaw:o.heldCashRaw,scaleNumerator:o.scaleNumerator,scaleDenominator:o.scaleDenominator,slippageBufferBps:o.slippageBufferBps,quoteExpiresAt:o.quoteExpiresAt,authorityGrantRef:o.authorityGrantRef,scopeBindingRef:o.scopeBindingRef,...l===void 0?{}:{producerVerification:l},commandRef:o.commandRef});return{commandKind:"create_or_transition_source_hold",suppliedWireDigest:r,canonicalRequestPayload:i,casTriple:ne([a.expectedContextRevision,a.expectedSourceRevision,a.expectedBudgetRevision]),expectedClosureTarget:Object.freeze({commandKind:"create_or_transition_source_hold",targetTable:"source_holds",targetRecordRef:o.holdRef})}}case"bind_or_transition_guarantee":{let o=E(t,e,["commandKind","cas","sharedPrefundGuard","guaranteeRef","commitmentRef","targetGuaranteeState","asset","guaranteedAmountRaw","authorityGrantRef","scopeBindingRef","producerVerification","commandRef"],["inputDigest"]),a=Pe(o.cas,`${e}.cas`),s=Jt(o.sharedPrefundGuard,`${e}.sharedPrefundGuard`);y(o.guaranteeRef,`${e}.guaranteeRef`),y(o.commitmentRef,`${e}.commitmentRef`),U(o.targetGuaranteeState,nt,`${e}.targetGuaranteeState`);let d=ve(o.asset,`${e}.asset`);x(o.guaranteedAmountRaw,`${e}.guaranteedAmountRaw`),y(o.authorityGrantRef,`${e}.authorityGrantRef`),y(o.scopeBindingRef,`${e}.scopeBindingRef`);let u=ct(o.producerVerification,`${e}.producerVerification`);y(o.commandRef,`${e}.commandRef`);let l=Object.freeze({commandKind:"bind_or_transition_guarantee",cas:a,sharedPrefundGuard:s,guaranteeRef:o.guaranteeRef,commitmentRef:o.commitmentRef,targetGuaranteeState:o.targetGuaranteeState,asset:d,guaranteedAmountRaw:o.guaranteedAmountRaw,authorityGrantRef:o.authorityGrantRef,scopeBindingRef:o.scopeBindingRef,producerVerification:u,commandRef:o.commandRef});return{commandKind:"bind_or_transition_guarantee",suppliedWireDigest:r,canonicalRequestPayload:l,casTriple:ne([a.expectedContextRevision,a.expectedSourceRevision,a.expectedBudgetRevision]),expectedClosureTarget:Object.freeze({commandKind:"bind_or_transition_guarantee",targetTable:"guarantee_links",targetRecordRef:o.guaranteeRef})}}case"record_prefund_or_partner_fact":{let o=E(t,e,["commandKind","cas","sharedPrefundGuard","factRef","factKind","producerVerification","commandRef"],["inputDigest"]),a=Pe(o.cas,`${e}.cas`),s=Jt(o.sharedPrefundGuard,`${e}.sharedPrefundGuard`);y(o.factRef,`${e}.factRef`),U(o.factKind,tt,`${e}.factKind`);let d=ct(o.producerVerification,`${e}.producerVerification`);if(o.factKind==="partner_actual_capture_principal"&&d.producerKind!=="partner_funding_capture")throw new c(`${e}.producerVerification.producerKind must be "partner_funding_capture" when factKind is "partner_actual_capture_principal".`);y(o.commandRef,`${e}.commandRef`);let u=Object.freeze({commandKind:"record_prefund_or_partner_fact",cas:a,sharedPrefundGuard:s,factRef:o.factRef,factKind:o.factKind,producerVerification:d,commandRef:o.commandRef});return{commandKind:"record_prefund_or_partner_fact",suppliedWireDigest:r,canonicalRequestPayload:u,casTriple:ne([a.expectedContextRevision,a.expectedSourceRevision,a.expectedBudgetRevision]),expectedClosureTarget:Object.freeze({commandKind:"record_prefund_or_partner_fact",targetTable:"prefund_partner_facts",targetRecordRef:o.factRef})}}case"apply_qualified_cash":{let o=E(t,e,["commandKind","cas","cashBasisRef","applicationRef","asset","applyToPrincipalAmountRaw","commandRef"],["inputDigest"]),a=Pe(o.cas,`${e}.cas`);y(o.cashBasisRef,`${e}.cashBasisRef`),y(o.applicationRef,`${e}.applicationRef`);let s=ve(o.asset,`${e}.asset`);x(o.applyToPrincipalAmountRaw,`${e}.applyToPrincipalAmountRaw`),y(o.commandRef,`${e}.commandRef`);let d=Object.freeze({commandKind:"apply_qualified_cash",cas:a,cashBasisRef:o.cashBasisRef,applicationRef:o.applicationRef,asset:s,applyToPrincipalAmountRaw:o.applyToPrincipalAmountRaw,commandRef:o.commandRef});return{commandKind:"apply_qualified_cash",suppliedWireDigest:r,canonicalRequestPayload:d,casTriple:ne([a.expectedContextRevision,a.expectedSourceRevision,a.expectedBudgetRevision]),expectedClosureTarget:Object.freeze({commandKind:"apply_qualified_cash",targetTable:"cash_applications",targetRecordRef:o.applicationRef})}}case"dispatch_or_observe_execution_family":{let o=E(t,e,["commandKind","cas","sourceRoot","holdRef","executionIntentRef","familyRef","exactUnitsRaw","exactCashRaw","commandRef"],["inputDigest"]),a=Pe(o.cas,`${e}.cas`),s=Gt(o.sourceRoot,`${e}.sourceRoot`);y(o.holdRef,`${e}.holdRef`),y(o.executionIntentRef,`${e}.executionIntentRef`),y(o.familyRef,`${e}.familyRef`),x(o.exactUnitsRaw,`${e}.exactUnitsRaw`),x(o.exactCashRaw,`${e}.exactCashRaw`),y(o.commandRef,`${e}.commandRef`);let d=Object.freeze({commandKind:"dispatch_or_observe_execution_family",cas:a,sourceRoot:s,holdRef:o.holdRef,executionIntentRef:o.executionIntentRef,familyRef:o.familyRef,exactUnitsRaw:o.exactUnitsRaw,exactCashRaw:o.exactCashRaw,commandRef:o.commandRef});return{commandKind:"dispatch_or_observe_execution_family",suppliedWireDigest:r,canonicalRequestPayload:d,casTriple:ne([a.expectedContextRevision,a.expectedSourceRevision,a.expectedBudgetRevision]),expectedClosureTarget:Object.freeze({commandKind:"dispatch_or_observe_execution_family",targetTable:"execution_families",targetRecordRef:o.familyRef})}}case"settle_commercial_reduction":{let o=E(t,e,["commandKind","cas","decisionRef","decisionDigest","reductionRef","cancelledAmountRaw","ruleVersion","authorityGrantRef","scopeBindingRef","commandRef"],["inputDigest","feeEffectRef"]),a=Pe(o.cas,`${e}.cas`);y(o.decisionRef,`${e}.decisionRef`),ae(o.decisionDigest,`${e}.decisionDigest`),y(o.commandRef,`${e}.commandRef`),y(o.reductionRef,`${e}.reductionRef`);let s=rr(o.commandRef);if(o.reductionRef!==s)throw new c(`${e}.reductionRef must equal "efcreduce_" + SHA256(commandRef) ("${s}").`);Vt(o.cancelledAmountRaw,`${e}.cancelledAmountRaw`),y(o.ruleVersion,`${e}.ruleVersion`),y(o.authorityGrantRef,`${e}.authorityGrantRef`),y(o.scopeBindingRef,`${e}.scopeBindingRef`);let d;o.feeEffectRef!==void 0&&(y(o.feeEffectRef,`${e}.feeEffectRef`),d=o.feeEffectRef);let u=Object.freeze({commandKind:"settle_commercial_reduction",cas:a,decisionRef:o.decisionRef,decisionDigest:o.decisionDigest,reductionRef:o.reductionRef,cancelledAmountRaw:o.cancelledAmountRaw,ruleVersion:o.ruleVersion,authorityGrantRef:o.authorityGrantRef,scopeBindingRef:o.scopeBindingRef,...d===void 0?{}:{feeEffectRef:d},commandRef:o.commandRef});return{commandKind:"settle_commercial_reduction",suppliedWireDigest:r,canonicalRequestPayload:u,casTriple:ne([a.expectedContextRevision,a.expectedSourceRevision,a.expectedBudgetRevision]),expectedClosureTarget:Object.freeze({commandKind:"settle_commercial_reduction",targetTable:"commercial_reductions",targetRecordRef:o.reductionRef})}}}}function $e(t){if(typeof t!="object"||t===null)throw new c("canonicalizeAndMapEnterpriseCommand requires an input object.");let e=er(t.ownerScope),n=qe(t.path),{commandKind:r,suppliedWireDigest:o,canonicalRequestPayload:a,casTriple:s,expectedClosureTarget:d}=ut(t.body,"body");if(wn(r))throw new c(`commandKind "${r}" is server-derived and has no public merchant POST route; the Engine creates it from chain observation or Partner-confirmed capture.`);let u=a.commandRef;if(u!==n.commandRef)throw new c(`body.commandRef "${u}" must equal path.commandRef "${n.commandRef}".`);let l=t.idempotencyKey??n.commandRef;if(y(l,"Idempotency-Key"),l!==n.commandRef)throw new c(`Idempotency-Key header "${l}" must equal path.commandRef "${n.commandRef}" and body.commandRef "${u}".`);let i=sn[r],p=Object.freeze({protocol:Ze,method:"POST",routeTemplate:i,path:n,ownerScope:e,idempotencyKey:n.commandRef,request:a}),{canonicalJson:g,canonicalBytes:v}=vn(p,"canonicalObject"),M=we(v),b=Zt(M);if(o!==void 0&&o!==b)throw new c(`body.inputDigest "${o}" does not match recomputed canonical digest "${b}".`);let V=be(e,n.purchaseRef,n.economicIntentRef),I=Object.freeze({...a,inputDigest:b}),q=Object.freeze({ownerScope:Object.freeze({audience:e.audience,principalId:e.principalId,appId:e.appId,organizationId:e.organizationId,targetRealm:e.targetRealm}),commandRef:n.commandRef,idempotencyKey:n.commandRef,kind:r,scopeRef:V,businessRef:n.purchaseRef,canonicalRequestBytes:v,inputDigest:M,casTriple:s});return Object.freeze({canonicalObject:p,canonicalJson:g,canonicalRequestBytes:v,wireInputDigest:b,coreInputDigest:M,sdkScopeRef:V,casTriple:s,expectedClosureTarget:d,routeTemplate:i,requestPath:nr(r,n),recoveryPath:tr(n),headers:Object.freeze({"Idempotency-Key":n.commandRef}),wireRequestBody:I,journalEnvelope:q})}function cn(t){if(we(t.canonicalRequestBytes)!==t.inputDigest)throw new c("Frozen envelope canonicalRequestBytes digest does not match envelope.inputDigest.");let n;try{let d=new TextDecoder("utf-8",{fatal:!0}).decode(t.canonicalRequestBytes);n=JSON.parse(d)}catch(d){throw new c(`Failed to decode frozen canonicalRequestBytes JSON: ${d instanceof Error?d.message:String(d)}`)}let r=E(n,"canonicalObject",["protocol","method","routeTemplate","path","ownerScope","idempotencyKey","request"]);if(r.protocol!==Ze)throw new c(`Frozen canonicalObject.protocol must be "${Ze}".`);if(r.method!=="POST")throw new c('Frozen canonicalObject.method must be "POST".');let o=er(r.ownerScope),a=qe(r.path);if(r.idempotencyKey!==a.commandRef)throw new c("Frozen canonicalObject.idempotencyKey does not match path.commandRef.");let s=$e({ownerScope:o,path:a,idempotencyKey:a.commandRef,body:r.request});if(typeof t.ownerScope!="object"||t.ownerScope===null||Array.isArray(t.ownerScope)||s.journalEnvelope.ownerScope.audience!==t.ownerScope.audience||s.journalEnvelope.ownerScope.principalId!==t.ownerScope.principalId||s.journalEnvelope.ownerScope.appId!==t.ownerScope.appId||s.journalEnvelope.ownerScope.organizationId!==t.ownerScope.organizationId||s.journalEnvelope.ownerScope.targetRealm!==t.ownerScope.targetRealm)throw new c("Frozen envelope.ownerScope does not match canonicalObject.ownerScope.");if(s.coreInputDigest!==t.inputDigest||s.sdkScopeRef!==t.scopeRef||s.journalEnvelope.businessRef!==t.businessRef||s.journalEnvelope.commandRef!==t.commandRef||s.journalEnvelope.idempotencyKey!==t.idempotencyKey||s.journalEnvelope.kind!==t.kind||s.casTriple[0]!==t.casTriple[0]||s.casTriple[1]!==t.casTriple[1]||s.casTriple[2]!==t.casTriple[2])throw new c("Frozen envelope metadata does not match re-canonicalized command object.");return s}function Ce(t,e,n){let r=E(t,n,["knowledgeState","state","unknownReason"]);if(r.knowledgeState==="known"){if(U(r.state,e,`${n}.state`),r.unknownReason!==null)throw new c(`${n}.unknownReason must be null when knowledgeState is "known".`);return Object.freeze({knowledgeState:"known",state:r.state,unknownReason:null})}if(r.knowledgeState==="unknown"){if(r.state!==null)throw new c(`${n}.state must be null when knowledgeState is "unknown".`);return U(r.unknownReason,en,`${n}.unknownReason`),Object.freeze({knowledgeState:"unknown",state:null,unknownReason:r.unknownReason})}throw new c(`${n}.knowledgeState must be "known" or "unknown".`)}function or(t,e="projection.businessProgress"){let n=E(t,e,["sourceExecution","guarantee","partnerCapture","partnerPayout"]),r=Ce(n.sourceExecution,nn,`${e}.sourceExecution`),o=Ce(n.guarantee,tn,`${e}.guarantee`),a=Ce(n.partnerCapture,Oe,`${e}.partnerCapture`),s=Ce(n.partnerPayout,Oe,`${e}.partnerPayout`);return Object.freeze({sourceExecution:r,guarantee:o,partnerCapture:a,partnerPayout:s})}function lt(t,e){if(!Array.isArray(t))throw new c(`${e} must be an array.`);return Object.freeze(t.map((n,r)=>Qo(n,`${e}[${r}]`)))}function Qo(t,e){let n=E(t,e,["operationRef","operationState"]);if(typeof n.operationRef!="string"||!/^op_[A-Za-z0-9_-]{32,96}$/.test(n.operationRef))throw new c(`${e}.operationRef must match ^op_[A-Za-z0-9_-]{32,96}$.`);return U(n.operationState,["pending","unknown","closed"],`${e}.operationState`),Object.freeze({operationRef:n.operationRef,operationState:n.operationState})}function J(t,e){let n=E(t,e,["knowledgeState","knownAmountRaw","unknownReason"]);if(n.knowledgeState==="known"){if(x(n.knownAmountRaw,`${e}.knownAmountRaw`),n.unknownReason!==null)throw new c(`${e}.unknownReason must be null when knowledgeState is "known".`);return Object.freeze({knowledgeState:"known",knownAmountRaw:n.knownAmountRaw,unknownReason:null})}if(n.knowledgeState==="unknown"){if(n.knownAmountRaw!==null)throw new c(`${e}.knownAmountRaw must be null when knowledgeState is "unknown".`);return U(n.unknownReason,Jn,`${e}.unknownReason`),Object.freeze({knowledgeState:"unknown",knownAmountRaw:null,unknownReason:n.unknownReason})}throw new c(`${e}.knowledgeState must be "known" or "unknown".`)}function dn(t,e){let n=E(t,e,["ownerPartitionHash","sessionFenceRef","authEpoch","projectionTicket","pendingPollRequired","auditIdentityRetentionRequired"]);if(ae(n.ownerPartitionHash,`${e}.ownerPartitionHash`),y(n.sessionFenceRef,`${e}.sessionFenceRef`),$(n.authEpoch,`${e}.authEpoch`),$(n.projectionTicket,`${e}.projectionTicket`),typeof n.pendingPollRequired!="boolean")throw new c(`${e}.pendingPollRequired must be a boolean.`);if(n.auditIdentityRetentionRequired!==!0)throw new c(`${e}.auditIdentityRetentionRequired must be true.`);return Object.freeze({ownerPartitionHash:n.ownerPartitionHash,sessionFenceRef:n.sessionFenceRef,authEpoch:n.authEpoch,projectionTicket:n.projectionTicket,pendingPollRequired:n.pendingPollRequired,auditIdentityRetentionRequired:!0})}function pt(t,e){let n=E(t,e,["commandKind","targetTable","targetRecordRef"]);U(n.commandKind,_n,`${e}.commandKind`),U(n.targetTable,Gn,`${e}.targetTable`),y(n.targetRecordRef,`${e}.targetRecordRef`);let r=Xt[n.commandKind];if(n.targetTable!==r)throw new c(`${e}.targetTable "${n.targetTable}" is invalid for commandKind "${n.commandKind}" (expected "${r}").`);return Object.freeze({commandKind:n.commandKind,targetTable:n.targetTable,targetRecordRef:n.targetRecordRef})}function Tn(t,e){let n=E(t,e,["commandRef","purchaseRef","economicIntentRef","inputDigest","commitConfirmationLevel","closedAt","resultContextRevision","closureTarget"]);if(y(n.commandRef,`${e}.commandRef`),y(n.purchaseRef,`${e}.purchaseRef`),y(n.economicIntentRef,`${e}.economicIntentRef`),ae(n.inputDigest,`${e}.inputDigest`),n.commitConfirmationLevel!=="outer_commit_driver_confirmed")throw new c(`${e}.commitConfirmationLevel must be "outer_commit_driver_confirmed".`);se(n.closedAt,`${e}.closedAt`),$(n.resultContextRevision,`${e}.resultContextRevision`);let r=pt(n.closureTarget,`${e}.closureTarget`);return Object.freeze({commandRef:n.commandRef,purchaseRef:n.purchaseRef,economicIntentRef:n.economicIntentRef,inputDigest:n.inputDigest,commitConfirmationLevel:"outer_commit_driver_confirmed",closedAt:n.closedAt,resultContextRevision:n.resultContextRevision,closureTarget:r})}function Ke(t,e="projection",n){let r=ir(t,e,n,"merchant_s2s");return Object.freeze({...r,audience:"merchant_s2s",operations:Object.freeze([])})}function An(t,e="projection",n){return ir(t,e,n,"partner_workspace")}function ir(t,e,n,r){let o=E(t,e,["audience","publicOrderRef","appId","environment","settlementAsset","authorizedOrderCeiling","principalEstablished","guaranteeState","effectiveGuaranteedAmount","partnerSettledFactAmount","appAvailableServiceAllocation","appActiveCommitments","budgetEpoch","allocationRevision","fulfillmentPermitted","cacheCoordination","projectionRevision","asOf","fulfillmentQualification","operations","businessProgress"]);if(o.audience!==r)throw new c(`${e}.audience must be "${r}", received "${String(o.audience)}".`);if(y(o.publicOrderRef,`${e}.publicOrderRef`),y(o.appId,`${e}.appId`),n!==void 0&&o.appId!==n)throw new c(`${e}.appId "${o.appId}" does not match expected appId "${n}".`);if(z(o.environment,`${e}.environment`),o.environment.length<1||o.environment.length>64||o.environment.trim()!==o.environment)throw new c(`${e}.environment must be a non-empty string of 1..64 characters.`);let a=ve(o.settlementAsset,`${e}.settlementAsset`);x(o.authorizedOrderCeiling,`${e}.authorizedOrderCeiling`),x(o.principalEstablished,`${e}.principalEstablished`),U(o.guaranteeState,rt,`${e}.guaranteeState`);let s=J(o.effectiveGuaranteedAmount,`${e}.effectiveGuaranteedAmount`);x(o.partnerSettledFactAmount,`${e}.partnerSettledFactAmount`);let d=J(o.appAvailableServiceAllocation,`${e}.appAvailableServiceAllocation`);if(x(o.appActiveCommitments,`${e}.appActiveCommitments`),$(o.budgetEpoch,`${e}.budgetEpoch`),$(o.allocationRevision,`${e}.allocationRevision`),typeof o.fulfillmentPermitted!="boolean")throw new c(`${e}.fulfillmentPermitted must be a boolean.`);let u=dn(o.cacheCoordination,`${e}.cacheCoordination`);if($(o.projectionRevision,`${e}.projectionRevision`),se(o.asOf,`${e}.asOf`),U(o.fulfillmentQualification,Ue,`${e}.fulfillmentQualification`),(o.fulfillmentQualification==="unknown"||o.fulfillmentQualification==="not_qualified")&&o.fulfillmentPermitted!==!1)throw new c(`${e}.fulfillmentPermitted must be false when fulfillmentQualification is "${o.fulfillmentQualification}".`);if(r==="merchant_s2s"&&(!Array.isArray(o.operations)||o.operations.length!==0))throw new c(`${e}.operations must be an empty array for merchant_s2s audience.`);let l=r==="merchant_s2s"?Object.freeze([]):lt(o.operations,`${e}.operations`),i=or(o.businessProgress,`${e}.businessProgress`),p=i.guarantee.knowledgeState==="known"?i.guarantee.state:"unknown";if(o.guaranteeState!==p)throw new c(`${e}.guaranteeState "${o.guaranteeState}" must match ${e}.businessProgress.guarantee ("${p}").`);return Object.freeze({audience:r,publicOrderRef:o.publicOrderRef,appId:o.appId,environment:o.environment,settlementAsset:a,authorizedOrderCeiling:o.authorizedOrderCeiling,principalEstablished:o.principalEstablished,guaranteeState:o.guaranteeState,effectiveGuaranteedAmount:s,partnerSettledFactAmount:o.partnerSettledFactAmount,appAvailableServiceAllocation:d,appActiveCommitments:o.appActiveCommitments,budgetEpoch:o.budgetEpoch,allocationRevision:o.allocationRevision,fulfillmentPermitted:o.fulfillmentPermitted,cacheCoordination:u,projectionRevision:o.projectionRevision,asOf:o.asOf,fulfillmentQualification:o.fulfillmentQualification,operations:l,businessProgress:i})}function ar(t,e="projection.commercialReduction.collectedFeeEffect"){if(t===null)return null;let n=E(t,e,["feeEffectRef","collectedFeeRaw","feeEntitlementCumulativeRaw","feeEntitlementIncrementRaw"]);y(n.feeEffectRef,`${e}.feeEffectRef`);let r=(o,a)=>o===null?null:(x(o,`${e}.${a}`),o);return Object.freeze({feeEffectRef:n.feeEffectRef,collectedFeeRaw:r(n.collectedFeeRaw,"collectedFeeRaw"),feeEntitlementCumulativeRaw:r(n.feeEntitlementCumulativeRaw,"feeEntitlementCumulativeRaw"),feeEntitlementIncrementRaw:r(n.feeEntitlementIncrementRaw,"feeEntitlementIncrementRaw")})}function sr(t,e="projection.commercialReduction"){let n=E(t,e,["reductionRef","decisionRef","decisionBusinessRef","decisionDigest","decisionRuleVersion","decisionValidUntil","cancelledAmountRaw","cumulativeCancelledAmountRaw","actualCaptureBasisRaw","commercialPrincipalNetRaw","principalRefundEntitlementRaw","reverseReapplyCoverage","settledAt","collectedFeeEffect"]);y(n.reductionRef,`${e}.reductionRef`),y(n.decisionRef,`${e}.decisionRef`),y(n.decisionBusinessRef,`${e}.decisionBusinessRef`),ae(n.decisionDigest,`${e}.decisionDigest`),y(n.decisionRuleVersion,`${e}.decisionRuleVersion`),se(n.decisionValidUntil,`${e}.decisionValidUntil`),x(n.cancelledAmountRaw,`${e}.cancelledAmountRaw`),x(n.cumulativeCancelledAmountRaw,`${e}.cumulativeCancelledAmountRaw`),x(n.actualCaptureBasisRaw,`${e}.actualCaptureBasisRaw`),x(n.commercialPrincipalNetRaw,`${e}.commercialPrincipalNetRaw`),x(n.principalRefundEntitlementRaw,`${e}.principalRefundEntitlementRaw`),U(n.reverseReapplyCoverage,it,`${e}.reverseReapplyCoverage`),se(n.settledAt,`${e}.settledAt`);let r=ar(n.collectedFeeEffect,`${e}.collectedFeeEffect`);return Object.freeze({reductionRef:n.reductionRef,decisionRef:n.decisionRef,decisionBusinessRef:n.decisionBusinessRef,decisionDigest:n.decisionDigest,decisionRuleVersion:n.decisionRuleVersion,decisionValidUntil:n.decisionValidUntil,cancelledAmountRaw:n.cancelledAmountRaw,cumulativeCancelledAmountRaw:n.cumulativeCancelledAmountRaw,actualCaptureBasisRaw:n.actualCaptureBasisRaw,commercialPrincipalNetRaw:n.commercialPrincipalNetRaw,principalRefundEntitlementRaw:n.principalRefundEntitlementRaw,reverseReapplyCoverage:n.reverseReapplyCoverage,settledAt:n.settledAt,collectedFeeEffect:r})}function mt(t,e="projection",n){let r=E(t,e,["audience","publicOrderRef","appId","environment","settlementAsset","projectionRevision","cacheCoordination","commercialReduction","asOf"]);if(r.audience!=="merchant_s2s")throw new c(`${e}.audience must be "merchant_s2s", received "${String(r.audience)}".`);if(y(r.publicOrderRef,`${e}.publicOrderRef`),y(r.appId,`${e}.appId`),n!==void 0&&r.appId!==n)throw new c(`${e}.appId "${r.appId}" does not match expected appId "${n}".`);if(z(r.environment,`${e}.environment`),r.environment.length<1||r.environment.length>64||r.environment.trim()!==r.environment)throw new c(`${e}.environment must be a non-empty string of 1..64 characters.`);let o=ve(r.settlementAsset,`${e}.settlementAsset`);$(r.projectionRevision,`${e}.projectionRevision`);let a=dn(r.cacheCoordination,`${e}.cacheCoordination`);if(a.pendingPollRequired!==!0)throw new c(`${e}.cacheCoordination.pendingPollRequired must be true for a B2 merchant_s2s projection.`);let s=sr(r.commercialReduction,`${e}.commercialReduction`);return se(r.asOf,`${e}.asOf`),Object.freeze({audience:"merchant_s2s",publicOrderRef:r.publicOrderRef,appId:r.appId,environment:r.environment,settlementAsset:o,projectionRevision:r.projectionRevision,cacheCoordination:a,commercialReduction:s,asOf:r.asOf})}function cr(t,e){let n=E(t,"MerchantCommandEnvelopeResponse",["outcomeStatus","receipt","projection","pendingPollRequired","auditIdentityRetentionRequired"]);if(n.outcomeStatus!=="applied"&&n.outcomeStatus!=="replayed_identical")throw new c('MerchantCommandEnvelopeResponse.outcomeStatus must be "applied" or "replayed_identical".');if(n.pendingPollRequired!==!1)throw new c("MerchantCommandEnvelopeResponse.pendingPollRequired must be false.");if(n.auditIdentityRetentionRequired!==!0)throw new c("MerchantCommandEnvelopeResponse.auditIdentityRetentionRequired must be true.");let r=Tn(n.receipt,"MerchantCommandEnvelopeResponse.receipt"),o=Ke(n.projection,"MerchantCommandEnvelopeResponse.projection",e);return Object.freeze({outcomeStatus:n.outcomeStatus,receipt:r,projection:o,pendingPollRequired:!1,auditIdentityRetentionRequired:!0})}function dr(t,e){let n=E(t,"MerchantCommandRecoveryResponse",["outcomeStatus","receipt","projection","pendingPollRequired","auditIdentityRetentionRequired"]);if(n.outcomeStatus!=="closed_recovered")throw new c('MerchantCommandRecoveryResponse.outcomeStatus must be "closed_recovered".');if(n.pendingPollRequired!==!1)throw new c("MerchantCommandRecoveryResponse.pendingPollRequired must be false.");if(n.auditIdentityRetentionRequired!==!0)throw new c("MerchantCommandRecoveryResponse.auditIdentityRetentionRequired must be true.");let r=Tn(n.receipt,"MerchantCommandRecoveryResponse.receipt"),o=Ke(n.projection,"MerchantCommandRecoveryResponse.projection",e);return Object.freeze({outcomeStatus:"closed_recovered",receipt:r,projection:o,pendingPollRequired:!1,auditIdentityRetentionRequired:!0})}function ur(t,e){let n=E(t,"MerchantCommercialReductionEnvelopeResponse",["outcomeStatus","receipt","projection","pendingPollRequired","auditIdentityRetentionRequired"]);if(n.outcomeStatus!=="applied"&&n.outcomeStatus!=="replayed_identical")throw new c('MerchantCommercialReductionEnvelopeResponse.outcomeStatus must be "applied" or "replayed_identical".');if(n.pendingPollRequired!==!1)throw new c("MerchantCommercialReductionEnvelopeResponse.pendingPollRequired must be false.");if(n.auditIdentityRetentionRequired!==!0)throw new c("MerchantCommercialReductionEnvelopeResponse.auditIdentityRetentionRequired must be true.");let r=Tn(n.receipt,"MerchantCommercialReductionEnvelopeResponse.receipt"),o=mt(n.projection,"MerchantCommercialReductionEnvelopeResponse.projection",e);return Object.freeze({outcomeStatus:n.outcomeStatus,receipt:r,projection:o,pendingPollRequired:!1,auditIdentityRetentionRequired:!0})}function lr(t,e){let n=E(t,"MerchantCommercialReductionRecoveryResponse",["outcomeStatus","receipt","projection","pendingPollRequired","auditIdentityRetentionRequired"]);if(n.outcomeStatus!=="closed_recovered")throw new c('MerchantCommercialReductionRecoveryResponse.outcomeStatus must be "closed_recovered".');if(n.pendingPollRequired!==!1)throw new c("MerchantCommercialReductionRecoveryResponse.pendingPollRequired must be false.");if(n.auditIdentityRetentionRequired!==!0)throw new c("MerchantCommercialReductionRecoveryResponse.auditIdentityRetentionRequired must be true.");let r=Tn(n.receipt,"MerchantCommercialReductionRecoveryResponse.receipt"),o=mt(n.projection,"MerchantCommercialReductionRecoveryResponse.projection",e);return Object.freeze({outcomeStatus:"closed_recovered",receipt:r,projection:o,pendingPollRequired:!1,auditIdentityRetentionRequired:!0})}function pr(t,e){let n=E(t,"CommandUnknownRecoveryResponse",["commandRef","inputDigest","outcomeStatus","unknownReason","receipt","pendingPollRequired","auditIdentityRetentionRequired","retryAction","projection"]);if(y(n.commandRef,"CommandUnknownRecoveryResponse.commandRef"),ae(n.inputDigest,"CommandUnknownRecoveryResponse.inputDigest"),n.outcomeStatus!=="unknown")throw new c('CommandUnknownRecoveryResponse.outcomeStatus must be "unknown".');if(U(n.unknownReason,rn,"CommandUnknownRecoveryResponse.unknownReason"),n.receipt!==null)throw new c("CommandUnknownRecoveryResponse.receipt must be null.");if(n.pendingPollRequired!==!0)throw new c("CommandUnknownRecoveryResponse.pendingPollRequired must be true.");if(n.auditIdentityRetentionRequired!==!0)throw new c("CommandUnknownRecoveryResponse.auditIdentityRetentionRequired must be true.");if(n.retryAction!=="retain_journal_and_poll_readonly_recovery")throw new c('CommandUnknownRecoveryResponse.retryAction must be "retain_journal_and_poll_readonly_recovery".');let r=n.projection===null?null:Ke(n.projection,"CommandUnknownRecoveryResponse.projection",e);return Object.freeze({commandRef:n.commandRef,inputDigest:n.inputDigest,outcomeStatus:"unknown",unknownReason:n.unknownReason,receipt:null,pendingPollRequired:!0,auditIdentityRetentionRequired:!0,retryAction:"retain_journal_and_poll_readonly_recovery",projection:r})}function On(t){let e=E(t,"AuthRevokedErrorResponse",["errorCode","message","outcomeDisclosure","protectedCacheMustClear","localContextAnchorRequired","auditIdentityRetentionRequired"]);if(U(e.errorCode,at,"AuthRevokedErrorResponse.errorCode"),z(e.message,"AuthRevokedErrorResponse.message"),e.message.length>512)throw new c("AuthRevokedErrorResponse.message exceeds 512 chars.");if(e.outcomeDisclosure!=="undisclosed")throw new c('AuthRevokedErrorResponse.outcomeDisclosure must be "undisclosed".');if(e.protectedCacheMustClear!==!0)throw new c("AuthRevokedErrorResponse.protectedCacheMustClear must be true.");if(e.localContextAnchorRequired!==!0)throw new c("AuthRevokedErrorResponse.localContextAnchorRequired must be true.");if(e.auditIdentityRetentionRequired!==!0)throw new c("AuthRevokedErrorResponse.auditIdentityRetentionRequired must be true.");return Object.freeze({errorCode:e.errorCode,message:e.message,outcomeDisclosure:"undisclosed",protectedCacheMustClear:!0,localContextAnchorRequired:!0,auditIdentityRetentionRequired:!0})}function mr(t){let e=E(t,"DeterministicCommandErrorResponse",["errorCode","message","preservePendingCommandJournal"],["currentContextRevision"]);if(U(e.errorCode,st,"DeterministicCommandErrorResponse.errorCode"),z(e.message,"DeterministicCommandErrorResponse.message"),e.currentContextRevision!==void 0&&$(e.currentContextRevision,"DeterministicCommandErrorResponse.currentContextRevision"),e.preservePendingCommandJournal!==!0)throw new c("DeterministicCommandErrorResponse.preservePendingCommandJournal must be true.");return Object.freeze({errorCode:e.errorCode,message:e.message,...e.currentContextRevision===void 0?{}:{currentContextRevision:e.currentContextRevision},preservePendingCommandJournal:!0})}function fr(t){let e=E(t,"InfrastructureUnavailableResponse",["errorCode","message","outcomeDisclosure","preservePendingCommandJournal","retryAction"]);if(e.errorCode!=="PF_SERVICE_UNAVAILABLE")throw new c('InfrastructureUnavailableResponse.errorCode must be "PF_SERVICE_UNAVAILABLE".');if(z(e.message,"InfrastructureUnavailableResponse.message"),e.message.length>512)throw new c("InfrastructureUnavailableResponse.message exceeds 512 chars.");if(e.outcomeDisclosure!=="unknown")throw new c('InfrastructureUnavailableResponse.outcomeDisclosure must be "unknown".');if(e.preservePendingCommandJournal!==!0)throw new c("InfrastructureUnavailableResponse.preservePendingCommandJournal must be true.");if(e.retryAction!=="retain_journal_and_poll_readonly_recovery")throw new c('InfrastructureUnavailableResponse.retryAction must be "retain_journal_and_poll_readonly_recovery".');return Object.freeze({errorCode:"PF_SERVICE_UNAVAILABLE",message:e.message,outcomeDisclosure:"unknown",preservePendingCommandJournal:!0,retryAction:"retain_journal_and_poll_readonly_recovery"})}function bn(t){let e=cn(t.envelope),n=e.canonicalObject.ownerScope.appId,r,o=!1;if(t.rawBodyText.trim().length>0)try{r=JSON.parse(t.rawBodyText),o=!0}catch{o=!1}if(t.httpStatus===401||t.httpStatus===403){let a={malformedBody:!0};if(o)try{a=On(r)}catch{a={malformedBody:!0}}return{httpStatus:t.httpStatus,observation:{kind:"corrupted_or_unclosed",reason:`http_${String(t.httpStatus)}_auth_denied`},receipt:null,projection:null,authRevokedError:a}}if(t.httpStatus===202){if(!o)return{httpStatus:202,observation:{kind:"accepted_pending",httpStatus:202},wireOutcomeStatus:"unknown",receipt:null,projection:null};try{let a=pr(r,n);return a.commandRef!==t.envelope.commandRef||dt(a.inputDigest)!==t.envelope.inputDigest?{httpStatus:202,observation:{kind:"corrupted_or_unclosed",reason:"http_202_envelope_identity_mismatch"},wireOutcomeStatus:"unknown",receipt:null,projection:null}:{httpStatus:202,observation:{kind:"accepted_pending",httpStatus:202},wireOutcomeStatus:"unknown",receipt:null,projection:a.projection}}catch{return{httpStatus:202,observation:{kind:"accepted_pending",httpStatus:202},wireOutcomeStatus:"unknown",receipt:null,projection:null}}}if(t.httpStatus===200){if(!o)return{httpStatus:200,observation:{kind:"corrupted_or_unclosed",reason:"http_200_invalid_json"},receipt:null,projection:null};try{let a=t.envelope.kind==="settle_commercial_reduction",s=a?t.method==="POST"?ur(r,n):lr(r,n):t.method==="POST"?cr(r,n):dr(r,n),{receipt:d}=s,u=a?null:s.projection,l=a?s.projection:void 0,i=dt(d.inputDigest,"receipt.inputDigest"),p=be(e.canonicalObject.ownerScope,d.purchaseRef,d.economicIntentRef),g=e.expectedClosureTarget;return d.commandRef!==t.envelope.commandRef||d.purchaseRef!==e.canonicalObject.path.purchaseRef||d.economicIntentRef!==e.canonicalObject.path.economicIntentRef||i!==t.envelope.inputDigest||p!==t.envelope.scopeRef||d.closureTarget.commandKind!==t.envelope.kind||d.closureTarget.targetTable!==g.targetTable||d.closureTarget.targetRecordRef!==g.targetRecordRef?{httpStatus:200,observation:{kind:"corrupted_or_unclosed",reason:"http_200_receipt_envelope_binding_mismatch"},receipt:null,projection:null}:l!==void 0&&l.commercialReduction.reductionRef!==g.targetRecordRef?{httpStatus:200,observation:{kind:"corrupted_or_unclosed",reason:"http_200_commercial_reduction_projection_binding_mismatch"},receipt:null,projection:null}:{httpStatus:200,observation:{kind:"completed",commandRef:d.commandRef,idempotencyKey:d.commandRef,commandKind:d.closureTarget.commandKind,scopeRef:p,businessRef:d.purchaseRef,inputDigest:i,originalCasTriple:t.envelope.casTriple,completionRef:`${d.closureTarget.targetTable}:${d.closureTarget.targetRecordRef}@${d.resultContextRevision}`,observedAtIso:d.closedAt},wireOutcomeStatus:s.outcomeStatus,receipt:d,projection:u,...l===void 0?{}:{commercialReductionProjection:l}}}catch{return{httpStatus:200,observation:{kind:"corrupted_or_unclosed",reason:"http_200_schema_validation_failed"},receipt:null,projection:null}}}if(t.httpStatus===400||t.httpStatus===409||t.httpStatus===422){let a;if(o)try{a=mr(r)}catch{a=void 0}return{httpStatus:t.httpStatus,observation:{kind:"corrupted_or_unclosed",reason:`http_${String(t.httpStatus)}_deterministic_error`},receipt:null,projection:null,...a===void 0?{}:{deterministicError:a}}}if(t.httpStatus===404)return{httpStatus:404,observation:{kind:"missing_original",httpStatus:404},receipt:null,projection:null};if(t.httpStatus===503&&o)try{fr(r)}catch{}return{httpStatus:t.httpStatus,observation:{kind:"corrupted_or_unclosed",reason:`http_${String(t.httpStatus)}_unavailable_or_unexpected`},receipt:null,projection:null}}async function Rr(t,e,n,r){if(t.signal?.aborted)throw new Error("Enterprise Funds request aborted before send");let o=new AbortController,a,s=()=>o.abort();t.signal&&t.signal.addEventListener("abort",s,{once:!0}),t.timeoutMs!==void 0&&(a=setTimeout(()=>o.abort(),t.timeoutMs));try{let d=await t.transport(e,{...n,redirect:"manual",signal:o.signal}),u=d.status;if(r!==void 0&&r(u),u>=300&&u<400||d.type==="opaqueredirect")return{status:u>=300&&u<400?u:307,rawText:"",bodyStreamFailed:!1};let l="",i=!1;try{l=await d.text()}catch{l="",i=!0}return{status:u,rawText:l,bodyStreamFailed:i}}finally{a!==void 0&&clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",s)}}function ft(t,e="caller"){if(typeof t!="object"||t===null||Array.isArray(t))throw new _(`${e} context must be a non-null object.`);let n=t;if(typeof n.contextGeneration!="number"||!Number.isSafeInteger(n.contextGeneration)||n.contextGeneration<1)throw new _(`${e}.contextGeneration must be a positive safe integer (>= 1).`);if(typeof n.sessionId!="string"||n.sessionId.trim().length===0)throw new _(`${e}.sessionId must be a non-empty string.`);if(typeof n.authEpoch!="number"||!Number.isSafeInteger(n.authEpoch)||n.authEpoch<0)throw new _(`${e}.authEpoch must be a non-negative safe integer.`);if(typeof n.ownerScope!="object"||n.ownerScope===null||Array.isArray(n.ownerScope))throw new _(`${e}.ownerScope must be a non-null object.`);if(typeof n.canRead!="boolean")throw new _(`${e}.canRead must be a boolean.`);if(typeof n.canExecute!="boolean")throw new _(`${e}.canExecute must be a boolean.`);let r=n.ownerScope;return Object.freeze({ownerScope:Object.freeze({...r}),sessionId:n.sessionId,authEpoch:n.authEpoch,canRead:n.canRead,canExecute:n.canExecute,contextGeneration:n.contextGeneration})}function ke(t,e,n){let r=ft(t,"caller"),o=r.ownerScope;if(o.audience!=="merchant_s2s"||o.principalId!==e.principalId||o.appId!==e.appId||o.organizationId!==e.organizationId||o.targetRealm!==e.targetRealm)throw new ee("caller.ownerScope does not match the client-bound merchant_s2s ownerScope partition.");if(!r.canRead)throw new ee("caller.canRead must be true to access Enterprise Funds journal or recovery.");if(n&&!r.canExecute)throw new ee("caller.canExecute must be true to execute commands.");return Object.freeze({ownerScope:Object.freeze({audience:e.audience,principalId:e.principalId,appId:e.appId,organizationId:e.organizationId,targetRealm:e.targetRealm,...o.opaqueIdentityRef===void 0?{}:{opaqueIdentityRef:o.opaqueIdentityRef}}),sessionId:r.sessionId,authEpoch:r.authEpoch,canRead:r.canRead,canExecute:r.canExecute,contextGeneration:r.contextGeneration})}function un(t){let e=t.ownerScope;return JSON.stringify([e.audience??null,e.principalId??null,e.appId??null,e.organizationId??null,e.targetRealm??null,t.sessionId,t.authEpoch,t.canRead,t.canExecute])}function Yo(t){let e=t.projectionFenceResult!==void 0&&!t.projectionFenceResult.applied?t.projectionFenceResult.reason:"context_mismatch",n=t.projectionFenceResult!==void 0?t.projectionFenceResult.watermarkTicket:0;return Object.freeze({resultKind:"stale_or_denied",staleOrDenied:!0,snapshot:null,sendInvoked:t.sendInvoked,...t.httpStatus===void 0?{}:{httpStatus:t.httpStatus},receipt:null,originalCasTriple:null,projection:null,projectionFenceResult:Object.freeze({applied:!1,reason:e,projection:null,watermarkTicket:n})})}function Xo(t){let e=t.projectionFenceResult!==void 0&&!t.projectionFenceResult.applied?t.projectionFenceResult.reason:"context_mismatch",n=t.projectionFenceResult!==void 0?t.projectionFenceResult.watermarkTicket:0;return Object.freeze({resultKind:"stale_or_denied",staleOrDenied:!0,snapshot:null,lookupInvoked:t.lookupInvoked,...t.httpStatus===void 0?{}:{httpStatus:t.httpStatus},receipt:null,originalCasTriple:null,projection:null,projectionFenceResult:Object.freeze({applied:!1,reason:e,projection:null,watermarkTicket:n})})}function yr(t){if(typeof t!="object"||t===null)throw new c("EnterpriseFunds client configuration is required.");if(typeof t.getCallerContext!="function")throw new c("getCallerContext must be a function returning EnterpriseHostCallerSessionContext.");let e=In(t.ownerScope,t.appId),n=new En({store:t.store}),r=new Map,o=new Map,a=null,s=null,d=null,u=null,l=1,i=0,p=()=>{for(let f of r.values())f.fence.switchContext({ownerScope:e,sessionId:"__invalidated_context__",authEpoch:f.lastSyncedAuthEpoch}),f.lastAppliedCommercialReductionTicket=0,f.lastSyncedOwnerAudience=e.audience,f.lastSyncedPrincipalId=e.principalId,f.lastSyncedAppId=e.appId,f.lastSyncedOrganizationId=e.organizationId,f.lastSyncedTargetRealm=e.targetRealm,f.lastSyncedSessionId="__invalidated_context__"},g=(f,m,R)=>{let h=f.lastSyncedOwnerAudience!==m.ownerScope.audience||f.lastSyncedPrincipalId!==m.ownerScope.principalId||f.lastSyncedAppId!==m.ownerScope.appId||f.lastSyncedOrganizationId!==m.ownerScope.organizationId||f.lastSyncedTargetRealm!==m.ownerScope.targetRealm||f.lastSyncedSessionId!==m.sessionId||f.lastSyncedAuthEpoch!==m.authEpoch;if((R||h||!m.canRead)&&(f.fence.switchContext({ownerScope:m.ownerScope,sessionId:m.sessionId,authEpoch:m.authEpoch}),f.lastAppliedCommercialReductionTicket=0,f.lastSyncedOwnerAudience=m.ownerScope.audience,f.lastSyncedPrincipalId=m.ownerScope.principalId,f.lastSyncedAppId=m.ownerScope.appId,f.lastSyncedOrganizationId=m.ownerScope.organizationId,f.lastSyncedTargetRealm=m.ownerScope.targetRealm,f.lastSyncedSessionId=m.sessionId,f.lastSyncedAuthEpoch=m.authEpoch),f.deniedExecutionSession!==null){let k=m.ownerScope.audience==="merchant_s2s"&&m.ownerScope.principalId===e.principalId&&m.ownerScope.appId===e.appId&&m.ownerScope.organizationId===e.organizationId&&m.ownerScope.targetRealm===e.targetRealm,A=m.sessionId!==f.deniedExecutionSession.sessionId||m.authEpoch>f.deniedExecutionSession.authEpoch;k&&m.canRead&&m.canExecute&&A&&(f.deniedExecutionSession=null)}},v=()=>{let f;try{f=t.getCallerContext()}catch(K){return i+=1,a=null,u!==null&&(l=Math.max(l,u+1)),p(),{effectiveCaller:null,generation:i,error:K}}let m;try{m=ft(f,"caller")}catch(K){return i+=1,a=null,u!==null&&(l=Math.max(l,u+1)),p(),{effectiveCaller:null,generation:i,error:K}}let R=m.contextGeneration,h=un(m);if(s===null){if(u!==null&&(R<u||R<l))return i+=1,a=null,l=Math.max(l,u+1),p(),{effectiveCaller:null,generation:i,error:new _(`caller.contextGeneration (${String(R)}) regressed below active generation (${String(Math.max(u,l))}).`)};if(s=R,d=h,u=Math.max(u??R,R),l=Math.max(l,R),i===0&&(i=1),a===null)for(let K of r.values())g(K,m,!1);return{effectiveCaller:a??m,generation:i,error:null}}if(!(R!==s||h!==d))return R<l&&a===null?{effectiveCaller:null,generation:i,error:new _(`caller.contextGeneration (${String(R)}) must advance to at least ${String(l)} after a context transition.`)}:{effectiveCaller:a??m,generation:i,error:null};let A=Math.max(u??s,s),S=R>s&&R>=A&&R>=l;if(s=R,d=h,a=null,i+=1,!S)return u=Math.max(A,R),l=Math.max(l,u+1),p(),{effectiveCaller:null,generation:i,error:new _(`caller.contextGeneration (${String(R)}) regressed or failed to advance on caller context transition (minimum required: ${String(l)}).`)};u=R,l=R;for(let K of r.values())g(K,m,!0);return{effectiveCaller:m,generation:i,error:null}},M=(f,m,R)=>{let h;try{h=ke(f,e,m)}catch(N){throw N instanceof _&&(i+=1,a=null,u!==null&&(l=Math.max(l,u)),p()),N}let k=a??R.effectiveCaller,A=k!==null?un(k):d,S=un(h),K=u!==null&&(h.contextGeneration<u||h.contextGeneration<l),O=u!==null&&h.contextGeneration===u&&(R.error!==null||S!==A);if(K||O)throw i+=1,a=null,u!==null&&(l=Math.max(l,u)),p(),new _(`caller.contextGeneration (${String(h.contextGeneration)}) regressed below or failed to advance past active generation (${String(Math.max(u??1,l))}).`);return(u===null||h.contextGeneration>u)&&(u=h.contextGeneration,l=Math.max(l,h.contextGeneration)),h},b=(f,m)=>{let R=r.get(f);if(!R){let h=a??m;R={fence:new Cn({ownerScope:h.ownerScope,sessionId:h.sessionId,authEpoch:h.authEpoch}),lastAppliedCommercialReductionTicket:0,lastSyncedOwnerAudience:h.ownerScope.audience,lastSyncedPrincipalId:h.ownerScope.principalId,lastSyncedAppId:h.ownerScope.appId,lastSyncedOrganizationId:h.ownerScope.organizationId,lastSyncedTargetRealm:h.ownerScope.targetRealm,lastSyncedSessionId:h.sessionId,lastSyncedAuthEpoch:h.authEpoch,deniedExecutionSession:null},r.set(f,R)}return g(R,a??m,!1),R},V=(f,m,R,h)=>{if(R.error!==null||R.effectiveCaller===null||R.generation!==m)return!0;try{let k=ke(R.effectiveCaller,e,h);return k.sessionId!==f.sessionId||k.authEpoch!==f.authEpoch||k.contextGeneration!==f.contextGeneration}catch{return!0}},I=(f,m,R,h,k)=>{if(R===401||R===403)return{projection:null,fenceResult:f.fence.applyResponse(m,{status:R,errorBody:k})};if(h!==void 0&&h.commercialReductionProjection!==void 0)return m.ticketNumber<=f.lastAppliedCommercialReductionTicket?{projection:null,commercialReductionWithheld:"stale_or_out_of_order_response"}:(f.lastAppliedCommercialReductionTicket=m.ticketNumber,{projection:null});if(h!==void 0&&h.projection!==null){let A=f.fence.applyResponse(m,{status:200,bodyValid:!0,projection:h.projection});return{projection:A.applied?A.projection:null,fenceResult:A}}return R===200?{projection:null,fenceResult:f.fence.applyResponse(m,{status:200,bodyValid:!1,rawBody:k})}:{projection:null}},q=(f,m)=>f?.commercialReductionProjection===void 0?{}:m!==void 0?{commercialReductionProjection:null,commercialReductionDisclosureWithheld:m}:{commercialReductionProjection:f.commercialReductionProjection},Z=(f,m,R,h,k)=>{if(f!==401&&f!==403)return;let A=v(),S=V(h,k,A,!1),K=m.lastSyncedSessionId===h.sessionId&&m.lastSyncedAuthEpoch===h.authEpoch;if(S||!K)return{projection:null,fenceResult:{applied:!1,reason:"context_mismatch",projection:null,watermarkTicket:m.fence.getAppliedTicketWatermark()}};let O=I(m,R,f,void 0,void 0);return(O.fenceResult===void 0||O.fenceResult.applied)&&(m.deniedExecutionSession={sessionId:h.sessionId,authEpoch:h.authEpoch,httpStatus:f}),O};return Object.freeze({ownerScope:e,async executeCommand(f){if(typeof f!="object"||f===null)throw new c("executeCommand input must be a non-null object.");let m=v();if(f.caller===void 0&&m.error!==null)throw m.error;let R=f.caller!==void 0?M(f.caller,!0,m):ke(m.effectiveCaller,e,!0),h=m.generation,k=f.projectionTicketNumber,A=$e({ownerScope:e,path:f.path,idempotencyKey:f.idempotencyKey,body:f.body});o.set(A.journalEnvelope.commandRef,A.sdkScopeRef);let S=b(A.sdkScopeRef,R);if(S.deniedExecutionSession!==null&&S.deniedExecutionSession.sessionId===R.sessionId&&S.deniedExecutionSession.authEpoch===R.authEpoch)throw new ee(`Order scope execution is denied for session "${R.sessionId}" (authEpoch ${String(R.authEpoch)}) after HTTP ${String(S.deniedExecutionSession.httpStatus)}.`);let K=S.fence.issueTicket(k),O,N,F,H,Se=!1,G=!1,me=await n.executeCommand({caller:R,envelope:A.journalEnvelope,sendOnce:async({envelope:Me})=>{let ue=cn(Me),Rn=v();if(V(R,h,Rn,!0)||S.deniedExecutionSession!==null&&S.deniedExecutionSession.sessionId===R.sessionId&&S.deniedExecutionSession.authEpoch===R.authEpoch)return G=!0,{kind:"corrupted_or_unclosed",reason:"caller_context_changed_or_denied_before_http_send"};Se=!0;let He=await Rr(t,`${t.apiBaseUrl}${ue.requestPath}`,{method:"POST",headers:{authorization:t.authorizationHeader,"content-type":"application/json","Idempotency-Key":ue.headers["Idempotency-Key"]},body:JSON.stringify(ue.wireRequestBody)},fe=>{O=fe,H=Z(fe,S,K,R,h)});return O=He.status,N=He.rawText,F=bn({method:"POST",httpStatus:He.status,rawBodyText:He.rawText,envelope:Me}),F.observation}}),he=v(),oe=V(R,h,he,!1),ge=me.snapshot,je=null,Ne,B;if(Se&&!G&&!oe)if(!(S.lastSyncedSessionId===R.sessionId&&S.lastSyncedAuthEpoch===R.authEpoch))oe=!0,B={applied:!1,reason:"context_mismatch",projection:null,watermarkTicket:S.fence.getAppliedTicketWatermark()};else if(H!==void 0)H.fenceResult!==void 0&&H.fenceResult.applied&&S.fence.getAppliedTicketWatermark()===K.ticketNumber?(je=null,B=H.fenceResult,(O===401||O===403)&&ge.status==="unknown"&&(ge=await n.parkEntry({caller:R,idempotencyKey:A.journalEnvelope.idempotencyKey}),he=v(),oe=oe||V(R,h,he,!1))):(je=null,B=H.fenceResult!==void 0&&!H.fenceResult.applied?H.fenceResult:{applied:!1,reason:"stale_ticket",projection:S.fence.getProjection(),watermarkTicket:S.fence.getAppliedTicketWatermark()});else{let ue=I(S,K,O,F,N);je=ue.projection,B=ue.fenceResult,Ne=ue.commercialReductionWithheld}else Se&&oe&&(B={applied:!1,reason:"context_mismatch",projection:null,watermarkTicket:S.fence.getAppliedTicketWatermark()});let Te=B!==void 0&&!B.applied&&B.reason!=="corrupted_ok_body";if(G||oe||Te)return Yo({sendInvoked:Se,httpStatus:O,projectionFenceResult:B});let De=ge.status==="resolved"&&F?.receipt!==null?F?.receipt??null:null,Ve=F?.wireOutcomeStatus==="applied"||F?.wireOutcomeStatus==="replayed_identical"||F?.wireOutcomeStatus==="unknown"?F.wireOutcomeStatus:void 0,Y=F?.deterministicError,fn=F?.authRevokedError;return Object.freeze({resultKind:"active",staleOrDenied:!1,snapshot:ge,sendInvoked:Se,...O===void 0?{}:{httpStatus:O},...Ve===void 0?{}:{wireOutcomeStatus:Ve},receipt:De,originalCasTriple:ge.envelope.casTriple,projection:je,...q(F,Ne),...B===void 0?{}:{projectionFenceResult:B},...Y===void 0?{}:{deterministicError:Y},...fn===void 0?{}:{authRevokedError:fn}})},async recoverCommand(f){if(typeof f!="object"||f===null)throw new c("recoverCommand input must be a non-null object.");let m=v();if(f.caller===void 0&&m.error!==null)throw m.error;let R=f.caller!==void 0?M(f.caller,!1,m):ke(m.effectiveCaller,e,!1),h=m.generation,k=f.commandRef,A=f.purchaseRef,S=f.economicIntentRef,K=f.projectionTicketNumber;if(A!==void 0&&S===void 0||A===void 0&&S!==void 0)throw new c("recoverCommand requires both purchaseRef and economicIntentRef when either is provided.");let O;A!==void 0&&S!==void 0?O=be(e,A,S):typeof k=="string"&&(O=o.get(k));let N,F;O!==void 0&&(N=b(O,R),F=N.fence.issueTicket(K));let H,Se,G,me,he,oe=!1,ge=!1,je=await n.recoverCommand({caller:R,idempotencyKey:k,lookup:async({envelope:fe})=>{let ie;try{ie=cn(fe)}catch(Ge){throw he=Ge,Ge}if(o.set(fe.commandRef,ie.sdkScopeRef),A!==void 0&&A!==ie.canonicalObject.path.purchaseRef||S!==void 0&&S!==ie.canonicalObject.path.economicIntentRef)throw he=new c("recoverCommand purchaseRef/economicIntentRef does not match the frozen journal envelope."),he;(N===void 0||F===void 0)&&(N=b(ie.sdkScopeRef,R),F=N.fence.issueTicket(K));let Qr=v();if(V(R,h,Qr,!1))return ge=!0,{kind:"corrupted_or_unclosed",reason:"caller_context_changed_or_denied_before_http_lookup"};let Yr=N,Xr=F;oe=!0;let yn=await Rr(t,`${t.apiBaseUrl}${ie.recoveryPath}`,{method:"GET",headers:{authorization:t.authorizationHeader,"X-Original-Command-Digest":ie.wireInputDigest}},Ge=>{H=Ge,me=Z(Ge,Yr,Xr,R,h)});return H=yn.status,Se=yn.rawText,G=bn({method:"GET",httpStatus:yn.status,rawBodyText:yn.rawText,envelope:fe}),G.observation}}).catch(fe=>{throw fe instanceof T&&N&&F&&!V(R,h,v(),!1)&&I(N,F,200,void 0,void 0),fe});if(he!==void 0)throw he;let Ne=v(),B=V(R,h,Ne,!1),Te=je.snapshot,De=null,Ve,Y;if(oe&&N!==void 0&&F!==void 0&&!ge&&!B)if(!(N.lastSyncedSessionId===R.sessionId&&N.lastSyncedAuthEpoch===R.authEpoch))B=!0,Y={applied:!1,reason:"context_mismatch",projection:null,watermarkTicket:N.fence.getAppliedTicketWatermark()};else if(me!==void 0)me.fenceResult!==void 0&&me.fenceResult.applied&&N.fence.getAppliedTicketWatermark()===F.ticketNumber?(De=null,Y=me.fenceResult,(H===401||H===403)&&Te.status==="unknown"&&(Te=await n.parkEntry({caller:R,idempotencyKey:k}),Ne=v(),B=B||V(R,h,Ne,!1))):(De=null,Y=me.fenceResult!==void 0&&!me.fenceResult.applied?me.fenceResult:{applied:!1,reason:"stale_ticket",projection:N.fence.getProjection(),watermarkTicket:N.fence.getAppliedTicketWatermark()});else{let ie=I(N,F,H,G,Se);De=ie.projection,Y=ie.fenceResult,Ve=ie.commercialReductionWithheld}else oe&&B&&(Y={applied:!1,reason:"context_mismatch",projection:null,watermarkTicket:N!==void 0?N.fence.getAppliedTicketWatermark():0});let fn=Y!==void 0&&!Y.applied&&Y.reason!=="corrupted_ok_body";if(ge||B||fn)return Xo({lookupInvoked:oe,httpStatus:H,projectionFenceResult:Y});let xt=Te.status==="resolved"&&G?.receipt!==null?G?.receipt??null:null,Me=G?.wireOutcomeStatus==="closed_recovered"||G?.wireOutcomeStatus==="unknown"?G.wireOutcomeStatus:void 0,ue=G?.deterministicError,Rn=G?.authRevokedError;return Object.freeze({resultKind:"active",staleOrDenied:!1,snapshot:Te,lookupInvoked:oe,...H===void 0?{}:{httpStatus:H},...Me===void 0?{}:{wireOutcomeStatus:Me},receipt:xt,originalCasTriple:Te.envelope.casTriple,projection:De,...q(G,Ve),...Y===void 0?{}:{projectionFenceResult:Y},...ue===void 0?{}:{deterministicError:ue},...Rn===void 0?{}:{authRevokedError:Rn}})},async loadPending(f){if(typeof f!="object"||f===null)throw new c("loadPending input must be a non-null object.");let m=v();if(f.caller===void 0&&m.error!==null)throw m.error;let R=f.caller!==void 0?M(f.caller,!1,m):ke(m.effectiveCaller,e,!1),h=m.generation,k=f.commandRef,A=await n.loadEntry({caller:R,idempotencyKey:k}),S=v();return V(R,h,S,!1)?null:A},getProjectedOrder(f){if(typeof f!="object"||f===null)return null;let m=v();if(m.error!==null||m.effectiveCaller===null)return null;try{ke(m.effectiveCaller,e,!1)}catch{return null}try{let R=be(e,f.purchaseRef,f.economicIntentRef),h=r.get(R);return h?(g(h,m.effectiveCaller,!1),h.fence.getProjection()):null}catch{return null}},getProjectionWatermark(f){if(typeof f!="object"||f===null)return 0;let m=v();if(m.error!==null||m.effectiveCaller===null)return 0;try{ke(m.effectiveCaller,e,!1)}catch{return 0}try{let R=be(e,f.purchaseRef,f.economicIntentRef),h=r.get(R);return h?(g(h,m.effectiveCaller,!1),h.fence.getAppliedTicketWatermark()):0}catch{return 0}},switchCallerContext(f){let m;try{m=ft(f,"nextCaller")}catch(O){throw i+=1,a=null,u!==null&&(l=Math.max(l,u+1)),p(),O}let R=v(),h=a??R.effectiveCaller,k=h!==null?un(h):d,A=un(m),S=u!==null&&(m.contextGeneration<u||m.contextGeneration<l),K=u!==null&&m.contextGeneration===u&&(R.error!==null||A!==k);if(S||K)throw i+=1,a=null,u!==null&&(l=Math.max(l,u)),p(),new _(`nextCaller.contextGeneration (${String(m.contextGeneration)}) regressed below or failed to advance past active generation (${String(Math.max(u??1,l))}).`);u=Math.max(u??m.contextGeneration,m.contextGeneration),l=Math.max(l,u),a=m,i+=1;for(let O of r.values())g(O,m,!0)}})}var gr="/api/merchant/enterprise-funds/preparations",Rt="facto.enterprise-purchase-preparation.v1",Zo="facto.enterprise-purchase-preparation-request.v1",ei="/api/merchant/enterprise-funds/purchases/{purchaseRef}/intents/{economicIntentRef}/commands/{commandRef}/holds",hr=Object.freeze({prepare:gr,byReference:"/api/merchant/enterprise-funds/preparations/by-reference/{merchantPaymentRef}"}),ni=["merchantPaymentRef","mandateId","userLinkRef"],ti=[...ni,"amount","currency","useCase","cartDigest"],ri=["protocolId","httpStatus","merchantPaymentRef","outcome","preparation","projection","receipt","outcomeDisclosure","pendingPollRequired","protectedCacheMustClear","reasonCode"],oi=["preparationRef","requestFingerprint","appId","organizationId","targetRealm","purchaseRef","economicIntentRef","publicOrderRef","mandateId","userLinkRef","pinRevision","pinnedRouteRef","executionPlanRef","firstCommandCandidate"],ii=["subject","requestFenceRef","contextGeneration","active"],ai=["test","dev","external","mainnet_staging","production"];function j(t){throw new c(t)}function Le(t,e,n,r=[]){(!t||typeof t!="object"||Array.isArray(t)||![Object.prototype,null].includes(Object.getPrototypeOf(t)))&&j(`${e} must be a plain object.`);let o=Object.getOwnPropertyDescriptors(t);for(let s of Reflect.ownKeys(o))(typeof s!="string"||!o[s]?.enumerable||!("value"in o[s]))&&j(`${e} must contain only enumerable data properties.`);let a=Object.fromEntries(Object.entries(o).map(([s,d])=>[s,d.value]));return E(a,e,n,r)}function Ie(t,e){return z(t,e),(!t||t.trim()!==t||[...t].length>128||/[\u0000-\u001f\u007f]/.test(t))&&j(`${e} must be canonical nonempty text of at most 128 characters.`),t}function yt(t){(typeof t!="string"||!/^sha256:[0-9a-f]{64}$(?![\s\S])/.test(t))&&j("Invalid preparation fingerprint.")}function ht(t){let e=Le(t,"preparation request",ti,["description"]),n=Ie(e.merchantPaymentRef,"merchantPaymentRef");(n==="."||n==="..")&&j("merchantPaymentRef cannot be a URL dot segment.");let r=Ie(e.mandateId,"mandateId"),o=Ie(e.userLinkRef,"userLinkRef");(typeof e.amount!="string"||!/^(0|[1-9][0-9]*)(\.[0-9]{1,18})?$(?![\s\S])/.test(e.amount))&&j("amount must be exact decimal-unit text with at most 18 fraction digits."),(e.currency!=="USDC"||typeof e.useCase!="string"||!["immediate","recurring","top_up","metered"].includes(e.useCase))&&j("Invalid preparation currency or useCase."),yt(e.cartDigest);let a;return Object.hasOwn(e,"description")&&(z(e.description,"description"),([...e.description].length>240||/[\u0000-\u001f\u007f]/.test(e.description))&&j("Invalid description."),a=e.description),Object.freeze({merchantPaymentRef:n,mandateId:r,userLinkRef:o,amount:e.amount,currency:"USDC",useCase:e.useCase,cartDigest:e.cartDigest,...a===void 0?{}:{description:a}})}function si(t,e){let n=ht(e),{canonicalBytes:r}=vn({protocol:Zo,method:"POST",routeTemplate:gr,appId:Ie(t,"appId"),request:n}),o=we(r);return yt(o),o}function ci(t,e,n){let r=Le(t,"preparation",oi);for(let a of["preparationRef","appId","mandateId","userLinkRef","pinnedRouteRef","executionPlanRef"])Ie(r[a],a);(r.appId!==e||r.mandateId!==n.mandateId||r.userLinkRef!==n.userLinkRef)&&j("Preparation original identity mismatch."),yt(r.requestFingerprint),r.requestFingerprint!==si(e,n)&&j("Preparation original request fingerprint mismatch."),(typeof r.organizationId!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$(?![\s\S])/.test(r.organizationId))&&j("Invalid preparation organization UUID."),(typeof r.targetRealm!="string"||!ai.some(a=>a===r.targetRealm))&&j("Invalid preparation target realm."),y(r.purchaseRef,"purchaseRef"),y(r.economicIntentRef,"economicIntentRef"),y(r.publicOrderRef,"publicOrderRef"),$(r.pinRevision,"pinRevision");let o=null;if(r.firstCommandCandidate!==null){let a=Le(r.firstCommandCandidate,"firstCommandCandidate",["method","routeTemplate","path","request"]);(a.method!=="POST"||a.routeTemplate!==sn.create_or_transition_source_hold)&&j("First candidate must use the original holds route.");let s=Le(a.request,"first hold request",["commandKind","inputDigest","cas","sourceRoot","holdRef","targetHoldState","settlementAsset","heldUnitsRaw","heldCashRaw","scaleNumerator","scaleDenominator","slippageBufferBps","quoteExpiresAt","authorityGrantRef","scopeBindingRef","commandRef"],["producerVerification"]);(s.commandKind!=="create_or_transition_source_hold"||s.targetHoldState!=="active")&&j("First candidate must be an active source-hold admission.");let d=ut(s);(d.canonicalRequestPayload.commandKind!=="create_or_transition_source_hold"||d.suppliedWireDigest===void 0)&&j("First candidate must contain its original hold digest.");let u=$e({ownerScope:{audience:"merchant_s2s",principalId:`merchant_app:${e}`,appId:e,organizationId:r.organizationId,targetRealm:r.targetRealm},path:qe(a.path),body:{...d.canonicalRequestPayload,inputDigest:d.suppliedWireDigest}});(u.canonicalObject.path.purchaseRef!==r.purchaseRef||u.canonicalObject.path.economicIntentRef!==r.economicIntentRef)&&j("First candidate purchase/intent mismatch.");let l=u.wireRequestBody;(l.commandKind!=="create_or_transition_source_hold"||l.targetHoldState!=="active")&&j("First candidate kind/state mismatch."),o=Object.freeze({method:"POST",routeTemplate:ei,path:u.canonicalObject.path,request:Object.freeze({...l,targetHoldState:"active"})})}return Object.freeze({preparationRef:r.preparationRef,requestFingerprint:r.requestFingerprint,appId:e,organizationId:r.organizationId,targetRealm:r.targetRealm,purchaseRef:r.purchaseRef,economicIntentRef:r.economicIntentRef,publicOrderRef:r.publicOrderRef,mandateId:n.mandateId,userLinkRef:n.userLinkRef,pinRevision:r.pinRevision,pinnedRouteRef:r.pinnedRouteRef,executionPlanRef:r.executionPlanRef,firstCommandCandidate:o})}function di(t,e,n,r){let o=Le(t,"preparation response",ri);(o.protocolId!==Rt||o.httpStatus!==e||o.receipt!==null)&&j("Preparation HTTP/protocol/receipt mismatch.");let a=ht(r),d=e===401||e===403||(e===400||e===503)&&o.merchantPaymentRef===null?null:a.merchantPaymentRef;if(o.merchantPaymentRef!==d&&j("Preparation original merchant reference mismatch."),e===200){(o.outcome!=="prepared"||o.outcomeDisclosure!=="disclosed"||o.pendingPollRequired!==!1||o.protectedCacheMustClear!==!1||o.reasonCode!==null)&&j("Malformed prepared envelope.");let l=ci(o.preparation,n,a),i=o.projection===null?null:Ke(o.projection,"projection",n);return i!==null&&i.publicOrderRef!==l.publicOrderRef&&j("Preparation projection order mismatch."),Object.freeze({protocolId:Rt,httpStatus:200,merchantPaymentRef:a.merchantPaymentRef,outcome:"prepared",preparation:l,projection:i,receipt:null,outcomeDisclosure:"disclosed",pendingPollRequired:!1,protectedCacheMustClear:!1,reasonCode:null})}(o.preparation!==null||o.projection!==null||o.protectedCacheMustClear!==!0)&&j("Unknown/error response must not contain protected payload.");let u={202:["pending","unknown",!0,["not_observed","preparation_commit_unknown","current_snapshot_unavailable","preparation_pending"]],400:["invalid_request","unknown",!0,["invalid_preparation_request"]],401:["access_denied","undisclosed",!0,["current_authentication_required"]],403:["access_denied","undisclosed",!0,["current_access_denied"]],503:["pending","unknown",!0,["temporarily_unavailable"]]};if(e===409){let l={conflict:["original_input_conflict","original_binding_conflict"],legacy_conflict:["legacy_payment_exists"],blocked:["current_admission_blocked","required_configuration_unavailable","trusted_source_or_plan_unavailable"]};(typeof o.outcome!="string"||!Object.hasOwn(l,o.outcome)||typeof o.reasonCode!="string"||!l[o.outcome].includes(o.reasonCode)||o.outcomeDisclosure!=="disclosed"||o.pendingPollRequired!==!1)&&j("Malformed preparation conflict.")}else{let l=u[e];(!l||o.outcome!==l[0]||o.outcomeDisclosure!==l[1]||o.pendingPollRequired!==l[2]||typeof o.reasonCode!="string"||!l[3].includes(o.reasonCode))&&j("Malformed preparation error/unknown.")}return Object.freeze({protocolId:Rt,httpStatus:e,merchantPaymentRef:d,outcome:o.outcome,preparation:null,projection:null,receipt:null,outcomeDisclosure:o.outcomeDisclosure,pendingPollRequired:o.pendingPollRequired,protectedCacheMustClear:!0,reasonCode:o.reasonCode})}function ce(t,e,n,r){return Object.freeze({resultKind:t,httpStatus:e,envelope:null,preparation:null,projection:null,receipt:null,requestFingerprint:null,firstCommandCandidate:null,merchantPaymentRef:null,originalRequest:null,protectedCacheMustClear:n,pendingPollRequired:!0,reasonCode:r})}function Er(t){let e=new URL(t.apiBaseUrl);(!["http:","https:"].includes(e.protocol)||e.pathname!=="/"||e.search||e.hash||e.username||e.password)&&j("Preparation apiBaseUrl must be an HTTP(S) origin without path/query/hash/userinfo."),typeof t.getHostContext!="function"&&j("getHostContext is required.");let n=Ie(t.appId,"appId"),r,o=0,a=0,s=0,d=0,u=new Set;function l(){try{let g=Le(t.getHostContext(),"host context",ii),v=Ie(g.subject,"subject"),M=Ie(g.requestFenceRef,"requestFenceRef");(typeof g.contextGeneration!="number"||!Number.isSafeInteger(g.contextGeneration)||g.contextGeneration<1||typeof g.active!="boolean")&&j("Invalid host generation/active.");let b=Object.freeze({subject:v,requestFenceRef:M,contextGeneration:g.contextGeneration,active:g.active});return(b.contextGeneration<=d||r&&(b.contextGeneration<r.contextGeneration||b.contextGeneration===r.contextGeneration&&(b.subject!==r.subject||b.requestFenceRef!==r.requestFenceRef||b.active!==r.active)))&&j("Host context must change only with a strictly increasing generation."),(!r||b.contextGeneration!==r.contextGeneration)&&o++,r=b,b}catch(g){throw d=Math.max(d,r?.contextGeneration??0),o++,g}}l();let i=g=>JSON.stringify([n,e.origin,g.subject,g.requestFenceRef]);async function p(g,v){let M=ht(v),b=l();if(!b.active||u.has(i(b)))return ce("stale_or_denied",null,!0,"current_access_denied");a>=Number.MAX_SAFE_INTEGER&&j("Preparation request sequence exhausted.");let V=o,I=++a,q=null,Z=(h=!1)=>{try{return l().active&&o===V&&(h?I>s:I===s)}catch{return!1}},f=new AbortController,m=()=>f.abort();t.signal?.addEventListener("abort",m,{once:!0});let R=t.timeoutMs===void 0?void 0:setTimeout(m,t.timeoutMs);try{if(t.signal?.aborted)return ce("unknown",null,!0,"transport_or_response_unknown");let h=new TextEncoder().encode(M.merchantPaymentRef),k=new Uint8Array(h.byteLength);k.set(h);let A=we(k).slice(7),S;try{S=await t.transport(e.origin+(g==="POST"?hr.prepare:hr.byReference.replace("{merchantPaymentRef}",encodeURIComponent(M.merchantPaymentRef))),{method:g,redirect:"manual",signal:f.signal,headers:{Authorization:t.authorizationHeader,Accept:"application/json",...g==="POST"?{"Content-Type":"application/json","Idempotency-Key":`prepare_v1_${A}`}:{}},...g==="POST"?{body:JSON.stringify(M)}:{}})}catch{return Z(!0)?(s=I,ce("unknown",null,!0,"transport_or_response_unknown")):ce("stale_or_denied",null,!1,"stale_context_or_response")}if(q=S.status,!Z(!0))return S.body?.cancel().catch(()=>{}),ce("stale_or_denied",q,!1,"stale_context_or_response");if(s=I,q===401||q===403)return u.add(i(b)),S.body?.cancel().catch(()=>{}),ce("stale_or_denied",q,!0,"current_access_denied");if(S.redirected||q>=300&&q<400||S.type==="opaqueredirect")return S.body?.cancel().catch(()=>{}),ce("unknown",q,!0,"transport_or_response_unknown");let K;try{K=await S.text()}catch{return Z()?ce("unknown",q,!0,"transport_or_response_unknown"):ce("stale_or_denied",q,!1,"stale_context_or_response")}if(!Z())return ce("stale_or_denied",q,!1,"stale_context_or_response");let O;try{O=di(JSON.parse(K),q,n,M)}catch{return ce("unknown",q,!0,"transport_or_response_unknown")}if(!Z())return ce("stale_or_denied",q,!1,"stale_context_or_response");let N=O.preparation;return Object.freeze({resultKind:"active",httpStatus:O.httpStatus,envelope:O,preparation:N,projection:O.projection,receipt:null,requestFingerprint:N?.requestFingerprint??null,firstCommandCandidate:N?.firstCommandCandidate??null,merchantPaymentRef:O.merchantPaymentRef,originalRequest:null,protectedCacheMustClear:O.protectedCacheMustClear,pendingPollRequired:O.pendingPollRequired})}finally{R!==void 0&&clearTimeout(R),t.signal?.removeEventListener("abort",m)}}return Object.freeze({preparePurchaseOnce:g=>p("POST",g),getPreparation:g=>p("GET",g)})}var Cr=Object.freeze({partnerProjection:"/api/partner/enterprise-funds/orders/{publicOrderRef}/projection",partnerOperation:"/api/partner/enterprise-funds/orders/{publicOrderRef}/operations/{operationRef}",consumerProjection:"/api/consumer/enterprise-funds/orders/{publicOrderRef}/projection",consumerOperation:"/api/consumer/enterprise-funds/orders/{publicOrderRef}/operations/{operationRef}",consoleProjection:"/api/console/enterprise-funds/purchases/{purchaseRef}/intents/{economicIntentRef}/projection",consoleCommand:"/api/console/enterprise-funds/purchases/{purchaseRef}/intents/{economicIntentRef}/commands/{commandRef}"}),ui=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;function li(t,e){let n=Cr[t],r={partnerProjection:["publicOrderRef"],partnerOperation:["publicOrderRef","operationRef"],consumerProjection:["publicOrderRef"],consumerOperation:["publicOrderRef","operationRef"],consoleProjection:["purchaseRef","economicIntentRef"],consoleCommand:["purchaseRef","economicIntentRef","commandRef"]},o=n;for(let a of r[t]){let s=e[a];if(typeof s!="string"||s.length===0)throw new c(`Audience read route "${t}" requires "${a}".`);o=o.replace(`{${a}}`,encodeURIComponent(s))}return o}function pi(t,e="audienceProjectionUnavailable"){let n=E(t,e,["code","message","preservePendingCommandJournal","retryAction"]);if(n.code!=="audience_projection_unavailable")throw new c(`${e}.code must be "audience_projection_unavailable".`);if(typeof n.message!="string")throw new c(`${e}.message must be a string.`);if(n.preservePendingCommandJournal!==!0)throw new c(`${e}.preservePendingCommandJournal must be true.`);if(n.retryAction!=="retain_journal_and_poll_readonly_recovery")throw new c(`${e}.retryAction must be "retain_journal_and_poll_readonly_recovery".`);return Object.freeze({code:"audience_projection_unavailable",message:n.message,preservePendingCommandJournal:!0,retryAction:"retain_journal_and_poll_readonly_recovery"})}function mi(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e=t,n=e.code??e.errorCode;return typeof n=="string"?n:null}function Sr(t,e){let n=E(t,e,["operationRef","closedAt","completion"]);if(typeof n.operationRef!="string"||!/^op_[A-Za-z0-9_-]{32,96}$/.test(n.operationRef))throw new c(`${e}.operationRef must match ^op_[A-Za-z0-9_-]{32,96}$.`);if(se(n.closedAt,`${e}.closedAt`),n.completion!=="this_operation_closed")throw new c(`${e}.completion must be "this_operation_closed".`);return Object.freeze({operationRef:n.operationRef,closedAt:n.closedAt,completion:"this_operation_closed"})}function _r(t,e="partnerProjectionResponse"){let n=E(t,e,["projection"]);return Object.freeze({projection:An(n.projection,`${e}.projection`)})}function wr(t,e="partnerOperationRecoveryResponse"){let n=E(t,e,["publicOrderRef","operationRef","outcomeStatus","receipt","projection","pendingPollRequired","auditIdentityRetentionRequired"]);if(y(n.publicOrderRef,`${e}.publicOrderRef`),n.outcomeStatus!=="closed_recovered")throw new c(`${e}.outcomeStatus must be "closed_recovered".`);Et(n,e);let r=jn(n.operationRef,`${e}.operationRef`),o=Sr(n.receipt,`${e}.receipt`);if(o.operationRef!==r)throw new c(`${e}.receipt.operationRef must equal ${e}.operationRef.`);return Object.freeze({publicOrderRef:n.publicOrderRef,operationRef:r,outcomeStatus:"closed_recovered",receipt:o,projection:An(n.projection,`${e}.projection`),pendingPollRequired:!1,auditIdentityRetentionRequired:!0})}function Pr(t,e="partnerOperationUnknownRecoveryResponse"){let n=E(t,e,["publicOrderRef","operationRef","outcomeStatus","unknownReason","receipt","projection","pendingPollRequired","auditIdentityRetentionRequired","retryAction"]);if(y(n.publicOrderRef,`${e}.publicOrderRef`),n.outcomeStatus!=="unknown")throw new c(`${e}.outcomeStatus must be "unknown".`);if(U(n.unknownReason,Pn,`${e}.unknownReason`),n.receipt!==null)throw new c(`${e}.receipt must be null.`);Ct(n,e);let r=n.projection===null?null:An(n.projection,`${e}.projection`);return Object.freeze({publicOrderRef:n.publicOrderRef,operationRef:jn(n.operationRef,`${e}.operationRef`),outcomeStatus:"unknown",unknownReason:n.unknownReason,receipt:null,projection:r,pendingPollRequired:!0,auditIdentityRetentionRequired:!0,retryAction:"retain_journal_and_poll_readonly_recovery"})}function kn(t,e="projection"){let n=E(t,e,["audience","publicOrderRef","settlementAsset","authorizedPaymentCeiling","establishedPrincipal","confirmedCollectedFromMe","appliedToPrincipal","unappliedOwnCash","remainingMyDebt","mySourceWithdrawableSnapshot","myActiveHoldAmount","myEffectiveAvailableSource","executionState","fulfillmentPermitted","cacheCoordination","projectionRevision","asOf","fulfillmentQualification","operations","businessProgress"]);if(n.audience!=="consumer")throw new c(`${e}.audience must be "consumer", received "${String(n.audience)}".`);return y(n.publicOrderRef,`${e}.publicOrderRef`),x(n.authorizedPaymentCeiling,`${e}.authorizedPaymentCeiling`),x(n.establishedPrincipal,`${e}.establishedPrincipal`),x(n.confirmedCollectedFromMe,`${e}.confirmedCollectedFromMe`),x(n.myActiveHoldAmount,`${e}.myActiveHoldAmount`),U(n.executionState,ot,`${e}.executionState`),U(n.fulfillmentQualification,Ue,`${e}.fulfillmentQualification`),xr(n,e),$(n.projectionRevision,`${e}.projectionRevision`),se(n.asOf,`${e}.asOf`),Object.freeze({audience:"consumer",publicOrderRef:n.publicOrderRef,settlementAsset:ve(n.settlementAsset,`${e}.settlementAsset`),authorizedPaymentCeiling:n.authorizedPaymentCeiling,establishedPrincipal:n.establishedPrincipal,confirmedCollectedFromMe:n.confirmedCollectedFromMe,appliedToPrincipal:J(n.appliedToPrincipal,`${e}.appliedToPrincipal`),unappliedOwnCash:J(n.unappliedOwnCash,`${e}.unappliedOwnCash`),remainingMyDebt:J(n.remainingMyDebt,`${e}.remainingMyDebt`),mySourceWithdrawableSnapshot:J(n.mySourceWithdrawableSnapshot,`${e}.mySourceWithdrawableSnapshot`),myActiveHoldAmount:n.myActiveHoldAmount,myEffectiveAvailableSource:J(n.myEffectiveAvailableSource,`${e}.myEffectiveAvailableSource`),executionState:n.executionState,fulfillmentPermitted:n.fulfillmentPermitted,cacheCoordination:dn(n.cacheCoordination,`${e}.cacheCoordination`),projectionRevision:n.projectionRevision,asOf:n.asOf,fulfillmentQualification:n.fulfillmentQualification,operations:lt(n.operations,`${e}.operations`),businessProgress:gt(n.businessProgress,`${e}.businessProgress`)})}function fi(t,e){let n=E(t,e,["knowledgeState","state","unknownReason"]);if(n.knowledgeState==="known"){if(n.state!=="partially_received")throw new c(`${e}.state must be "partially_received" when knowledgeState is "known".`);if(n.unknownReason!==null)throw new c(`${e}.unknownReason must be null when knowledgeState is "known".`);return Object.freeze({knowledgeState:"known",state:"partially_received",unknownReason:null})}if(n.knowledgeState==="unknown"){if(n.state!==null)throw new c(`${e}.state must be null when knowledgeState is "unknown".`);return U(n.unknownReason,en,`${e}.unknownReason`),Object.freeze({knowledgeState:"unknown",state:null,unknownReason:n.unknownReason})}throw new c(`${e}.knowledgeState must be "known" or "unknown".`)}function gt(t,e="projection.businessProgress"){let n=E(t,e,["sourceExecution","guarantee","partnerCapture","partnerPayout","userCollection"]);return Object.freeze({sourceExecution:Ce(n.sourceExecution,nn,`${e}.sourceExecution`),guarantee:Ce(n.guarantee,tn,`${e}.guarantee`),partnerCapture:Ce(n.partnerCapture,Oe,`${e}.partnerCapture`),partnerPayout:Ce(n.partnerPayout,Oe,`${e}.partnerPayout`),userCollection:fi(n.userCollection,`${e}.userCollection`)})}function vr(t,e="consumerProjectionResponse"){let n=E(t,e,["projection"]);return Object.freeze({projection:kn(n.projection,`${e}.projection`)})}function Ir(t,e="consumerOperationRecoveryResponse"){let n=E(t,e,["publicOrderRef","operationRef","outcomeStatus","receipt","projection","pendingPollRequired","auditIdentityRetentionRequired"]);if(y(n.publicOrderRef,`${e}.publicOrderRef`),n.outcomeStatus!=="closed_recovered")throw new c(`${e}.outcomeStatus must be "closed_recovered".`);Et(n,e);let r=jn(n.operationRef,`${e}.operationRef`),o=Sr(n.receipt,`${e}.receipt`);if(o.operationRef!==r)throw new c(`${e}.receipt.operationRef must equal ${e}.operationRef.`);return Object.freeze({publicOrderRef:n.publicOrderRef,operationRef:r,outcomeStatus:"closed_recovered",receipt:o,projection:kn(n.projection,`${e}.projection`),pendingPollRequired:!1,auditIdentityRetentionRequired:!0})}function Tr(t,e="consumerOperationUnknownRecoveryResponse"){let n=E(t,e,["publicOrderRef","operationRef","outcomeStatus","unknownReason","receipt","projection","pendingPollRequired","auditIdentityRetentionRequired","retryAction"]);if(y(n.publicOrderRef,`${e}.publicOrderRef`),n.outcomeStatus!=="unknown")throw new c(`${e}.outcomeStatus must be "unknown".`);if(U(n.unknownReason,Pn,`${e}.unknownReason`),n.receipt!==null)throw new c(`${e}.receipt must be null.`);Ct(n,e);let r=n.projection===null?null:kn(n.projection,`${e}.projection`);return Object.freeze({publicOrderRef:n.publicOrderRef,operationRef:jn(n.operationRef,`${e}.operationRef`),outcomeStatus:"unknown",unknownReason:n.unknownReason,receipt:null,projection:r,pendingPollRequired:!0,auditIdentityRetentionRequired:!0,retryAction:"retain_journal_and_poll_readonly_recovery"})}function xn(t,e="projection"){let n=E(t,e,["audience","purchaseRef","economicIntentRef","appId","organizationId","contextRevision","sourceRevision","budgetRevision","authorizedCeilingRaw","principalEstablishedRaw","consumerCollectedRaw","consumerAppliedToPrincipalRaw","consumerUnappliedRaw","remainingRecoverablePrincipalRaw","sharedPrefundAccountAvailableRaw","appAllocationRemainingRaw","sourceWithdrawableSnapshotRaw","sourceRepresentedHoldRaw","sourceUnrepresentedHoldRaw","sourceEffectiveAvailableRaw","fulfillmentPermitted","cacheCoordination","projectionRevision","asOf","fulfillmentQualification","settlementAsset","businessProgress"]);if(n.audience!=="console_admin")throw new c(`${e}.audience must be "console_admin", received "${String(n.audience)}".`);if(y(n.purchaseRef,`${e}.purchaseRef`),y(n.economicIntentRef,`${e}.economicIntentRef`),y(n.appId,`${e}.appId`),typeof n.organizationId!="string"||!ui.test(n.organizationId))throw new c(`${e}.organizationId must be a UUID.`);return $(n.contextRevision,`${e}.contextRevision`),$(n.sourceRevision,`${e}.sourceRevision`),$(n.budgetRevision,`${e}.budgetRevision`),x(n.authorizedCeilingRaw,`${e}.authorizedCeilingRaw`),x(n.principalEstablishedRaw,`${e}.principalEstablishedRaw`),x(n.consumerCollectedRaw,`${e}.consumerCollectedRaw`),x(n.sourceRepresentedHoldRaw,`${e}.sourceRepresentedHoldRaw`),x(n.sourceUnrepresentedHoldRaw,`${e}.sourceUnrepresentedHoldRaw`),U(n.fulfillmentQualification,Ue,`${e}.fulfillmentQualification`),xr(n,e),$(n.projectionRevision,`${e}.projectionRevision`),se(n.asOf,`${e}.asOf`),Object.freeze({audience:"console_admin",purchaseRef:n.purchaseRef,economicIntentRef:n.economicIntentRef,appId:n.appId,organizationId:n.organizationId,contextRevision:n.contextRevision,sourceRevision:n.sourceRevision,budgetRevision:n.budgetRevision,authorizedCeilingRaw:n.authorizedCeilingRaw,principalEstablishedRaw:n.principalEstablishedRaw,consumerCollectedRaw:n.consumerCollectedRaw,consumerAppliedToPrincipalRaw:J(n.consumerAppliedToPrincipalRaw,`${e}.consumerAppliedToPrincipalRaw`),consumerUnappliedRaw:J(n.consumerUnappliedRaw,`${e}.consumerUnappliedRaw`),remainingRecoverablePrincipalRaw:J(n.remainingRecoverablePrincipalRaw,`${e}.remainingRecoverablePrincipalRaw`),sharedPrefundAccountAvailableRaw:J(n.sharedPrefundAccountAvailableRaw,`${e}.sharedPrefundAccountAvailableRaw`),appAllocationRemainingRaw:J(n.appAllocationRemainingRaw,`${e}.appAllocationRemainingRaw`),sourceWithdrawableSnapshotRaw:J(n.sourceWithdrawableSnapshotRaw,`${e}.sourceWithdrawableSnapshotRaw`),sourceRepresentedHoldRaw:n.sourceRepresentedHoldRaw,sourceUnrepresentedHoldRaw:n.sourceUnrepresentedHoldRaw,sourceEffectiveAvailableRaw:J(n.sourceEffectiveAvailableRaw,`${e}.sourceEffectiveAvailableRaw`),fulfillmentPermitted:n.fulfillmentPermitted,cacheCoordination:dn(n.cacheCoordination,`${e}.cacheCoordination`),projectionRevision:n.projectionRevision,asOf:n.asOf,fulfillmentQualification:n.fulfillmentQualification,settlementAsset:ve(n.settlementAsset,`${e}.settlementAsset`),businessProgress:gt(n.businessProgress,`${e}.businessProgress`)})}function Ar(t,e="consoleProjectionResponse"){let n=E(t,e,["projection"]);return Object.freeze({projection:xn(n.projection,`${e}.projection`)})}function Or(t,e="consoleCommandReceipt"){let n=E(t,e,["commandRef","purchaseRef","economicIntentRef","inputDigest","commitConfirmationLevel","closedAt","resultContextRevision","closureTarget","resultSourceRevision","resultBudgetRevision","originalCas"]);if(y(n.commandRef,`${e}.commandRef`),y(n.purchaseRef,`${e}.purchaseRef`),y(n.economicIntentRef,`${e}.economicIntentRef`),ae(n.inputDigest,`${e}.inputDigest`),n.commitConfirmationLevel!=="outer_commit_driver_confirmed")throw new c(`${e}.commitConfirmationLevel must be "outer_commit_driver_confirmed".`);return se(n.closedAt,`${e}.closedAt`),$(n.resultContextRevision,`${e}.resultContextRevision`),$(n.resultSourceRevision,`${e}.resultSourceRevision`),$(n.resultBudgetRevision,`${e}.resultBudgetRevision`),Object.freeze({commandRef:n.commandRef,purchaseRef:n.purchaseRef,economicIntentRef:n.economicIntentRef,inputDigest:n.inputDigest,commitConfirmationLevel:"outer_commit_driver_confirmed",closedAt:n.closedAt,resultContextRevision:n.resultContextRevision,closureTarget:pt(n.closureTarget,`${e}.closureTarget`),resultSourceRevision:n.resultSourceRevision,resultBudgetRevision:n.resultBudgetRevision,originalCas:Pe(n.originalCas,`${e}.originalCas`)})}function br(t,e="consoleCommandRecoveryResponse"){let n=E(t,e,["outcomeStatus","receipt","projection","pendingPollRequired","auditIdentityRetentionRequired"]);if(n.outcomeStatus!=="closed_recovered")throw new c(`${e}.outcomeStatus must be "closed_recovered".`);return Et(n,e),Object.freeze({outcomeStatus:"closed_recovered",receipt:Or(n.receipt,`${e}.receipt`),projection:xn(n.projection,`${e}.projection`),pendingPollRequired:!1,auditIdentityRetentionRequired:!0})}function kr(t,e="consoleCommandUnknownRecoveryResponse"){let n=E(t,e,["commandRef","inputDigest","outcomeStatus","unknownReason","receipt","pendingPollRequired","auditIdentityRetentionRequired","retryAction","projection"]);if(y(n.commandRef,`${e}.commandRef`),ae(n.inputDigest,`${e}.inputDigest`),n.outcomeStatus!=="unknown")throw new c(`${e}.outcomeStatus must be "unknown".`);if(U(n.unknownReason,rn,`${e}.unknownReason`),n.receipt!==null)throw new c(`${e}.receipt must be null.`);return Ct(n,e),Object.freeze({commandRef:n.commandRef,inputDigest:n.inputDigest,outcomeStatus:"unknown",unknownReason:n.unknownReason,receipt:null,pendingPollRequired:!0,auditIdentityRetentionRequired:!0,retryAction:"retain_journal_and_poll_readonly_recovery",projection:xn(n.projection,`${e}.projection`)})}function jn(t,e){if(typeof t!="string"||!/^op_[A-Za-z0-9_-]{32,96}$/.test(t))throw new c(`${e} must match ^op_[A-Za-z0-9_-]{32,96}$.`);return t}function Et(t,e){if(t.pendingPollRequired!==!1)throw new c(`${e}.pendingPollRequired must be false for a closed recovery.`);if(t.auditIdentityRetentionRequired!==!0)throw new c(`${e}.auditIdentityRetentionRequired must be true.`)}function Ct(t,e){if(t.pendingPollRequired!==!0)throw new c(`${e}.pendingPollRequired must be true for an unknown recovery.`);if(t.auditIdentityRetentionRequired!==!0)throw new c(`${e}.auditIdentityRetentionRequired must be true.`);if(t.retryAction!=="retain_journal_and_poll_readonly_recovery")throw new c(`${e}.retryAction must be "retain_journal_and_poll_readonly_recovery".`)}function xr(t,e){if(typeof t.fulfillmentPermitted!="boolean")throw new c(`${e}.fulfillmentPermitted must be a boolean.`);if(t.fulfillmentQualification!=="qualified"&&t.fulfillmentPermitted!==!1)throw new c(`${e}.fulfillmentPermitted must be false when fulfillmentQualification is "${String(t.fulfillmentQualification)}".`)}function Ri(t){try{return On(t)}catch{return null}}function Fe(t,e,n,r){if(t===401||t===403){let o=Ri(e);return Object.freeze({resultKind:"auth_revoked",httpStatus:t,error:o,malformedBody:o===null})}if(t===200)try{return Object.freeze({resultKind:"closed",httpStatus:200,body:n(e)})}catch{return Object.freeze({resultKind:"unexpected",httpStatus:t,malformedBody:!0})}if(t===202)try{return Object.freeze({resultKind:"unknown",httpStatus:202,body:r(e)})}catch{return Object.freeze({resultKind:"unexpected",httpStatus:t,malformedBody:!0})}if(t===400)return Object.freeze({resultKind:"invalid_reference",httpStatus:400,errorCode:mi(e)});if(t===503)try{return Object.freeze({resultKind:"unavailable",httpStatus:503,error:pi(e),malformedBody:!1})}catch{return Object.freeze({resultKind:"unavailable",httpStatus:503,error:null,malformedBody:!0})}return Object.freeze({resultKind:"unexpected",httpStatus:t,malformedBody:!1})}function yi(t,e){return Fe(t,e,_r,()=>{throw new c("Partner projection has no 202 unknown body.")})}function hi(t,e){return Fe(t,e,wr,Pr)}function gi(t,e){return Fe(t,e,vr,()=>{throw new c("Consumer projection has no 202 unknown body.")})}function Ei(t,e){return Fe(t,e,Ir,Tr)}function Ci(t,e){return Fe(t,e,Ar,()=>{throw new c("Console projection has no 202 unknown body.")})}function Si(t,e){return Fe(t,e,br,kr)}function Un(t){return t==="sandbox"?"dev":t}var St=Object.freeze({dev:"https://dev-api.facto.to",production:"https://api.facto.to"}),ln=Object.freeze({dev:"https://dev.facto.to",production:"https://app.facto.to"}),wi=Object.freeze({dev:Object.freeze(["dev_mcid_","dev_pspid_","dev_cpid_"]),production:Object.freeze(["mcid_","pspid_","cpid_"])});function Pi(t){if(typeof t=="string"){for(let e of["dev","production"])for(let n of wi[e])if(t.startsWith(n))return e}}var W=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"});function vi(t){t.appId||P("appId is required"),t.state||P("state is required"),t.nonce||P("nonce is required"),t.hostedConnectUrl||P("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||P("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=Na(t.merchantOrigin),n=Tt(t.hostedConnectUrl);ze(n,ln,"hostedConnectUrl",!0);let r=new URL("/connect",`${n}/`);r.searchParams.set("external_app_id",t.appId),r.searchParams.set("external_state",t.state),r.searchParams.set("external_nonce",t.nonce),r.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 a=o.toString();return a&&(r.hash=a),r.toString()}function Ii(t){let e=At(t),n=`Basic ${kt(`${e.clientId}:${e.clientSecret}`)}`,r=(i,p)=>de(e,i,{code:p.code,state:p.state,nonce:p.nonce},n,ta),o=(i,p)=>de(e,i,na(e,p),n,ra),a=(i,p)=>de(e,i,{appId:e.appId,externalCustomerRef:p.externalCustomerRef,requestedUseCases:p.requestedUseCases,defaultLimits:p.defaultLimits,returnUrl:p.returnUrl,state:p.state,...p.customerEmail===void 0?{}:{customerEmail:p.customerEmail},...p.customerUsername===void 0?{}:{customerUsername:p.customerUsername}},n,Kr),s=(i,p)=>te(e,`${i}/${encodeURIComponent(p)}`,n,Kr),d=(i,p)=>te(e,`${i}/${encodeURIComponent(p)}`,n,Lr),u=(i,p)=>{let g={mandateId:p.mandateId,merchantPaymentRef:p.merchantPaymentRef,amount:p.amount,currency:p.currency,useCase:p.useCase};return p.paymentOptionId!==void 0&&(g.paymentOptionId=p.paymentOptionId),p.description!==void 0&&(g.description=p.description),p.metadata!==void 0&&(g.metadata=p.metadata),p.subMerchantRef!==void 0&&(g.subMerchantRef=p.subMerchantRef),p.subMerchantDisplayName!==void 0&&(g.subMerchantDisplayName=p.subMerchantDisplayName),de(e,i,g,n,Dn,{"Idempotency-Key":p.idempotencyKey},[402])},l=(i,p)=>te(e,`${i}/${encodeURIComponent(p)}`,n,Dn);return{createHostedConnectUrl(i){let p=i.hostedConnectUrl??e.hostedConnectUrl;if(i.hostedConnectUrl!==void 0){let g=ze(i.hostedConnectUrl,ln,"hostedConnectUrl",!0);g!==void 0&&g!==Un(e.environment)&&P("hostedConnectUrl conflicts with the configured environment")}return vi({appId:e.appId,state:i.state,nonce:i.nonce,customerEmail:i.customerEmail,customerUsername:i.customerUsername,hostedConnectUrl:p,merchantOrigin:i.merchantOrigin})},exchangeUserLinkCode(i){return r(W.exchangeLinkCode,i)},getPaymentReadiness(i){return o(W.paymentCapability,i)},createAuthorizationSession(i){return a(W.authorizationSessions,i)},getAuthorizationSession(i){return s(W.authorizationSessions,i)},getPaymentAuthorization(i){return d(W.paymentAuthorizations,i)},createMerchantPayment(i){return u(W.payments,i)},getMerchantPayment(i){return l(W.payments,i)},exchangeLinkCode(i){return r(W.exchangeLinkCode,i)},getPaymentCapability(i){return o(W.paymentCapability,i)},createCheckoutSession(i){return i.userLinkRef!==void 0&&xe(i.userLinkRef,"ul_","userLinkRef"),de(e,W.checkoutSessions,{...i.userLinkRef!==void 0?{userLinkRef:i.userLinkRef}:{app_id:e.appId,facto_server_wallet_address:i.factoServerWalletAddress},amount:i.amount,asset_symbol:i.assetSymbol,order_ref:i.orderRef,return_url:i.returnUrl},n,oa)},getCheckoutSession(i){return te(e,`${W.checkoutSessions}/${encodeURIComponent(i)}`,n,ia)},createMandateAuthorizationSession(i){return a(W.authorizationSessions,i)},getMandateAuthorizationSession(i){return s(W.authorizationSessions,i)},getMerchantMandate(i){return d(W.paymentAuthorizations,i)},listPaymentOptions(i){return i.userLinkRef!==void 0&&xe(i.userLinkRef,"ul_","userLinkRef"),de(e,W.paymentOptions,{...i.userLinkRef!==void 0?{userLinkRef:i.userLinkRef}:{appId:e.appId,grantRef:i.grantRef},...i.amount!==void 0?{amount:i.amount}:{},...i.assetSymbol!==void 0?{assetSymbol:i.assetSymbol}:{}},n,ca)},createMandatePayment(i){return u(W.payments,i)},getMandatePayment(i){return l(W.payments,i)},pollMerchantPayment(i,p,g){return Oi(()=>te(e,`${W.payments}/${encodeURIComponent(i)}`,n,Dn),p,g)},revokeUserLink(i){return Mr(e,`/api/merchant/user-links/${encodeURIComponent(i)}`,n)},listMerchantPayments(i={}){return te(e,_t("/api/merchant/payments",{limit:i.limit,startingAfter:i.startingAfter,createdAfter:i.createdAfter,createdBefore:i.createdBefore,authorizationId:i.authorizationId,status:i.status}),n,p=>wt(p,Dn))},listPaymentAuthorizations(i={}){return te(e,_t("/api/merchant/payment-authorizations",{limit:i.limit,startingAfter:i.startingAfter,userLinkRef:i.userLinkRef,status:i.status}),n,p=>wt(p,Lr))},createRefund(i){let p={paymentId:i.paymentId};return i.amount!==void 0&&(p.amount=i.amount),i.reason!==void 0&&(p.reason=i.reason),i.merchantRefundRef!==void 0&&(p.merchantRefundRef=i.merchantRefundRef),de(e,"/api/merchant/refunds",p,n,Pt,{"Idempotency-Key":i.idempotencyKey},[402])},getRefund(i){return te(e,`/api/merchant/refunds/${encodeURIComponent(i)}`,n,Pt)},listRefunds(i={}){return te(e,_t("/api/merchant/refunds",{limit:i.limit,startingAfter:i.startingAfter,paymentId:i.paymentId}),n,p=>wt(p,Pt))},createWebhookEndpoint(i){return de(e,"/api/merchant/webhook-endpoints",{url:i.url,enabledEvents:i.enabledEvents},n,Ur)},listWebhookEndpoints(){return te(e,"/api/merchant/webhook-endpoints",n,i=>{let g=L(i).data;if(!Array.isArray(g))throw new Error("expected data array");return g.map(It)})},getWebhookEndpoint(i){return te(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(i)}`,n,It)},deleteWebhookEndpoint(i){return Mr(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(i)}`,n)},rotateWebhookSecret(i){return de(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(i)}/rotate-secret`,{},n,Ur)},getDevCapabilities(){return Nn(e,"getDevCapabilities"),te(e,"/api/dev/capabilities",n,Ji)},fundDevUser(i){return Nn(e,"fundDevUser"),jr(i.userLinkRef),Nr(i.amount),Dr(i.idempotencyKey),de(e,"/api/dev/faucet/usdc",{userLinkRef:i.userLinkRef,amount:i.amount},n,Xi,{"Idempotency-Key":i.idempotencyKey})},simulateDevCharge(i){return Nn(e,"simulateDevCharge"),jr(i.userLinkRef),i.cardRef!==void 0&&xe(i.cardRef,"card_","cardRef"),Nr(i.amount),Di(i.scenario),i.merchantReference!==void 0&&(typeof i.merchantReference!="string"||i.merchantReference.length>120)&&P("merchantReference must not exceed 120 characters"),Dr(i.idempotencyKey),de(e,"/api/dev/simulate/charge",{userLinkRef:i.userLinkRef,...i.cardRef===void 0?{}:{cardRef:i.cardRef},amount:i.amount,scenario:i.scenario,...i.merchantReference===void 0?{}:{merchantReference:i.merchantReference}},n,qr,{"Idempotency-Key":i.idempotencyKey})},getDevSimulation(i){return Nn(e,"getDevSimulation"),xe(i,"sim_","simulationId"),te(e,`/api/dev/simulations/${encodeURIComponent(i)}`,n,qr)},sendWebhookTestDelivery(i){return ji(e),Ni(i.webhookEndpointId),i.message!==void 0&&(typeof i.message!="string"||i.message.length>120)&&P("webhook test message must not exceed 120 characters"),de(e,`/api/merchant/webhook-endpoints/${encodeURIComponent(i.webhookEndpointId)}/test-delivery`,i.message===void 0?{}:{message:i.message},n,Zi)}}}var Ti=new Set(["declined","succeeded","paid_via_coverage","failed","canceled"]);function Ai(t){return Ti.has(t)}async function Oi(t,e,n={}){let r=Math.max(0,n.initialIntervalMs??1e3),o=Math.max(r,n.maxIntervalMs??8e3),a=n.backoffFactor??1.5,s=n.timeoutMs??3e5,d=n.signal,u=Date.now()+s,l=r,i;for(;;){bi(d);let p=await t();if(p.status!==i&&(i=p.status,e(p)),Ai(p.status))return p;let g=u-Date.now();if(g<=0)return p;await ki(Math.min(l,g),d),l=Math.min(l*a,o)}}function bi(t){if(t?.aborted)throw new Ee("FACTO_STATUS_POLL_ABORTED","mandate payment polling aborted",{retryable:!1})}function ki(t,e){return new Promise((n,r)=>{let o=setTimeout(()=>{e?.removeEventListener("abort",a),n()},t),a=()=>{clearTimeout(o),r(new Ee("FACTO_STATUS_POLL_ABORTED","mandate payment polling aborted",{retryable:!1}))};if(e){if(e.aborted){clearTimeout(o),a();return}e.addEventListener("abort",a,{once:!0})}})}var xi=Object.freeze(["dev","production","sandbox"]);function At(t){t.appId||P("appId is required"),t.clientId||P("clientId is required"),t.clientSecret||P("clientSecret is required");let e=t.environment;e!==void 0&&!xi.includes(e)&&P("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&&P("provide either transport or fetch, not both"),t.timeoutMs!==void 0&&(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<=0)&&P("timeoutMs must be a positive safe integer");let n=t.apiBaseUrl?ze(t.apiBaseUrl,St,"apiBaseUrl",!1):void 0,r=t.hostedConnectUrl?ze(t.hostedConnectUrl,ln,"hostedConnectUrl",!0):void 0;n!==void 0&&r!==void 0&&n!==r&&P("apiBaseUrl and hostedConnectUrl target different Facto environments");let o=Pi(t.clientId),a=e??o??n??r;a===void 0&&P("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 s=Un(a);e!==void 0&&o!==void 0&&o!==s&&P(`environment '${e}' conflicts with the clientId keyspace, which is ${o} material`);for(let i of[n,r])i!==void 0&&i!==s&&P("environment selector conflicts with a published Facto endpoint");let d=Tt(t.apiBaseUrl??St[s]),u=Tt(t.hostedConnectUrl??ln[s]),l=ze(d,St,"apiBaseUrl",!1);return ze(u,ln,"hostedConnectUrl",!0),Mi(t.clientId,l),{appId:t.appId,clientId:t.clientId,clientSecret:t.clientSecret,environment:a,apiBaseUrl:d,hostedConnectUrl:u,transport:t.transport??t.fetch??((i,p)=>globalThis.fetch(i,p)),...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.retry===void 0?{}:{retry:t.retry},...t.signal===void 0?{}:{signal:t.signal}}}function Nn(t,e){Un(t.environment)!=="dev"&&P(`${e} is available only in the sandbox/dev environment`)}function ji(t){Un(t.environment)!=="dev"&&P("sendWebhookTestDelivery is available only in the sandbox/dev environment")}function xe(t,e,n){(typeof t!="string"||!new RegExp(`^${e}[A-Za-z0-9_-]+$`).test(t))&&P(`${n} must be an opaque ${e} reference`)}function jr(t){xe(t,"ul_","userLinkRef")}function Ni(t){(typeof t!="string"||!/^we_[A-Za-z0-9]+$/.test(t))&&P("webhookEndpointId must be an opaque we_ reference")}function Nr(t){(typeof t!="object"||t===null||t.currency!=="USDC"||typeof t.amount!="string"||!/^[0-9]+(?:\.[0-9]{1,6})?$/.test(t.amount))&&P("Dev amount must be a USDC decimal with at most six fractional digits")}function Di(t){(typeof t!="string"||!Wr.includes(t))&&P("unknown Dev simulation scenario")}function Dr(t){(typeof t!="string"||t.trim()!==t||t.length<16||t.length>255)&&P("idempotencyKey must be 16 to 255 non-whitespace-trimmed characters")}function Mi(t,e){let n=e==="dev",r=e==="production";t.startsWith("dev_")&&e!==void 0&&!n&&P("a dev credential can target only the sandbox/dev environment"),(n||r)&&(t.startsWith("staging_")||t.startsWith("test_")||t.startsWith("lab_")||t.startsWith("sandbox_"))&&P("internal or legacy (staging_/test_/lab_/sandbox_) credentials cannot target a published Facto environment")}function ze(t,e,n,r){let o;try{o=new URL(t)}catch{P(`${n} must be an absolute URL`)}let a=o.hostname.toLowerCase().replace(/\.$/,"");for(let s of["dev","production"]){let d=new URL(e[s]);if(a!==d.hostname.toLowerCase())continue;let u=o.pathname==="/"||r&&o.pathname==="/connect";return(o.origin!==d.origin||o.username!==""||o.password!==""||!u||o.search!==""||o.hash!=="")&&P(`${n} is not the exact published ${s} endpoint`),s}}async function de(t,e,n,r,o,a={},s=[]){return Br(t,()=>bt(t,`${t.apiBaseUrl}${e}`,{method:"POST",headers:{authorization:r,"content-type":"application/json",...a},body:JSON.stringify(n)},async d=>{if(!d.ok&&!s.includes(d.status))throw await Ot(d);return zr(d,o)}),a["Idempotency-Key"]!==void 0)}async function te(t,e,n,r){return Br(t,()=>bt(t,`${t.apiBaseUrl}${e}`,{method:"GET",headers:{authorization:n}},async o=>{if(!o.ok)throw await Ot(o);return zr(o,r)}),!0)}async function zr(t,e){try{return e(await t.json())}catch(n){throw new Ee("FACTO_ENGINE_RESPONSE_INVALID","Facto Engine returned an invalid response",{retryable:!1,details:n})}}async function Mr(t,e,n){return bt(t,`${t.apiBaseUrl}${e}`,{method:"DELETE",headers:{authorization:n}},async r=>{if(!r.ok)throw await Ot(r)})}async function Ot(t){return new Ee("FACTO_ENGINE_REQUEST_FAILED",`Facto Engine request failed with status ${t.status}`,{retryable:t.status===429||t.status>=500,status:t.status,details:await ja(t),retryAfterSeconds:jt(t)})}function Br(t,e,n){return n?qn(e,{...t.retry,signal:t.signal??t.retry?.signal}):e()}async function bt(t,e,n,r){return t.timeoutMs===void 0&&t.signal===void 0?r(await t.transport(e,n)):Ui(t,e,n,r)}function Ui(t,e,n,r){let o=new AbortController;return t.signal?.aborted?Promise.reject(new Ee("FACTO_REQUEST_ABORTED","Facto Engine request aborted",{retryable:!1})):new Promise((a,s)=>{let d=!1,u,l=()=>{u!==void 0&&clearTimeout(u),t.signal?.removeEventListener("abort",p)},i=g=>{d||(d=!0,l(),s(new Ee("FACTO_REQUEST_ABORTED",g,{retryable:!1})),o.abort())},p=()=>i("Facto Engine request aborted");t.signal?.addEventListener("abort",p,{once:!0}),t.timeoutMs!==void 0&&(u=setTimeout(()=>i("Facto Engine request timed out"),t.timeoutMs)),(async()=>{try{let g=await t.transport(e,{...n,signal:o.signal});if(d){g.body?.cancel().catch(()=>{});return}let v=await r(g);d||(d=!0,l(),a(v))}catch(g){d||(d=!0,l(),s(g))}})()})}function _t(t,e){let n=new URLSearchParams;for(let[o,a]of Object.entries(e))a!==void 0&&a!==""&&n.set(o,String(a));let r=n.toString();return r?`${t}?${r}`:t}function wt(t,e){let n=L(t),r=n.data;if(!Array.isArray(r))throw new Error("expected data array");return{data:r.map(e),hasMore:We(n,"hasMore")}}var qi=["pending","succeeded","failed"],$i=["requested_by_customer","duplicate","fraudulent","other"];function Ki(t,e){let n=t[e];if(typeof n!="string"||!qi.includes(n))throw new Error(`expected refund status at ${e}`);return n}function Li(t,e){let n=t[e];if(n!==void 0){if(typeof n!="string"||!$i.includes(n))throw new Error(`expected refund reason at ${e}`);return n}}function Pt(t){let e=L(t),n=Li(e,"reason"),r=re(e,"merchantRefundRef");return{refundId:C(e,"refundId"),paymentId:C(e,"paymentId"),status:Ki(e,"status"),amount:C(e,"amount"),currency:C(e,"currency"),...n===void 0?{}:{reason:n},...r===void 0?{}:{merchantRefundRef:r},createdAt:C(e,"createdAt")}}var Fi=["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 zi(t,e){let n=t[e];if(!Array.isArray(n))throw new Error(`expected event-type array at ${e}`);return n.map(r=>{if(typeof r!="string"||!Fi.includes(r))throw new Error(`unknown webhook event type: ${String(r)}`);return r})}function It(t){let e=L(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:zi(e,"enabledEvents"),status:n,createdAt:C(e,"createdAt")}}function Ur(t){let e=It(t),n=L(t);return{...e,secret:C(n,"secret")}}var Mn=["fixtures","synthetic_identity","faucet","simulation","money_loop","webhook_test_delivery"],Bi=["unavailable","degraded","ready"],Wi=["contract","implemented","deployed","verified"],Wr=["approved","declined_setup","declined_limit","payment_failed"],Vi=["pre_admission","onchain_test_assets"],Hi=["accepted","processing","succeeded","failed","declined"],Gi=["accepted","broadcast","confirmed","failed"];function Ji(t){let e=L(t),n=e.capabilities;if(!Array.isArray(n)||n.length!==Mn.length)throw new Error("expected exactly six Dev capabilities");let r=n.map(Qi),o=new Set(r.map(a=>a.name));if(o.size!==Mn.length)throw new Error("expected each Dev capability exactly once");for(let a of Mn)if(!o.has(a))throw new Error(`missing Dev capability: ${a}`);return{environment:mn(e,"environment","dev"),contractVersion:mn(e,"contractVersion","2026-07-09"),capabilities:r,checkedAt:C(e,"checkedAt")}}function Qi(t){let e=L(t),n=Q(e,"name",Mn,"Dev capability name"),r=Q(e,"status",Bi,"Dev capability status"),o=Q(e,"evidenceLevel",Wi,"Dev evidence level"),a=Be(e,"reasonCode"),s=Be(e,"verifiedAt");if(r==="ready"&&(o!=="verified"||s===null))throw new Error("ready Dev capability requires verified evidence");let d=ea(e,"limits");return{name:n,status:r,evidenceLevel:o,...a===void 0?{}:{reasonCode:a},...s===void 0?{}:{verifiedAt:s},...d===void 0?{}:{limits:d}}}function Yi(t){let e=L(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:mn(e,"currency","USDC")}}function Xi(t){let e=L(t);return{faucetTransferId:pn(e,"faucetTransferId","sft_"),userLinkRef:pn(e,"userLinkRef","ul_"),amount:Yi(e.amount),status:Q(e,"status",Gi,"Dev faucet status"),createdAt:C(e,"createdAt")}}function qr(t){let e=L(t);return{simulationId:pn(e,"simulationId","sim_"),scenario:Q(e,"scenario",Wr,"Dev scenario"),executionMode:Q(e,"executionMode",Vi,"Dev execution mode"),status:Q(e,"status",Hi,"Dev simulation status"),reasonCode:vt(e,"reasonCode"),authorizationRef:vt(e,"authorizationRef"),chargeRef:vt(e,"chargeRef"),createdAt:C(e,"createdAt"),updatedAt:C(e,"updatedAt")}}function Zi(t){let e=L(t);return{eventId:$r(e,"eventId","evt_"),deliveryId:$r(e,"deliveryId","wd_"),status:mn(e,"status","queued"),createdAt:C(e,"createdAt")}}function ea(t,e){if(t[e]===void 0)return;let n=L(t[e]);for(let r of Object.values(n))if(r!==null&&typeof r!="string"&&typeof r!="number"&&typeof r!="boolean")throw new Error(`expected scalar Dev limit at ${e}`);return n}function pn(t,e,n){let r=C(t,e);if(!new RegExp(`^${n}[A-Za-z0-9_-]+$`).test(r))throw new Error(`expected opaque ${e}`);return r}function $r(t,e,n){let r=C(t,e);if(!new RegExp(`^${n}[A-Za-z0-9]+$`).test(r))throw new Error(`expected opaque ${e}`);return r}function na(t,e){return e.userLinkRef===void 0&&e.factoServerWalletAddress===void 0&&P("payment readiness requires userLinkRef, factoServerWalletAddress, or both"),e.userLinkRef!==void 0&&xe(e.userLinkRef,"ul_","userLinkRef"),e.factoServerWalletAddress!==void 0&&typeof e.factoServerWalletAddress!="string"&&P("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 ye(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 ta(t){let e=L(t),n=ye(e,"cardRef"),r=ye(e,"factoUserId"),o=ye(e,"factoServerWalletAddress");if(n!=null&&(xe(n,"card_","cardRef"),r!=null||o!=null))throw new Error("synthetic Dev links must not expose canonical identity");return{appId:C(e,"appId"),userLinkRef:pn(e,"userLinkRef","ul_"),grantStatus:C(e,"grantStatus"),pipelineReady:We(e,"pipelineReady"),scopes:ka(e,"scopes"),...n===void 0?{}:{cardRef:n},...r===void 0?{}:{factoUserId:r},...o===void 0?{}:{factoServerWalletAddress:o}}}function ra(t){let e=L(t),n=We(e,"pipelineReady"),r=e.notReadyReason,o=r==null?r:Q(e,"notReadyReason",Dt,"payment readiness not-ready reason");if(n&&o!==void 0&&o!==null)throw new Error("expected notReadyReason only when pipelineReady is false");let a=ye(e,"factoUserId"),s=ye(e,"factoServerWalletAddress");return xa(e,"payment readiness"),{appId:C(e,"appId"),userLinkRef:pn(e,"userLinkRef","ul_"),readinessScope:Q(e,"readinessScope",Mt,"payment readiness scope"),chainId:Hr(e,"chainId"),protocolId:C(e,"protocolId"),assetSymbol:C(e,"assetSymbol"),spendMode:C(e,"spendMode"),pipelineReady:n,...o===void 0?{}:{notReadyReason:o},...a===void 0?{}:{factoUserId:a},...s===void 0?{}:{factoServerWalletAddress:s}}}function oa(t){let e=L(t);return{sessionId:C(e,"sessionId"),checkoutUrl:C(e,"checkoutUrl"),status:mn(e,"status","pending"),amount:C(e,"amount"),assetSymbol:C(e,"assetSymbol"),orderRef:Be(e,"orderRef")}}function ia(t){let e=L(t);return{sessionId:C(e,"sessionId"),status:wa(e,"status"),amount:C(e,"amount"),assetSymbol:C(e,"assetSymbol"),orderRef:Be(e,"orderRef"),chargeId:Be(e,"chargeId"),confirmedAt:Be(e,"confirmedAt")}}function Kr(t){let e=L(t),n=re(e,"mandateId"),r=re(e,"userLinkRef");return{sessionId:C(e,"sessionId"),authorizationUrl:C(e,"authorizationUrl"),status:Ta(e,"status"),...n===void 0?{}:{mandateId:n},...r===void 0?{}:{userLinkRef:r},expiresAt:C(e,"expiresAt"),state:C(e,"state")}}function Lr(t){let e=L(t),n=re(e,"expiresAt");return{mandateId:C(e,"mandateId"),appId:C(e,"appId"),status:Ia(e,"status"),allowedUseCases:ba(e,"allowedUseCases"),limits:ma(e.limits),paymentPath:fa(e.paymentPath),createdAt:C(e,"createdAt"),...n===void 0?{}:{expiresAt:n}}}var aa="direct",sa="defaultPaymentOptionId";function ca(t){let e=L(t);Jr(e,"payment options");let n=e.paymentOptions;if(!Array.isArray(n))throw new Error("expected paymentOptions array");let r=n.map(la).filter(s=>s.settlementPath===aa),o=Ra(e,sa),a=da(r,o);return{paymentOptions:r,...a===void 0?{}:{selectedPaymentOptionId:a}}}function da(t,e){return e!==void 0&&t.some(r=>r.paymentOptionId===e)?e:(t.find(r=>r.ready)??t[0])?.paymentOptionId}function ua(t){let e=re(t,"settlementPath"),n=re(t,"spendMode"),r=e??n;if(r===void 0)throw new Error("expected settlementPath or the deprecated spendMode on a payment option");return{settlementPath:r,spendMode:n??r}}function la(t){let e=L(t);Jr(e,"payment option");let n=re(e,"blockingReason"),r=ye(e,"balanceStatus"),o=ye(e,"holdingBalance"),a=ye(e,"availableBalance"),s=ha(e,"assetDecimals"),d=C(e,"assetSymbol"),u=C(e,"chainLabel"),l=C(e,"protocolLabel"),{settlementPath:i,spendMode:p}=ua(e);return{paymentOptionId:Vr(e,"paymentOptionId"),label:pa({assetSymbol:d,protocolLabel:l,chainLabel:u},C(e,"label")),ready:We(e,"ready"),isDefault:We(e,"isDefault"),chainId:Hr(e,"chainId"),chainLabel:u,protocolLabel:l,assetSymbol:d,spendMode:p,settlementPath:i,...n===void 0?{}:{blockingReason:n},...r===void 0?{}:{balanceStatus:r},...o===void 0?{}:{holdingBalance:o},...a===void 0?{}:{availableBalance:a},...s===void 0?{}:{assetDecimals:s}}}function pa(t,e){let n=[t.assetSymbol,t.protocolLabel,t.chainLabel].map(r=>r.trim()).filter(r=>r.length>0);return n.length>0?n.join(" \xB7 "):e}function Dn(t){let e=L(t),n=re(e,"amountRefunded"),r=ye(e,"subMerchantRef"),o=ye(e,"subMerchantDisplayName"),a=re(e,"chargeId"),s=re(e,"txHash"),d=Oa(e,"declineReason"),u=ya(e,"finalityEtaSeconds"),l=re(e,"terminalAt"),i=re(e,"updatedAt");return{paymentId:C(e,"paymentId"),mandateId:C(e,"mandateId"),merchantPaymentRef:C(e,"merchantPaymentRef"),status:Aa(e,"status"),amount:C(e,"amount"),...n===void 0?{}:{amountRefunded:n},currency:C(e,"currency"),useCase:Pa(e,"useCase"),...r===void 0?{}:{subMerchantRef:r},...o===void 0?{}:{subMerchantDisplayName:o},...a===void 0?{}:{chargeId:a},...s===void 0?{}:{txHash:s},...d===void 0?{}:{declineReason:d},...u===void 0?{}:{finalityEtaSeconds:u},...l===void 0?{}:{terminalAt:l},createdAt:C(e,"createdAt"),...i===void 0?{}:{updatedAt:i}}}function ma(t){let e=L(t);return{perTxAmount:C(e,"perTxAmount"),periodAmount:C(e,"periodAmount"),period:va(e,"period")}}function fa(t){let e=L(t),n=re(e,"blockingReason");return{ready:We(e,"ready"),summary:C(e,"summary"),...n===void 0?{}:{blockingReason:n}}}function L(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 re(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 Vr(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 Ra(t,e){if(!(t[e]===void 0||t[e]===null))return Vr(t,e)}function mn(t,e,n){if(t[e]!==n)throw new Error(`expected ${n} at ${e}`);return n}function We(t,e){let n=t[e];if(typeof n!="boolean")throw new Error(`expected boolean at ${e}`);return n}function Hr(t,e){let n=t[e];if(typeof n!="number"||!Number.isFinite(n))throw new Error(`expected finite number at ${e}`);return n}function ya(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}}function ha(t,e){let n=t[e];if(n==null)return n;if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new Error(`expected non-negative integer or null at ${e}`);return n}var ga=["pending","charged","expired","cancelled"],Gr=["immediate","recurring","top_up","metered"],Ea=["daily","weekly","monthly"],Ca=["pending","active","paused","revoked","expired","suspended"],Sa=["created","authorized","declined","expired"],_a=["accepted","declined","charging","finalizing","succeeded","paid_via_coverage","failed","canceled"];function wa(t,e){let n=t[e];if(typeof n!="string"||!ga.includes(n))throw new Error(`expected checkout status at ${e}`);return n}function Pa(t,e){return Q(t,e,Gr,"mandate use case")}function va(t,e){return Q(t,e,Ea,"mandate limit period")}function Ia(t,e){return Q(t,e,Ca,"mandate status")}function Ta(t,e){return Q(t,e,Sa,"mandate authorization status")}function Aa(t,e){return Q(t,e,_a,"mandate payment status")}function Oa(t,e){if(t[e]!==void 0)return Q(t,e,Nt,"mandate decline reason")}function ba(t,e){let n=t[e];if(!Array.isArray(n))throw new Error(`expected mandate use case array at ${e}`);return n.map(r=>{if(typeof r!="string"||!Gr.includes(r))throw new Error(`expected mandate use case array at ${e}`);return r})}function Q(t,e,n,r){let o=t[e];if(typeof o!="string"||!n.includes(o))throw new Error(`expected ${r} at ${e}`);return o}function Be(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 vt(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 ka(t,e){let n=t[e];if(!Array.isArray(n)||n.some(r=>typeof r!="string"))throw new Error(`expected string array at ${e}`);return n}function xa(t,e){let r=["pipelineId","selectedPipelineId","paymentRouteId","routeId","routeSelector"].find(o=>t[o]!==void 0);if(r)throw new Error(`unsafe ${e} field: ${r}`)}function Jr(t,e){let r=["userId","factoUserId","cardId","routeId","vaultKind","serverWallet","factoServerWalletAddress","pathSnapshot","paymentPathSnapshot","pipelineId","selectedPipelineId","paymentRouteId","routeSelector"].find(o=>t[o]!==void 0);if(r)throw new Error(`unsafe ${e} field: ${r}`)}async function ja(t){try{return await t.json()}catch{return await t.text().catch(()=>null)}}function Tt(t){return t.replace(/\/+$/,"")}function Na(t){let e;try{e=new URL(t)}catch{P("merchantOrigin must be an absolute http(s) origin")}e.protocol!=="http:"&&e.protocol!=="https:"&&P("merchantOrigin must be an absolute http(s) origin");let n=e.origin;return t!==n&&t!==`${n}/`&&P("merchantOrigin must be an absolute http(s) origin"),n}function P(t){throw new Ee("FACTO_CONFIG_INVALID",t,{retryable:!1})}function kt(t){let e=globalThis.btoa;if(e)return e(t);let n=globalThis.Buffer;if(n)return n.from(t).toString("base64");P("No base64 encoder is available in this runtime")}function os(t,e,n=Math.floor(Date.now()/1e3)){e||P("webhook secret is required"),(!Number.isSafeInteger(n)||n<0)&&P("webhook timestamp must be a non-negative safe integer");let r=Fr("sha256",e).update(`${n}.`).update(t).digest("hex");return`t=${n},v1=${r}`}function is(t,e,n,r=300){n||P("webhook secret is required");let o=e.split(",").map(u=>u.trim()),a,s=[];for(let u of o){let l=u.indexOf("=");if(l===-1)continue;let i=u.slice(0,l),p=u.slice(l+1);i==="t"?a=Number(p):i==="v1"&&s.push(p)}if(a===void 0||!Number.isFinite(a)||Math.abs(Date.now()/1e3-a)>r||s.length===0)return!1;let d=Fr("sha256",n).update(`${a}.`).update(t).digest();return s.some(u=>{let l;try{l=Buffer.from(u,"hex")}catch{return!1}return l.length===d.length&&_i(l,d)})}function ss(t){let e=At(t),n=`Basic ${kt(`${e.clientId}:${e.clientSecret}`)}`,r={appId:e.appId,environment:e.environment,apiBaseUrl:e.apiBaseUrl,authorizationHeader:n,transport:e.transport,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.signal===void 0?{}:{signal:e.signal},store:t.store,ownerScope:t.ownerScope,getCallerContext:t.getCallerContext};return yr(r)}function ds(t){let e=At(t);return Er({appId:e.appId,apiBaseUrl:e.apiBaseUrl,authorizationHeader:`Basic ${kt(`${e.clientId}:${e.clientSecret}`)}`,transport:e.transport,getHostContext:t.getHostContext,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.signal===void 0?{}:{signal:e.signal}})}var us=Ii;export{Ln as CARD_INTENT_JWKS_PATH,Qn as ENTERPRISE_ASSET_KINDS,Cr as ENTERPRISE_AUDIENCE_READ_ROUTE_TEMPLATES,at as ENTERPRISE_AUTH_REVOKED_ERROR_CODES,en as ENTERPRISE_BUSINESS_PROGRESS_UNKNOWN_REASONS,Gn as ENTERPRISE_CLOSURE_TARGET_TABLES,_n as ENTERPRISE_COMMAND_KINDS,Ze as ENTERPRISE_COMMAND_PROTOCOL_V1,rn as ENTERPRISE_COMMAND_UNKNOWN_REASONS,it as ENTERPRISE_COMMERCIAL_REDUCTION_COVERAGES,Hn as ENTERPRISE_COMMERCIAL_REDUCTION_REF_PREFIX_V1,ot as ENTERPRISE_CONSUMER_EXECUTION_STATES,st as ENTERPRISE_DETERMINISTIC_ERROR_CODES,Ue as ENTERPRISE_FULFILLMENT_QUALIFICATIONS,tn as ENTERPRISE_GUARANTEE_PROGRESS_STATES,rt as ENTERPRISE_GUARANTEE_STATES,Xt as ENTERPRISE_KIND_TO_TARGET_TABLE,sn as ENTERPRISE_MERCHANT_COMMAND_ROUTE_TEMPLATES,Yt as ENTERPRISE_MERCHANT_RECOVERY_ROUTE_TEMPLATE,Pn as ENTERPRISE_OPERATION_UNKNOWN_REASONS,Oe as ENTERPRISE_PARTNER_CAPTURE_PAYOUT_PROGRESS_STATES,tt as ENTERPRISE_PARTNER_FACT_KINDS,Xn as ENTERPRISE_PRODUCER_KINDS,$o as ENTERPRISE_PUBLIC_MERCHANT_COMMAND_KINDS,Vn as ENTERPRISE_SCOPE_REF_PREFIX_V1,Wt as ENTERPRISE_SERVER_DERIVED_COMMAND_KINDS,nn as ENTERPRISE_SOURCE_EXECUTION_PROGRESS_STATES,Yn as ENTERPRISE_SOURCE_PROTOCOLS,nt as ENTERPRISE_TARGET_GUARANTEE_STATES,Zn as ENTERPRISE_TARGET_HOLD_STATES,et as ENTERPRISE_TERMINAL_HOLD_STATES,Jn as ENTERPRISE_TRACKED_UNKNOWN_REASONS,ee as EnterpriseJournalAccessDeniedError,pe as EnterpriseJournalConflictError,T as EnterpriseJournalIntegrityError,Ae as EnterpriseJournalStoreError,_ as EnterpriseJournalValidationError,c as EnterpriseWireValidationError,St as FACTO_CONNECT_API_BASE_URLS,ln as FACTO_CONNECT_HOSTED_URLS,Ee as FactoConnectServerError,w as FactoIntentTokenError,Qt as MAX_UINT256_DECIMAL,Eo as PSP_CAPABILITY_TEMPLATES,So as PSP_CREDENTIAL_KEYSPACE,Kt as PSP_CREDENTIAL_SCOPES,_o as PSP_PARTNER_ROLE_TYPE,li as buildAudienceReadPath,vi as buildHostedConnectUrl,nr as buildMerchantCommandPath,tr as buildMerchantRecoveryPath,$e as canonicalizeAndMapEnterpriseCommand,Co as carriesMoneyVerb,be as computeEnterpriseScopeRef,Zt as coreDigestToWireDigest,ss as createEnterpriseFundsClient,ss as createEnterpriseFundsServerClient,ds as createEnterprisePurchaseServerClient,Ii as createFactoConnectServer,cn as decodeCanonicalCommandFromEnvelope,us as default,rr as deriveCommercialReductionRef,vn as encodeCanonicalUtf8Bytes,bn as evaluateMerchantWireResponseAgainstEnvelope,Pi as factoConnectEnvironmentFromClientId,wn as isServerDerivedEnterpriseCommandKind,Ai as isTerminalMandatePaymentStatus,On as parseAuthRevokedErrorResponse,pr as parseCommandUnknownRecoveryResponse,Or as parseConsoleCommandReceipt,br as parseConsoleCommandRecoveryResponse,kr as parseConsoleCommandUnknownRecoveryResponse,xn as parseConsoleOrderProjection,Ar as parseConsoleProjectionResponse,gt as parseConsumerBusinessProgress,Ir as parseConsumerOperationRecoveryResponse,Tr as parseConsumerOperationUnknownRecoveryResponse,kn as parseConsumerOrderProjection,vr as parseConsumerProjectionResponse,mr as parseDeterministicCommandErrorResponse,fr as parseInfrastructureUnavailableResponse,cr as parseMerchantCommandEnvelopeResponse,dr as parseMerchantCommandRecoveryResponse,ur as parseMerchantCommercialReductionEnvelopeResponse,lr as parseMerchantCommercialReductionRecoveryResponse,ar as parseMerchantS2sCollectedFeeEffect,sr as parseMerchantS2sCommercialReduction,mt as parseMerchantS2sCommercialReductionProjection,Ke as parseMerchantS2sOrderProjection,or as parsePartnerBusinessProgress,wr as parsePartnerOperationRecoveryResponse,Pr as parsePartnerOperationUnknownRecoveryResponse,_r as parsePartnerProjectionResponse,Si as readConsoleCommandResult,Ci as readConsoleProjectionResult,Ei as readConsumerOperationResult,gi as readConsumerProjectionResult,hi as readPartnerOperationResult,yi as readPartnerProjectionResult,an as serializeCanonicalJson,os as signWebhookPayload,Po as subMerchantOf,In as validateAndNormalizeS2sOwnerScope,to as verifyCardIntentToken,is as verifyWebhookSignature,dt as wireDigestToCoreDigest,qn as withServerRetry,wo as withSubMerchant};