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