@devlab.group/agent-commerce 2.4.1 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/README.md +115 -15
  2. package/dist/ap2.d.ts +24 -12
  3. package/dist/ap2.js +31 -13
  4. package/dist/ap2.js.map +1 -1
  5. package/dist/{chunk-DTKU3Z2M.js → chunk-3OTCFFFT.js} +37 -4
  6. package/dist/chunk-3OTCFFFT.js.map +1 -0
  7. package/dist/{chunk-QPV3EGJO.js → chunk-4K7FIBJM.js} +25 -4
  8. package/dist/chunk-4K7FIBJM.js.map +1 -0
  9. package/dist/{chunk-CXWC5LWM.js → chunk-FKQK5XZA.js} +652 -68
  10. package/dist/chunk-FKQK5XZA.js.map +1 -0
  11. package/dist/chunk-GA3O2A7R.js +92 -0
  12. package/dist/chunk-GA3O2A7R.js.map +1 -0
  13. package/dist/{chunk-WZW5ORZH.js → chunk-VUCMBGUR.js} +3 -3
  14. package/dist/{chunk-WZW5ORZH.js.map → chunk-VUCMBGUR.js.map} +1 -1
  15. package/dist/cli/{ap2-GWSP4LYY.js → ap2-YAPLERSC.js} +34 -15
  16. package/dist/cli/ap2-YAPLERSC.js.map +1 -0
  17. package/dist/cli/{chunk-G2JEY7MB.js → chunk-2J2IQQ4X.js} +8 -7
  18. package/dist/cli/chunk-2J2IQQ4X.js.map +1 -0
  19. package/dist/cli/chunk-2UPPX3FJ.js +311 -0
  20. package/dist/cli/chunk-2UPPX3FJ.js.map +1 -0
  21. package/dist/cli/{chunk-WYOGIANL.js → chunk-4H2QLHQI.js} +4 -4
  22. package/dist/cli/{chunk-WYOGIANL.js.map → chunk-4H2QLHQI.js.map} +1 -1
  23. package/dist/cli/{chunk-OZ4LAWBK.js → chunk-5R7DM5LM.js} +25 -4
  24. package/dist/cli/chunk-5R7DM5LM.js.map +1 -0
  25. package/dist/cli/chunk-663ALDZA.js +92 -0
  26. package/dist/cli/chunk-663ALDZA.js.map +1 -0
  27. package/dist/cli/{chunk-QQ3WY5L3.js → chunk-IDY2735M.js} +36 -104
  28. package/dist/cli/chunk-IDY2735M.js.map +1 -0
  29. package/dist/cli/chunk-JFVRG2HH.js +107 -0
  30. package/dist/cli/chunk-JFVRG2HH.js.map +1 -0
  31. package/dist/cli/chunk-M7NXVRU5.js +8 -0
  32. package/dist/cli/{chunk-ITWNSS2B.js.map → chunk-M7NXVRU5.js.map} +1 -1
  33. package/dist/cli/chunk-NIU5EMSB.js +119 -0
  34. package/dist/cli/chunk-NIU5EMSB.js.map +1 -0
  35. package/dist/cli/{chunk-TNMLDPUO.js → chunk-QA2OPHBF.js} +655 -70
  36. package/dist/cli/chunk-QA2OPHBF.js.map +1 -0
  37. package/dist/cli/{chunk-GJIMDMYT.js → chunk-QLUCNPRT.js} +404 -161
  38. package/dist/cli/chunk-QLUCNPRT.js.map +1 -0
  39. package/dist/cli/chunk-SYQLJXIU.js +105 -0
  40. package/dist/cli/chunk-SYQLJXIU.js.map +1 -0
  41. package/dist/cli/{chunk-3MGAJ5FX.js → chunk-VJ4EO4LE.js} +3 -3
  42. package/dist/cli/{chunk-3MGAJ5FX.js.map → chunk-VJ4EO4LE.js.map} +1 -1
  43. package/dist/cli/{chunk-PIMFPCNZ.js → chunk-Z34UMZBB.js} +234 -85
  44. package/dist/cli/chunk-Z34UMZBB.js.map +1 -0
  45. package/dist/cli/config-BWFMN2ZB.js +12 -0
  46. package/dist/cli/{config-UI4EDG4L.js.map → config-BWFMN2ZB.js.map} +1 -1
  47. package/dist/cli/index.js +258 -11
  48. package/dist/cli/index.js.map +1 -1
  49. package/dist/cli/{mcp-PGBRWZVA.js → mcp-KZEMXLHR.js} +5 -4
  50. package/dist/cli/mcp-KZEMXLHR.js.map +1 -0
  51. package/dist/cli/{near-5AY3HWYF.js → near-U6365VFX.js} +15 -4
  52. package/dist/cli/near-U6365VFX.js.map +1 -0
  53. package/dist/cli/payment-providers-SZL36H3Y.js +6 -0
  54. package/dist/cli/payment-providers-SZL36H3Y.js.map +1 -0
  55. package/dist/cli/{provider-I2ESL6RS.js → provider-6TKB5ADJ.js} +26 -15
  56. package/dist/cli/provider-6TKB5ADJ.js.map +1 -0
  57. package/dist/cli/receipts-ZGLJWMQG.js +8 -0
  58. package/dist/cli/receipts-ZGLJWMQG.js.map +1 -0
  59. package/dist/cli/reconcile-IC22MJD5.js +4 -0
  60. package/dist/cli/reconcile-IC22MJD5.js.map +1 -0
  61. package/dist/cli/{run-JK4ERPJV.js → run-ZTYPQI4D.js} +151 -115
  62. package/dist/cli/run-ZTYPQI4D.js.map +1 -0
  63. package/dist/cli/svm-KDSPDFJG.js +48 -0
  64. package/dist/cli/svm-KDSPDFJG.js.map +1 -0
  65. package/dist/cli/{x402-7WBFZQXV.js → x402-WLYBLODI.js} +10 -9
  66. package/dist/cli/x402-WLYBLODI.js.map +1 -0
  67. package/dist/index.d.ts +112 -12
  68. package/dist/index.js +948 -157
  69. package/dist/index.js.map +1 -1
  70. package/dist/mcp.d.ts +1 -2
  71. package/dist/mcp.js +1 -1
  72. package/dist/mpp.js +20 -10
  73. package/dist/mpp.js.map +1 -1
  74. package/dist/{near-D6C42VPE.js → near-FH7HPZV3.js} +15 -4
  75. package/dist/near-FH7HPZV3.js.map +1 -0
  76. package/dist/{protocol-adapter-C9odYl6l.d.ts → protocol-adapter-DEXpdp8m.d.ts} +102 -48
  77. package/dist/{runtime-Cl_BLVZV.d.ts → runtime-Dz2fSO-P.d.ts} +220 -2
  78. package/dist/svm-KNC3PHMS.js +48 -0
  79. package/dist/svm-KNC3PHMS.js.map +1 -0
  80. package/dist/x402.js +5 -5
  81. package/package.json +1 -1
  82. package/dist/authorization-DjAecwuW.d.ts +0 -115
  83. package/dist/chunk-CXWC5LWM.js.map +0 -1
  84. package/dist/chunk-DTKU3Z2M.js.map +0 -1
  85. package/dist/chunk-KA2AX5FH.js +0 -44
  86. package/dist/chunk-KA2AX5FH.js.map +0 -1
  87. package/dist/chunk-QPV3EGJO.js.map +0 -1
  88. package/dist/cli/ap2-GWSP4LYY.js.map +0 -1
  89. package/dist/cli/chunk-G2JEY7MB.js.map +0 -1
  90. package/dist/cli/chunk-GJIMDMYT.js.map +0 -1
  91. package/dist/cli/chunk-ITWNSS2B.js +0 -8
  92. package/dist/cli/chunk-OSTCU6ZK.js +0 -44
  93. package/dist/cli/chunk-OSTCU6ZK.js.map +0 -1
  94. package/dist/cli/chunk-OZ4LAWBK.js.map +0 -1
  95. package/dist/cli/chunk-PIMFPCNZ.js.map +0 -1
  96. package/dist/cli/chunk-QQ3WY5L3.js.map +0 -1
  97. package/dist/cli/chunk-TNMLDPUO.js.map +0 -1
  98. package/dist/cli/config-UI4EDG4L.js +0 -11
  99. package/dist/cli/mcp-PGBRWZVA.js.map +0 -1
  100. package/dist/cli/near-5AY3HWYF.js.map +0 -1
  101. package/dist/cli/provider-I2ESL6RS.js.map +0 -1
  102. package/dist/cli/run-JK4ERPJV.js.map +0 -1
  103. package/dist/cli/svm-3MMYFPC7.js +0 -33
  104. package/dist/cli/svm-3MMYFPC7.js.map +0 -1
  105. package/dist/cli/x402-7WBFZQXV.js.map +0 -1
  106. package/dist/near-D6C42VPE.js.map +0 -1
  107. package/dist/svm-QEUAUNPQ.js +0 -33
  108. package/dist/svm-QEUAUNPQ.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/execution/settlement-order.ts","../../src/payments/x402/networks.ts","../../src/core/canonical-json.ts","../../src/payments/x402/addresses.ts","../../src/payments/x402/payment-flow.ts","../../src/payments/x402/local-chain/accounts.ts"],"names":[],"mappings":";;;AAIO,IAAM,iCAAA,GAAoC;AAQ1C,IAAM,yCAAA,GAA4C;;;ACKlD,IAAM,cAAA,GAAiB;AA0D9B,IAAM,IAAA,GAAO,CAAC,OAAA,EAAiB,IAAA,MAC5B,EAAE,MAAA,EAAQ,MAAA,EAAQ,OAAA,EAAS,IAAA,EAAM,OAAA,EAAS,GAAA,EAAK,QAAA,EAAU,CAAA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,MAAM,eAAe,KAAA,CAAM,MAAA,GAAS,MAAM,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA,CAAE,MAAA;AAC7D,EAAA,OAAO,YAAA,IAAgB,CAAA,KAAM,EAAA,GAAK,CAAA,GAAI,IAAA,CAAK,IAAA,CAAK,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,MAAA,GAAS,CAAC,CAAA,CAAA;AAC3E;;;ACvFO,IAAM,kBAAA,GAAqB,CAAC,eAAA,EAAiB,SAAS;AAItD,IAAM,yBAAA,GAA6C;;;ACSnD,IAAM,yBAAA,GAIT;AAAA,EACF;AAAA,IACE,OAAA,EAAS,4CAAA;AAAA,IACT,UAAA,EAAY;AAAA,GACd;AAAA,EACA;AAAA,IACE,OAAA,EAAS,4CAAA;AAAA,IACT,UAAA,EAAY;AAAA,GACd;AAAA,EACA;AAAA,IACE,OAAA,EAAS,4CAAA;AAAA,IACT,UAAA,EAAY;AAAA;AAEhB;AAEyC,0BAA0B,CAAC;AAC9B,0BAA0B,CAAC;AAC9B,0BAA0B,CAAC","file":"chunk-5R7DM5LM.js","sourcesContent":["/**\n * Set on a payment requirement to run the backend before settlement.\n * The pipeline settles first unless this metadata value is `true`.\n */\nexport const SETTLE_AFTER_BACKEND_METADATA_KEY = 'settleAfterBackend';\n\n/**\n * Set to `true` when the rail permits presenting an authorization again after\n * its attempt was rejected, which settled nothing; the chain still spends each\n * nonce once. The pipeline lets retries reclaim the rejected attempt;\n * otherwise, it refuses them as replays.\n */\nexport const REUSE_REJECTED_AUTHORIZATION_METADATA_KEY = 'reuseRejectedAuthorization';\n","/**\n * Network profiles: family, display name, environment, EVM chain ID and\n * default stablecoin. Config load rejects unknown IDs; parsing an EVM chain\n * ID cannot establish whether it is mainnet. Merchants must declare custom\n * EVM networks under `payments.x402.networks`; built-ins cannot be redeclared.\n *\n * Profiles copy SDK asset defaults to keep config load and the CLI SDK-free.\n * Tests compare each profile with the pinned SDK tables.\n *\n * The local Anvil chain has a profile of its own, `eip155:31337` (Anvil's\n * default chain id), so the network alone tells a local deployment from a\n * public one. Local health checks still require an Anvil response, because an\n * RPC endpoint can report any chain id.\n */\nimport { CommerceError } from '../../core';\n\n/** Chain id of the local Anvil dev chain, Anvil's default */\nexport const LOCAL_CHAIN_ID = 31337;\n\nexport type X402NetworkFamily = 'evm' | 'svm' | 'near';\n\nexport type NetworkKind = 'testnet' | 'mainnet';\n\n/** An EVM network the x402 provider can settle on */\nexport interface NetworkProfile {\n /** CAIP-2 identifier, e.g. `eip155:84532` */\n readonly id: string;\n /** Signed into the buyer's EIP-712 domain */\n readonly chainId: number;\n readonly displayName: string;\n readonly kind: NetworkKind;\n /** The local Anvil dev chain, where the in-process facilitator runs */\n readonly local?: boolean;\n /**\n * Default USDC deployment and EIP-712 domain. EVM offers may name another\n * token; the local chain has no default and requires explicit token metadata.\n *\n * `name` is the signed EIP-712 domain name, not the symbol, and deployments\n * differ: `\"USDC\"` on Base Sepolia, `\"USD Coin\"` on Base.\n */\n readonly canonicalAsset?: {\n readonly symbol: string;\n readonly address: string;\n readonly name: string;\n readonly version: string;\n readonly decimals: number;\n };\n}\n\ninterface NonEvmNetwork<F extends X402NetworkFamily> {\n readonly family: F;\n readonly id: string;\n readonly displayName: string;\n readonly kind: NetworkKind;\n /** Solana mint or NEAR NEP-141 contract account, with no EIP-712 domain */\n readonly canonicalAsset: {\n readonly symbol: string;\n readonly address: string;\n readonly decimals: number;\n };\n}\n\nexport type X402Network =\n | (NetworkProfile & { readonly family: 'evm' })\n | NonEvmNetwork<'svm'>\n | NonEvmNetwork<'near'>;\n\n/** A merchant-declared EVM network, from `payments.x402.networks` */\nexport interface CustomNetworkDeclaration {\n readonly kind: NetworkKind;\n readonly displayName: string;\n}\n\nexport type CustomNetworks = Readonly<Record<string, CustomNetworkDeclaration>>;\n\nconst usdc = (address: string, name: string) =>\n ({ symbol: 'USDC', address, name, version: '2', decimals: 6 }) as const;\n\nconst PROFILES: readonly X402Network[] = [\n {\n family: 'evm',\n id: `eip155:${LOCAL_CHAIN_ID}`,\n chainId: LOCAL_CHAIN_ID,\n displayName: 'Local Anvil',\n kind: 'testnet',\n local: true,\n },\n {\n family: 'evm',\n id: 'eip155:84532',\n chainId: 84532,\n displayName: 'Base Sepolia',\n kind: 'testnet',\n canonicalAsset: usdc('0x036CbD53842c5426634e7929541eC2318f3dCF7e', 'USDC'),\n },\n {\n family: 'evm',\n id: 'eip155:8453',\n chainId: 8453,\n displayName: 'Base',\n kind: 'mainnet',\n canonicalAsset: usdc('0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', 'USD Coin'),\n },\n {\n family: 'evm',\n id: 'eip155:1',\n chainId: 1,\n displayName: 'Ethereum',\n kind: 'mainnet',\n canonicalAsset: usdc('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', 'USD Coin'),\n },\n {\n family: 'evm',\n id: 'eip155:137',\n chainId: 137,\n displayName: 'Polygon',\n kind: 'mainnet',\n canonicalAsset: usdc('0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359', 'USD Coin'),\n },\n {\n family: 'evm',\n id: 'eip155:42161',\n chainId: 42161,\n displayName: 'Arbitrum One',\n kind: 'mainnet',\n canonicalAsset: usdc('0xaf88d065e77c8cC2239327C5EDb3A432268e5831', 'USD Coin'),\n },\n {\n family: 'evm',\n id: 'eip155:421614',\n chainId: 421614,\n displayName: 'Arbitrum Sepolia',\n kind: 'testnet',\n canonicalAsset: usdc('0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d', 'USD Coin'),\n },\n {\n family: 'evm',\n id: 'eip155:43114',\n chainId: 43114,\n displayName: 'Avalanche C-Chain',\n kind: 'mainnet',\n canonicalAsset: usdc('0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E', 'USD Coin'),\n },\n {\n family: 'svm',\n id: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',\n displayName: 'Solana',\n kind: 'mainnet',\n canonicalAsset: {\n symbol: 'USDC',\n address: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',\n decimals: 6,\n },\n },\n {\n family: 'svm',\n id: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1',\n displayName: 'Solana Devnet',\n kind: 'testnet',\n canonicalAsset: {\n symbol: 'USDC',\n address: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU',\n decimals: 6,\n },\n },\n // NEAR's USDC contracts are implicit accounts: 64 lowercase hex characters\n {\n family: 'near',\n id: 'near:mainnet',\n displayName: 'NEAR',\n kind: 'mainnet',\n canonicalAsset: {\n symbol: 'USDC',\n address: '17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1',\n decimals: 6,\n },\n },\n {\n family: 'near',\n id: 'near:testnet',\n displayName: 'NEAR Testnet',\n kind: 'testnet',\n canonicalAsset: {\n symbol: 'USDC',\n address: '3e2210e1184b45b64c8a434c0a7e7b23cc04ea7eb7a6c3c32520d03d4afcb8af',\n decimals: 6,\n },\n },\n];\n\nconst BY_ID = new Map(PROFILES.map((profile) => [profile.id, profile]));\n\n/** Built-in networks of every family, for tests and diagnostics */\nexport const BUILT_IN_NETWORKS: readonly X402Network[] = PROFILES;\n\n/** The built-in EVM networks the x402 provider settles on without a declaration */\nexport const SUPPORTED_NETWORK_IDS: readonly string[] = PROFILES.filter(\n (p) => p.family === 'evm',\n).map((p) => p.id);\n\n// A chain id viem and EIP-712 can carry as a JS number\nconst EVM_NETWORK_ID = /^eip155:([1-9]\\d{0,15})$/;\n\nfunction invalid(message: string, path: string): CommerceError {\n return new CommerceError('CONFIG_INVALID', message, { details: { path } });\n}\n\n/** Built-in EVM profile for callers using the original network interface */\nexport function findNetworkProfile(id: string): NetworkProfile | undefined {\n const profile = BY_ID.get(id);\n return profile?.family === 'evm' ? profile : undefined;\n}\n\n/** A built-in network of any family, or a declared custom EVM network */\nexport function findX402Network(id: string, custom?: CustomNetworks): X402Network | undefined {\n const builtIn = BY_ID.get(id);\n if (builtIn) return builtIn;\n const declared = custom?.[id];\n const chainId = Number(EVM_NETWORK_ID.exec(id)?.[1]);\n if (!declared || !Number.isSafeInteger(chainId)) return undefined;\n return {\n family: 'evm',\n id,\n chainId,\n displayName: declared.displayName,\n kind: declared.kind,\n };\n}\n\nexport function requireX402Network(id: string, path: string, custom?: CustomNetworks): X402Network {\n const network = findX402Network(id, custom);\n if (!network) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `${path}: \"${id}\" is not a known network. Built-in CAIP-2 identifiers: ${PROFILES.map((p) => p.id).join(', ')}. Declare another EVM network under payments.x402.networks with its kind and displayName.`,\n { details: { path, network: id } },\n );\n }\n return network;\n}\n\n/**\n * Allows only new `eip155` networks in `payments.x402.networks`. Redeclaring\n * built-ins could relabel mainnet as testnet; Solana and NEAR IDs are SDK-fixed.\n */\nexport function validateCustomNetworks(custom: CustomNetworks, path: string): void {\n for (const id of Object.keys(custom)) {\n const at = `${path}.${id}`;\n if (BY_ID.has(id)) {\n throw invalid(\n `${at}: \"${id}\" is a built-in network and cannot be redeclared; remove this entry`,\n at,\n );\n }\n if (!findX402Network(id, custom)) {\n throw invalid(\n `${at}: \"${id}\" is not an EVM CAIP-2 identifier (\"eip155:\" followed by a positive chain id below 2^53). Only EVM networks can be declared.`,\n at,\n );\n }\n }\n}\n\n/** What a deployment is: the local dev chain, or a public testnet or mainnet */\nexport type DeploymentMode = 'local' | 'testnet' | 'mainnet';\n\nexport function resolveDeploymentMode(profile: {\n readonly kind: NetworkKind;\n readonly local?: boolean;\n}): DeploymentMode {\n return profile.local ? 'local' : profile.kind;\n}\n\n// The banner an operator must not miss. Printed for mainnet only\nconst LIVE_MAINNET_BANNER = 'LIVE MAINNET MODE - REAL FUNDS';\n\nexport function describeDeploymentMode(mode: DeploymentMode): string {\n return mode === 'mainnet' ? LIVE_MAINNET_BANNER : mode.toUpperCase();\n}\n","// RFC 8785 (JCS) serialization for request hashes\n\n// With the `u` flag, a valid surrogate pair is one code point, so this pattern\n// matches only lone surrogates\nconst LONE_SURROGATE = /\\p{Cs}/u;\n\n/**\n * Serializes JSON data using RFC 8785 (JCS) rules. Non-finite numbers, lone\n * surrogates and unsupported primitive values return undefined.\n * JSON.stringify supplies number formatting and string escaping; the default\n * sort orders keys by UTF-16 code units.\n */\nexport function canonicalJson(value: unknown): string | undefined {\n if (typeof value === 'string')\n return LONE_SURROGATE.test(value) ? undefined : JSON.stringify(value);\n if (typeof value === 'number') return Number.isFinite(value) ? JSON.stringify(value) : undefined;\n if (value === null || typeof value === 'boolean') return JSON.stringify(value);\n if (Array.isArray(value)) {\n const items = value.map(canonicalJson);\n return items.includes(undefined) ? undefined : `[${items.join(',')}]`;\n }\n if (typeof value !== 'object') return undefined;\n const members: string[] = [];\n for (const key of Object.keys(value).sort()) {\n const member = canonicalJson((value as Record<string, unknown>)[key]);\n if (member === undefined || LONE_SURROGATE.test(key)) return undefined;\n members.push(`${JSON.stringify(key)}:${member}`);\n }\n return `{${members.join(',')}}`;\n}\n","/**\n * SDK-free address checks for config load and the CLI. EVM addresses compare\n * without case; Solana keys and NEAR account IDs compare exactly.\n */\nimport type { X402Network } from './networks';\n\n// `0x` + 40 hex characters. Config load cannot check the EIP-55 checksum,\n// which needs keccak-256; the x402 and MPP providers refuse a mixed-case\n// address whose checksum is wrong when they start.\nconst EVM_ADDRESS = /^0x[0-9a-fA-F]{40}$/;\nconst EVM_ZERO = /^0x0{40}$/i;\n\n/** `0x` followed by 40 hex characters, in any case */\nexport const isEvmAddress = (value: unknown): value is `0x${string}` =>\n typeof value === 'string' && EVM_ADDRESS.test(value);\n\n/** The EVM zero address, in any case */\nexport const isEvmZeroAddress = (value: string): boolean => EVM_ZERO.test(value);\n\nconst BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n// A 32-byte key is 32 to 44 base58 characters\nconst SOLANA_ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;\n// The all-zero key, which is the System Program and owns nothing recoverable\nconst SOLANA_ZERO = '11111111111111111111111111111111';\nconst EVM_TRANSACTION_HASH = /^0x[0-9a-fA-F]{64}$/;\n// A 64-byte Ed25519 signature is at most 88 base58 characters\nconst SOLANA_SIGNATURE = /^[1-9A-HJ-NP-Za-km-z]{64,88}$/;\n\n// nearcore's account ID rule: 2 to 64 characters, lowercase alphanumeric runs\n// joined by single \"-\", \"_\" or \".\"; implicit accounts are 64 hex characters\nconst NEAR_ACCOUNT_ID = /^(([a-z\\d]+[-_])*[a-z\\d]+\\.)*([a-z\\d]+[-_])*[a-z\\d]+$/;\n// A transaction hash: 32 bytes in base58\nconst NEAR_TRANSACTION_HASH = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;\n\n/**\n * Returns the family's wire address or `undefined`. NEAR uses named or\n * implicit account IDs; a `.near` suffix does not identify the network.\n */\nexport function normalizeAddress(network: X402Network, value: string): string | undefined {\n switch (network.family) {\n case 'evm':\n return isEvmAddress(value) ? value : undefined;\n case 'svm':\n return SOLANA_ADDRESS.test(value) && base58ByteLength(value) === 32 ? value : undefined;\n case 'near':\n return value.length >= 2 && value.length <= 64 && NEAR_ACCOUNT_ID.test(value)\n ? value\n : undefined;\n }\n}\n\n/**\n * An address funds cannot be recovered from: the zero address of its family.\n * NEAR has no zero account.\n */\nexport function isBurnAddress(network: X402Network, wireAddress: string): boolean {\n switch (network.family) {\n case 'evm':\n return isEvmZeroAddress(wireAddress);\n case 'svm':\n return wireAddress === SOLANA_ZERO;\n case 'near':\n return false;\n }\n}\n\n/** Compare EVM addresses case-insensitively, Solana keys and NEAR account IDs exactly */\nexport function sameAddress(network: X402Network, a: string, b: string): boolean {\n return network.family === 'evm' ? a.toLowerCase() === b.toLowerCase() : a === b;\n}\n\n/**\n * A settlement reference in its family's form: an EVM transaction hash, a\n * Solana transaction signature or a NEAR transaction hash\n */\nexport function isTransactionReference(network: X402Network, value: string): boolean {\n switch (network.family) {\n case 'evm':\n return EVM_TRANSACTION_HASH.test(value);\n case 'svm':\n return SOLANA_SIGNATURE.test(value) && base58ByteLength(value) === 64;\n case 'near':\n return NEAR_TRANSACTION_HASH.test(value) && base58ByteLength(value) === 32;\n }\n}\n\nfunction base58ByteLength(value: string): number {\n let n = 0n;\n for (const char of value) n = n * 58n + BigInt(BASE58_ALPHABET.indexOf(char));\n // Each leading '1' encodes one leading zero byte\n const leadingZeros = value.length - value.replace(/^1+/, '').length;\n return leadingZeros + (n === 0n ? 0 : Math.ceil(n.toString(16).length / 2));\n}\n","/**\n * x402 exact-scheme flows, shared by the config loader and CLI.\n * The default `authorization` flow settles after a successful backend call;\n * `upfront` settles first.\n */\nexport const X402_PAYMENT_FLOWS = ['authorization', 'upfront'] as const;\n\nexport type X402PaymentFlow = (typeof X402_PAYMENT_FLOWS)[number];\n\nexport const X402_DEFAULT_PAYMENT_FLOW: X402PaymentFlow = 'authorization';\n","/**\n * Anvil's well-known development accounts.\n *\n * LOCAL DEVELOPMENT ONLY - DO NOT FUND. The keys come from Foundry's public\n * default mnemonic (\"test test ... junk\"), so value sent to these addresses on\n * a real network can be taken by anyone.\n *\n * Index layout on the local demo chain:\n * 0 - deployer and local facilitator signer (pays gas, broadcasts settlement)\n * 1 - merchant settlement destination (`payTo`)\n * 2 - buyer (signs EIP-3009 authorizations; never held by the gateway)\n */\nexport interface AnvilWellKnownAccount {\n readonly address: `0x${string}`;\n readonly privateKey: `0x${string}`;\n}\n\n/** A fixed-length tuple, so indexing by the layout above is typed */\nexport const ANVIL_WELL_KNOWN_ACCOUNTS: readonly [\n AnvilWellKnownAccount,\n AnvilWellKnownAccount,\n AnvilWellKnownAccount,\n] = [\n {\n address: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266',\n privateKey: '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80',\n },\n {\n address: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8',\n privateKey: '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d',\n },\n {\n address: '0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC',\n privateKey: '0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a',\n },\n];\n\nexport const LOCAL_FACILITATOR_ACCOUNT = ANVIL_WELL_KNOWN_ACCOUNTS[0];\nexport const LOCAL_MERCHANT_ACCOUNT = ANVIL_WELL_KNOWN_ACCOUNTS[1];\nexport const LOCAL_BUYER_ACCOUNT = ANVIL_WELL_KNOWN_ACCOUNTS[2];\n\n/** Label printed wherever a dev key appears in output, logs or manifests */\nexport const DEV_KEY_LABEL = 'LOCAL DEVELOPMENT ONLY - DO NOT FUND';\n"]}
@@ -0,0 +1,92 @@
1
+ import { getAddress, encodeAbiParameters, keccak256 } from 'viem';
2
+ import { createHash } from 'crypto';
3
+ import { PERMIT2_ADDRESS } from '@x402/evm';
4
+
5
+ // src/payments/x402/locator.ts
6
+ var LOCATOR_VERSION = 1;
7
+ var SECONDS = /^\d{1,13}$/;
8
+ var MAX_DATE_MS = 864e13;
9
+ function isoFromSeconds(seconds) {
10
+ const ms = SECONDS.test(seconds) ? Number(seconds) * 1e3 : Number.NaN;
11
+ return ms <= MAX_DATE_MS ? new Date(ms).toISOString() : void 0;
12
+ }
13
+ function eip3009Locator(network, asset, authorization) {
14
+ const { from, to, value, validAfter, validBefore, nonce } = authorization;
15
+ return withExpiry(
16
+ {
17
+ v: LOCATOR_VERSION,
18
+ network,
19
+ method: "eip3009",
20
+ asset: getAddress(asset),
21
+ from: getAddress(from),
22
+ to: getAddress(to),
23
+ value,
24
+ nonce: nonce.toLowerCase(),
25
+ validAfter,
26
+ validBefore
27
+ },
28
+ validBefore
29
+ );
30
+ }
31
+ function permit2Locator(network, transfer) {
32
+ const { asset, owner, to, amount, nonce, deadline, validAfter, proxy } = transfer;
33
+ return withExpiry(
34
+ {
35
+ v: LOCATOR_VERSION,
36
+ network,
37
+ method: "permit2",
38
+ asset: getAddress(asset),
39
+ owner: getAddress(owner),
40
+ to: getAddress(to),
41
+ amount,
42
+ nonce,
43
+ deadline,
44
+ validAfter,
45
+ proxy: getAddress(proxy)
46
+ },
47
+ deadline
48
+ );
49
+ }
50
+ function withExpiry(locator, seconds) {
51
+ const expiresAt = isoFromSeconds(seconds);
52
+ return expiresAt !== void 0 ? { ...locator, expiresAt } : locator;
53
+ }
54
+ function computeReplayKey(input) {
55
+ const encoded = encodeAbiParameters(
56
+ [{ type: "uint256" }, { type: "address" }, { type: "address" }, { type: "bytes32" }],
57
+ [BigInt(input.chainId), input.asset, input.from, input.nonce]
58
+ );
59
+ return keccak256(encoded);
60
+ }
61
+ function computePermit2ReplayKey(input) {
62
+ return keccak256(
63
+ encodeAbiParameters(
64
+ [
65
+ { type: "string" },
66
+ { type: "uint256" },
67
+ { type: "address" },
68
+ { type: "address" },
69
+ { type: "uint256" }
70
+ ],
71
+ [
72
+ "x402/exact/permit2/v1",
73
+ BigInt(input.chainId),
74
+ PERMIT2_ADDRESS,
75
+ input.owner,
76
+ BigInt(input.nonce)
77
+ ]
78
+ )
79
+ );
80
+ }
81
+ function computeSvmReplayKey(input) {
82
+ const digest = createHash("sha256").update("x402/exact/svm/v1\0").update(input.network).update("\0").update(Buffer.from(input.messageHash, "base64")).digest("hex");
83
+ return `0x${digest}`;
84
+ }
85
+ function computeNearReplayKey(input) {
86
+ const digest = createHash("sha256").update("x402/exact/near/v1\0").update(`${input.network}\0${input.senderId}\0${input.publicKey}\0${input.nonce.toString(10)}`).digest("hex");
87
+ return `0x${digest}`;
88
+ }
89
+
90
+ export { LOCATOR_VERSION, computeNearReplayKey, computePermit2ReplayKey, computeReplayKey, computeSvmReplayKey, eip3009Locator, isoFromSeconds, permit2Locator };
91
+ //# sourceMappingURL=chunk-663ALDZA.js.map
92
+ //# sourceMappingURL=chunk-663ALDZA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/payments/x402/locator.ts","../../src/payments/x402/replay-key.ts"],"names":[],"mappings":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AA,GAAS,WAAW,QAAQ,CAAA,CAC/B,OAAO,qBAAqB,CAAA,CAC5B,MAAA,CAAO,KAAA,CAAM,OAAO,CAAA,CACpB,OAAO,IAAI,CAAA,CACX,MAAA,CAAO,MAAA,CAAO,IAAA,CAAK,KAAA,CAAM,aAAa,QAAQ,CAAC,CAAA,CAC/C,MAAA,CAAO,KAAK,CAAA;AACf,EAAA,OAAO,KAAK,MAAM,CAAA,CAAA;AACpB;AAQO,SAAS,qBAAqB,KAAA,EAK1B;AACT,EAAA,MAAM,MAAA,GAAS,UAAA,CAAW,QAAQ,CAAA,CAC/B,MAAA,CAAO,sBAAsB,CAAA,CAC7B,MAAA,CAAO,CAAA,EAAG,KAAA,CAAM,OAAO,CAAA,EAAA,EAAK,KAAA,CAAM,QAAQ,CAAA,EAAA,EAAK,KAAA,CAAM,SAAS,CAAA,EAAA,EAAK,KAAA,CAAM,KAAA,CAAM,QAAA,CAAS,EAAE,CAAC,CAAA,CAAE,CAAA,CAC7F,MAAA,CAAO,KAAK,CAAA;AACf,EAAA,OAAO,KAAK,MAAM,CAAA,CAAA;AACpB","file":"chunk-663ALDZA.js","sourcesContent":["/**\n * Public payment coordinates returned under `RECONCILIATION_METADATA_KEY`\n * for later reconciliation. Locators contain transfer details and derived\n * metadata, excluding signatures, payloads and transaction bytes. Field names\n * avoid \"token\" because the receipt store redacts values under such keys.\n */\nimport { getAddress } from 'viem';\n\nexport const LOCATOR_VERSION = 1;\n\n// Bound decimal input length to cover Date's range without parsing large integers\nconst SECONDS = /^\\d{1,13}$/;\nconst MAX_DATE_MS = 8.64e15;\n\n/**\n * Converts unsigned decimal Unix seconds to ISO time, or undefined for invalid\n * or out-of-range input\n */\nexport function isoFromSeconds(seconds: string): string | undefined {\n const ms = SECONDS.test(seconds) ? Number(seconds) * 1000 : Number.NaN;\n return ms <= MAX_DATE_MS ? new Date(ms).toISOString() : undefined;\n}\n\nexport interface Eip3009Authorization {\n readonly from: string;\n readonly to: string;\n readonly value: string;\n readonly validAfter: string;\n readonly validBefore: string;\n readonly nonce: string;\n}\n\n/** Builds the shared EIP-3009 locator used by x402 and MPP */\nexport function eip3009Locator(\n network: string,\n asset: string,\n authorization: Eip3009Authorization,\n): Readonly<Record<string, unknown>> {\n const { from, to, value, validAfter, validBefore, nonce } = authorization;\n return withExpiry(\n {\n v: LOCATOR_VERSION,\n network,\n method: 'eip3009',\n asset: getAddress(asset),\n from: getAddress(from),\n to: getAddress(to),\n value,\n nonce: nonce.toLowerCase(),\n validAfter,\n validBefore,\n },\n validBefore,\n );\n}\n\nexport interface Permit2Transfer {\n readonly asset: string;\n readonly owner: string;\n /** Recipient named in the signed witness for the x402 proxy transfer */\n readonly to: string;\n readonly amount: string;\n readonly nonce: string;\n readonly deadline: string;\n readonly validAfter: string;\n readonly proxy: string;\n}\n\n/** A Permit2 transfer's locator */\nexport function permit2Locator(\n network: string,\n transfer: Permit2Transfer,\n): Readonly<Record<string, unknown>> {\n const { asset, owner, to, amount, nonce, deadline, validAfter, proxy } = transfer;\n return withExpiry(\n {\n v: LOCATOR_VERSION,\n network,\n method: 'permit2',\n asset: getAddress(asset),\n owner: getAddress(owner),\n to: getAddress(to),\n amount,\n nonce,\n deadline,\n validAfter,\n proxy: getAddress(proxy),\n },\n deadline,\n );\n}\n\nfunction withExpiry(\n locator: Readonly<Record<string, unknown>>,\n seconds: string,\n): Readonly<Record<string, unknown>> {\n const expiresAt = isoFromSeconds(seconds);\n return expiresAt !== undefined ? { ...locator, expiresAt } : locator;\n}\n","/**\n * `PaymentResult.replayKey` is derived from the payment authorization alone,\n * never from the request id, so the same authorization replayed on another\n * request collides in the receipt store's reservation. The MPP provider uses\n * the EIP-3009 derivation.\n */\nimport { createHash } from 'node:crypto';\nimport { PERMIT2_ADDRESS } from '@x402/evm';\nimport { encodeAbiParameters, keccak256 } from 'viem';\n\nexport interface ReplayKeyInput {\n readonly chainId: number;\n readonly asset: `0x${string}`;\n readonly from: `0x${string}`;\n readonly nonce: `0x${string}`;\n}\n\nexport function computeReplayKey(input: ReplayKeyInput): string {\n const encoded = encodeAbiParameters(\n [{ type: 'uint256' }, { type: 'address' }, { type: 'address' }, { type: 'bytes32' }],\n [BigInt(input.chainId), input.asset, input.from, input.nonce],\n );\n return keccak256(encoded);\n}\n\n/**\n * Identifies a Permit2 authorization by chain, Permit2 contract, owner and\n * nonce. Nonces span all tokens and spenders, so asset and resource are excluded.\n * The tag separates these keys from EIP-3009 in the receipt store's unique column.\n */\nexport function computePermit2ReplayKey(input: {\n readonly chainId: number;\n readonly owner: `0x${string}`;\n readonly nonce: string;\n}): string {\n return keccak256(\n encodeAbiParameters(\n [\n { type: 'string' },\n { type: 'uint256' },\n { type: 'address' },\n { type: 'address' },\n { type: 'uint256' },\n ],\n [\n 'x402/exact/permit2/v1',\n BigInt(input.chainId),\n PERMIT2_ADDRESS,\n input.owner,\n BigInt(input.nonce),\n ],\n ),\n );\n}\n\n/**\n * Identifies a Solana `exact` payment by network and SHA-256 of the signed\n * message bytes. Excludes signatures, including the facilitator's fee payer\n * slot, so altered signatures keep the same key. `messageHash` is the SDK's\n * base64 `transactionMessageHash`.\n */\nexport function computeSvmReplayKey(input: {\n readonly network: string;\n readonly messageHash: string;\n}): string {\n const digest = createHash('sha256')\n .update('x402/exact/svm/v1\\0')\n .update(input.network)\n .update('\\0')\n .update(Buffer.from(input.messageHash, 'base64'))\n .digest('hex');\n return `0x${digest}`;\n}\n\n/**\n * Identifies a NEAR `exact` payment by network, sender, curve-prefixed public\n * key (`ed25519:...`) and delegate nonce. Nonces are scoped per access key,\n * excluding token, recipient, relayer and signature; another key of the same\n * sender has an independent nonce scope.\n */\nexport function computeNearReplayKey(input: {\n readonly network: string;\n readonly senderId: string;\n readonly publicKey: string;\n readonly nonce: bigint;\n}): string {\n const digest = createHash('sha256')\n .update('x402/exact/near/v1\\0')\n .update(`${input.network}\\0${input.senderId}\\0${input.publicKey}\\0${input.nonce.toString(10)}`)\n .digest('hex');\n return `0x${digest}`;\n}\n"]}
@@ -1,106 +1,8 @@
1
+ import { CommerceError } from './chunk-SYQLJXIU.js';
1
2
  import { isRecord } from './chunk-3M6U7ILB.js';
2
3
 
3
- // src/core/errors/codes.ts
4
- var COMMERCE_ERROR_HTTP_STATUS = {
5
- CONFIG_INVALID: 500,
6
- RESOURCE_NOT_FOUND: 404,
7
- INPUT_INVALID: 400,
8
- PAYMENT_REQUIRED: 402,
9
- PAYMENT_INVALID: 402,
10
- PAYMENT_REPLAYED: 409,
11
- PAYMENT_PROVIDER_UNAVAILABLE: 503,
12
- PAYMENT_SETTLEMENT_FAILED: 502,
13
- // 403, not 402: a 402 tells a client to pay and retry, which cannot fix a
14
- // missing or rejected mandate, and a client that auto-pays on 402 would be
15
- // charged for a request that was never going to be delivered
16
- AUTHORIZATION_REQUIRED: 403,
17
- AUTHORIZATION_INVALID: 403,
18
- AUTHORIZATION_REPLAYED: 409,
19
- AUTHORIZATION_PROVIDER_UNAVAILABLE: 503,
20
- BACKEND_TIMEOUT: 504,
21
- BACKEND_ERROR: 502,
22
- PROTOCOL_UNSUPPORTED: 501,
23
- GATEWAY_BUSY: 503,
24
- STORAGE_ERROR: 500,
25
- INTERNAL_ERROR: 500
26
- };
27
- var RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set([
28
- "PAYMENT_PROVIDER_UNAVAILABLE",
29
- // The verifier or replay store was unreachable, so the mandate got no
30
- // verdict. The same proof can verify once the outage clears.
31
- "AUTHORIZATION_PROVIDER_UNAVAILABLE",
32
- "BACKEND_TIMEOUT",
33
- // Load shedding is transient: the caller should back off and try again.
34
- // Clients act on this flag, and leaving it out would make a momentary
35
- // throttle look like a permanent failure.
36
- "GATEWAY_BUSY"
37
- ]);
38
-
39
- // src/core/errors/commerce-error.ts
40
- var CommerceError = class _CommerceError extends Error {
41
- code;
42
- httpStatus;
43
- retryable;
44
- details;
45
- requestId;
46
- resourceId;
47
- constructor(code, message, options = {}) {
48
- super(message, options.cause !== void 0 ? { cause: options.cause } : void 0);
49
- this.name = "CommerceError";
50
- this.code = code;
51
- this.httpStatus = options.httpStatus ?? COMMERCE_ERROR_HTTP_STATUS[code];
52
- this.retryable = RETRYABLE_ERROR_CODES.has(code);
53
- if (options.details !== void 0) this.details = options.details;
54
- if (options.requestId !== void 0) this.requestId = options.requestId;
55
- if (options.resourceId !== void 0) this.resourceId = options.resourceId;
56
- Error.captureStackTrace?.(this, _CommerceError);
57
- }
58
- /** Non-secret, client-safe representation. `cause` is never included */
59
- toInfo() {
60
- return {
61
- code: this.code,
62
- message: this.message,
63
- httpStatus: this.httpStatus,
64
- retryable: this.retryable,
65
- ...this.requestId !== void 0 ? { requestId: this.requestId } : {},
66
- ...this.resourceId !== void 0 ? { resourceId: this.resourceId } : {},
67
- ...this.details !== void 0 ? { details: this.details } : {}
68
- };
69
- }
70
- };
71
- function isCommerceError(value) {
72
- return value instanceof CommerceError;
73
- }
74
- function toCommerceError(value, fallbackCode = "INTERNAL_ERROR", fallbackMessage = "Unexpected internal error") {
75
- if (isCommerceError(value)) return value;
76
- return new CommerceError(fallbackCode, fallbackMessage, { cause: value });
77
- }
78
- function describeError(error) {
79
- if (error instanceof Error) return { message: error.message, name: error.name };
80
- return { message: String(error) };
81
- }
82
- function redactedErrorText(value) {
83
- const text = value instanceof Error ? `${value.name}: ${value.message}` : String(value);
84
- return text.replace(/\b[a-z][a-z\d+.-]*:\/\/[^\s"'<>]+/gi, (match) => {
85
- try {
86
- const url = new URL(match);
87
- return `${url.protocol}//${url.host}`;
88
- } catch {
89
- return "[unparseable URL]";
90
- }
91
- });
92
- }
93
- var MAX_LOGGED_CAUSES = 5;
94
- function toLogInfo(value) {
95
- const error = toCommerceError(value);
96
- const cause = [];
97
- let current = error.cause;
98
- while (current !== void 0 && cause.length < MAX_LOGGED_CAUSES) {
99
- cause.push(redactedErrorText(current));
100
- current = current instanceof Error ? current.cause : void 0;
101
- }
102
- return cause.length > 0 ? { ...error.toInfo(), cause } : error.toInfo();
103
- }
4
+ // src/core/domain/payment.ts
5
+ var RECONCILIATION_METADATA_KEY = "reconciliation";
104
6
 
105
7
  // src/core/interfaces/runtime.ts
106
8
  var systemClock = {
@@ -127,6 +29,35 @@ var PAYMENT_METHOD_NAMES = Object.keys(
127
29
  // src/core/domain/resource.ts
128
30
  var DEFAULT_BACKEND_TIMEOUT_MS = 1e4;
129
31
 
32
+ // src/core/domain/transaction.ts
33
+ var TRANSACTION_STATES = [
34
+ "payment-pending",
35
+ "payment-failed",
36
+ "payment-uncertain",
37
+ "settled-undelivered",
38
+ "delivery-started",
39
+ "delivery-unknown",
40
+ "delivered"
41
+ ];
42
+ var isSuccess = (status) => status >= 200 && status <= 299;
43
+ function transactionState(facts, now) {
44
+ const { payment, backend, completedAt } = facts;
45
+ if (payment.status === "settlement-uncertain" || payment.status === "failed") {
46
+ return "payment-uncertain";
47
+ }
48
+ if (payment.status === "rejected") return "payment-failed";
49
+ const waiting = backend !== void 0 && completedAt === void 0 && Date.parse(now) < Date.parse(backend.deadlineAt);
50
+ if (payment.status !== "settled") {
51
+ return waiting && backend?.status === void 0 ? "delivery-started" : "payment-pending";
52
+ }
53
+ if (backend === void 0) return "settled-undelivered";
54
+ const { status } = backend;
55
+ if (status !== void 0 && status !== 0 && !isSuccess(status)) return "settled-undelivered";
56
+ if (status !== void 0 && isSuccess(status) && completedAt !== void 0) return "delivered";
57
+ if (status !== 0 && waiting) return "delivery-started";
58
+ return "delivery-unknown";
59
+ }
60
+
130
61
  // src/core/domain/wire.ts
131
62
  var PAYMENT_INPUT_FIELD = "_payment";
132
63
  var PAYMENT_HEADER = "payment-signature";
@@ -146,6 +77,7 @@ function toDeliverySummary(outcome) {
146
77
  requestId: outcome.requestId,
147
78
  resourceId: outcome.resourceId,
148
79
  receiptId: outcome.receipt.id,
80
+ ...outcome.persistenceFailures?.includes("receipt") ? { receiptCommitted: false } : {},
149
81
  deliveredAt: outcome.receipt.deliveredAt,
150
82
  ...p !== void 0 ? {
151
83
  payment: {
@@ -266,6 +198,6 @@ function isHttpProtocolAdapter(adapter) {
266
198
  return typeof adapter.handleHttp === "function";
267
199
  }
268
200
 
269
- export { AUTHORIZATION_HEADER, AUTHORIZATION_INPUT_FIELD, CommerceError, DEFAULT_BACKEND_TIMEOUT_MS, DELIVERY_SUMMARY_META_KEY, NOOP_LOGGER, PAYMENT_HEADER, PAYMENT_INPUT_FIELD, PAYMENT_METHOD_NAMES, PAYMENT_REQUIRED_HEADER, PAYMENT_RESPONSE_HEADER, PROTOCOL_NAMES, RESERVED_INPUT_FIELDS, describeError, extractReservedInputFields, isCommerceError, isHttpProtocolAdapter, parseAuthorizationHeader, parseAuthorizationSubmission, redactedErrorText, systemClock, toCommerceError, toDeliverySummary, toErrorEnvelope, toLogInfo, toPaymentRequiredEnvelope };
270
- //# sourceMappingURL=chunk-QQ3WY5L3.js.map
271
- //# sourceMappingURL=chunk-QQ3WY5L3.js.map
201
+ export { AUTHORIZATION_HEADER, AUTHORIZATION_INPUT_FIELD, DEFAULT_BACKEND_TIMEOUT_MS, DELIVERY_SUMMARY_META_KEY, NOOP_LOGGER, PAYMENT_HEADER, PAYMENT_INPUT_FIELD, PAYMENT_METHOD_NAMES, PAYMENT_REQUIRED_HEADER, PAYMENT_RESPONSE_HEADER, PROTOCOL_NAMES, RECONCILIATION_METADATA_KEY, RESERVED_INPUT_FIELDS, TRANSACTION_STATES, extractReservedInputFields, isHttpProtocolAdapter, parseAuthorizationHeader, parseAuthorizationSubmission, systemClock, toDeliverySummary, toErrorEnvelope, toPaymentRequiredEnvelope, transactionState };
202
+ //# sourceMappingURL=chunk-IDY2735M.js.map
203
+ //# sourceMappingURL=chunk-IDY2735M.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/domain/payment.ts","../../src/core/interfaces/runtime.ts","../../src/core/domain/common.ts","../../src/core/domain/resource.ts","../../src/core/domain/transaction.ts","../../src/core/domain/wire.ts","../../src/core/interfaces/logger.ts","../../src/core/interfaces/protocol-adapter.ts"],"names":[],"mappings":";;;;AA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,OAAA,KAAY,EAAC;AAAA,IAC3C,GAAI,aAAA,KAAkB,MAAA,GAAY,EAAE,aAAA,KAAkB;AAAC,GACzD;AACF;;;ACzVO,IAAM,WAAA,GAAsB;AAAA,EACjC,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AACf;;;AC0DO,SAAS,sBAAsB,OAAA,EAA0D;AAC9F,EAAA,OAAO,OAAQ,QAAgC,UAAA,KAAe,UAAA;AAChE","file":"chunk-IDY2735M.js","sourcesContent":["/**\n * Canonical payment model. FROZEN CONTRACT.\n *\n * Core decides that a payment is required and for how much. Payment providers\n * decide how the challenge is encoded, verified and settled. No x402- or\n * EVM-specific type may appear in this file.\n */\nimport type {\n AdapterDescriptor,\n AdapterHealth,\n DecimalAmount,\n IsoTimestamp,\n PaymentMethodName,\n} from './common';\nimport type { PaymentAttempt } from './receipt';\nimport type { CommerceResource } from './resource';\n\n/**\n * `PaymentResult.metadata` key for public coordinates returned by `verify`\n * for later provider reconciliation. Core must store the value unchanged and\n * interpret only `expiresAt`. Never include signatures, payloads or\n * transaction bytes. Experimental: may change in a minor release.\n */\nexport const RECONCILIATION_METADATA_KEY = 'reconciliation';\n\n/**\n * Provider-native payment challenge, opaque to core. For x402 the `accepts`\n * entries are x402 `PaymentRequirements` objects, passed to protocol adapters\n * verbatim.\n */\nexport interface PaymentChallenge {\n readonly provider: PaymentMethodName;\n /** Provider protocol version, e.g. the x402 `x402Version` value as a string */\n readonly version: string;\n readonly accepts: readonly Readonly<Record<string, unknown>>[];\n /**\n * The provider's own challenge document, verbatim: for x402 v2 the\n * `PaymentRequired` object a buyer's client consumes, for MPP an object\n * carrying the serialized `WWW-Authenticate` challenge. Opaque to core.\n *\n * `accepts` alone is not that document: x402 v2 carries the resource\n * description and protocol version on the envelope. Adapters with a native\n * channel for it (x402's `PAYMENT-REQUIRED` header, MPP's `WWW-Authenticate`)\n * send it there as is, so every surface offers the same challenge.\n */\n readonly envelope?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * What the buyer must pay, in canonical terms, plus the provider-native\n * challenge the buyer's client needs to construct a payment\n */\nexport interface PaymentRequirement {\n readonly id: string;\n readonly requestId: string;\n readonly resourceId: string;\n readonly provider: PaymentMethodName;\n readonly amount: DecimalAmount;\n readonly currency: string;\n /**\n * Merchant-controlled settlement destination, never a gateway-owned wallet.\n * Multi-offer challenges omit this, `network` and `asset`; selection\n * supplies the chosen offer's terms.\n */\n readonly destination?: string;\n readonly network?: string;\n readonly asset?: string;\n readonly expiresAt?: IsoTimestamp;\n readonly challenge: PaymentChallenge;\n readonly metadata?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Opaque payment proof supplied by the buyer's client. For x402 over HTTP it is\n * the base64 `PAYMENT-SIGNATURE` header value; over MCP and A2A it is the same\n * string in the reserved `_payment` input field.\n */\nexport interface PaymentSubmission {\n readonly method: PaymentMethodName;\n readonly payload: string;\n}\n\n/** Outcome of verification or settlement */\nexport interface PaymentResult {\n readonly status: 'verified' | 'settled' | 'rejected';\n readonly provider: PaymentMethodName;\n /** Settlement reference, e.g. an on-chain transaction hash */\n readonly externalReference?: string;\n readonly payer?: string;\n readonly payee?: string;\n readonly amount: DecimalAmount;\n readonly currency: string;\n readonly network?: string;\n readonly asset?: string;\n /**\n * Stable, provider-computed identity of the payment authorization.\n *\n * The pipeline reserves this key before settlement and rejects a second\n * request presenting it with `PAYMENT_REPLAYED`. Providers must derive it\n * only from the authorization (payer, nonce, asset, network), so the same\n * authorization always maps to the same key.\n */\n readonly replayKey?: string;\n /** Machine-readable rejection reason when status is `rejected` */\n readonly rejectionReason?: string;\n readonly settledAt?: IsoTimestamp;\n readonly metadata?: Readonly<Record<string, unknown>>;\n}\n\n/** Input to {@link PaymentProvider.createRequirement} */\nexport interface PaymentContext {\n readonly requestId: string;\n readonly resource: CommerceResource;\n readonly amount: DecimalAmount;\n readonly currency: string;\n readonly requestedAt: IsoTimestamp;\n /**\n * Validated resource input used to build the backend request. The pipeline\n * sets this field on every createRequirement call. A rail may bind its\n * challenge to the input but must not send it to a third party.\n */\n readonly input?: unknown;\n readonly metadata?: Readonly<Record<string, unknown>>;\n}\n\n/** Input to {@link PaymentProvider.verify} */\nexport interface PaymentVerificationContext {\n readonly requestId: string;\n readonly resource: CommerceResource;\n readonly requirement: PaymentRequirement;\n readonly submission: PaymentSubmission;\n}\n\n/** Input to {@link PaymentProvider.settle} */\nexport interface PaymentSettlementContext extends PaymentVerificationContext {\n readonly verification: PaymentResult;\n}\n\n/** Input to {@link PaymentProvider.reconcile}. Experimental: may change in a minor release */\nexport interface PaymentReconciliationContext {\n readonly attempt: PaymentAttempt;\n /** Coordinates from `verify`; optional for compatibility with pre-2.5.0 attempts */\n readonly locator?: Readonly<Record<string, unknown>>;\n readonly now: IsoTimestamp;\n}\n\n/** Chain evidence for resolving an attempt. Experimental: may change in a minor release */\nexport interface PaymentReconciliationResult {\n /**\n * Report `settled` only with a final transfer record for this authorization.\n * Report `not-settled` only when a state read proves it unused after it can\n * no longer land; missing logs or receipts are insufficient. Otherwise,\n * report `unknown`.\n */\n readonly outcome: 'settled' | 'not-settled' | 'unknown';\n /** A machine-readable token, such as `not_final` */\n readonly reason: string;\n readonly externalReference?: string;\n /** Public chain facts only */\n readonly evidence?: Readonly<Record<string, unknown>>;\n /** For `unknown`, the earliest time a different answer is possible, if known */\n readonly retryAfter?: IsoTimestamp;\n}\n\n/**\n * Contract every payment rail implements. Implementations must be\n * non-custodial: they orchestrate an external payment protocol and never hold\n * buyer or merchant production signing keys.\n */\nexport interface PaymentProvider {\n readonly name: PaymentMethodName;\n readonly descriptor: AdapterDescriptor;\n\n /**\n * Build the requirement and its challenge. The pipeline calls it for every\n * paid request, including one that already carries a proof to verify.\n */\n createRequirement(context: PaymentContext): Promise<PaymentRequirement>;\n\n /**\n * Selects a proof's offer before verification, returning its destination,\n * network, asset and metadata while preserving `id` and the full `challenge`.\n * Verification, authorization, replay reservation and settlement use the result.\n * This hook must not verify, reserve or settle. If no unique offer matches,\n * return the original requirement for `verify` to reject.\n */\n selectRequirement?(context: PaymentVerificationContext): Promise<PaymentRequirement>;\n\n /**\n * Validate a submitted proof against the requirement. Must return `rejected`\n * or throw a `CommerceError` rather than an untyped error, and must never\n * move funds.\n */\n verify(context: PaymentVerificationContext): Promise<PaymentResult>;\n\n /**\n * Execute settlement. Called only after `verify` returned `verified` and the\n * replay key was reserved. A settlement verdict, including a rejection, is a\n * returned result; the pipeline records any throw as settlement-uncertain.\n */\n settle(context: PaymentSettlementContext): Promise<PaymentResult>;\n\n /**\n * Read chain evidence for an attempt with an unknown outcome. Implementations\n * must not write, broadcast or call a facilitator. Providers without this\n * hook require manual resolution. Experimental: may change in a minor release.\n */\n reconcile?(context: PaymentReconciliationContext): Promise<PaymentReconciliationResult>;\n\n health(): Promise<AdapterHealth>;\n}\n","// Time and ids are injected so tests can be deterministic\nimport type { IsoTimestamp } from '../domain/common';\n\nexport interface Clock {\n now(): Date;\n nowIso(): IsoTimestamp;\n /** Milliseconds since an arbitrary origin; use for durations only */\n monotonicMs(): number;\n}\n\nexport interface IdGenerator {\n /** Opaque, collision-resistant identifier */\n next(prefix?: string): string;\n}\n\nexport const systemClock: Clock = {\n now: () => new Date(),\n nowIso: () => new Date().toISOString(),\n monotonicMs: () => performance.now(),\n};\n","// Shared primitive aliases for the canonical domain model. FROZEN CONTRACT\n\n/**\n * A JSON Schema document (in practice a draft 2020-12 subset). Deliberately\n * loose: adapters translate it to their own schema representation. Never treat\n * it as trusted input without validation.\n */\nexport type JsonSchema = Record<string, unknown>;\n\n/** Protocol surfaces a resource can be exposed through */\nexport type ProtocolName = 'http' | 'mcp' | 'a2a' | 'acp';\n\n// A Record over the union fails to compile when a name is missing or extra\nconst PROTOCOL_NAME_KEYS: Record<ProtocolName, true> = {\n http: true,\n mcp: true,\n a2a: true,\n acp: true,\n};\n\n/**\n * The same names as a value, for code that checks one at runtime: config\n * validation and the OpenAPI importer's `--expose`\n */\nexport const PROTOCOL_NAMES: readonly ProtocolName[] = Object.keys(\n PROTOCOL_NAME_KEYS,\n) as ProtocolName[];\n\n/**\n * Payment rails a resource can accept.\n *\n * A resource's list is an ordered candidate list, not a buyer-selected menu.\n * The pipeline uses the first method with an enabled provider, and a\n * rejection ends the request instead of trying another rail. Config requires at\n * least one named rail to be enabled and permits others that are not.\n */\nexport type PaymentMethodName = 'x402' | 'mpp';\n\n// Checked for completeness the same way as PROTOCOL_NAME_KEYS\nconst PAYMENT_METHOD_NAME_KEYS: Record<PaymentMethodName, true> = { x402: true, mpp: true };\n\n/** The same names as a value, for config validation */\nexport const PAYMENT_METHOD_NAMES: readonly PaymentMethodName[] = Object.keys(\n PAYMENT_METHOD_NAME_KEYS,\n) as PaymentMethodName[];\n\n/**\n * Authorization methods a resource can require. Neither a transport nor a\n * payment rail: it proves the purchase was approved, and sits beside the\n * payment rather than replacing it.\n */\nexport type AuthorizationMethodName = 'ap2';\n\n/** ISO-8601 timestamp string, always UTC with millisecond precision */\nexport type IsoTimestamp = string;\n\n/**\n * A decimal amount as a string in the currency's display unit (for example\n * \"0.01\" USDC), never a float and never base units. Payment providers convert\n * it to on-chain base units.\n */\nexport type DecimalAmount = string;\n\n/** Health of an individual adapter or subsystem */\nexport interface AdapterHealth {\n readonly status: 'pass' | 'warn' | 'fail';\n readonly detail?: string;\n readonly checkedAt: IsoTimestamp;\n readonly durationMs?: number;\n /**\n * Results per checked part, such as each x402 offer. Names and statuses\n * may be published; exclude diagnostic detail.\n */\n readonly components?: readonly AdapterHealthComponent[];\n}\n\n/** One part of an {@link AdapterHealth} result */\nexport interface AdapterHealthComponent {\n readonly name: string;\n readonly status: 'pass' | 'warn' | 'fail';\n}\n\n/** Describes an adapter's supported surface for diagnostics */\nexport interface AdapterDescriptor {\n readonly name: string;\n readonly kind: 'protocol' | 'payment' | 'storage' | 'authorization';\n /** Version of this adapter implementation, independent of the spec */\n readonly implementationVersion: string;\n /** Exact pinned specification revision this adapter targets */\n readonly supportedSpec: string;\n readonly capabilities: readonly string[];\n readonly status: 'stable' | 'experimental' | 'planned';\n /** Capabilities explicitly not implemented, printed by `doctor` */\n readonly unsupported?: readonly string[];\n}\n","// Canonical resource model. FROZEN CONTRACT\nimport type {\n AuthorizationMethodName,\n DecimalAmount,\n JsonSchema,\n PaymentMethodName,\n ProtocolName,\n} from './common';\n\n/** HTTP methods a backend handler may use */\nexport type BackendMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * How the gateway calls the merchant's existing backend.\n *\n * Backend URLs come from operator configuration only, never from users or\n * agents (docs/security.md, SSRF). Secret header values belong in `${ENV_VAR}`\n * placeholders resolved by the config loader, not in plaintext configuration.\n */\nexport interface BackendHandler {\n readonly type: 'http';\n readonly method: BackendMethod;\n readonly url: string;\n readonly headers?: Readonly<Record<string, string>>;\n /** Hard upper bound on the backend call. Defaults to `DEFAULT_BACKEND_TIMEOUT_MS` */\n readonly timeoutMs?: number;\n /**\n * Names the top-level input properties carrying each part of the request.\n *\n * When absent, `{param}` values come from top-level input and everything left\n * over becomes the query string (GET/DELETE) or the whole JSON body\n * (POST/PUT/PATCH). That cannot express an operation with path, query and\n * body at once, such as `POST /users/{userId}/orders?notify=true`.\n *\n * When present, each group comes from its named property, and top-level input\n * that no binding names is not forwarded.\n */\n readonly inputBindings?: {\n readonly path?: string;\n readonly query?: string;\n readonly body?: string;\n };\n}\n\n/** Default backend timeout when a resource does not specify one */\nexport const DEFAULT_BACKEND_TIMEOUT_MS = 10_000;\n\n/**\n * Canonical pricing. `dynamic` exists in the type for forward compatibility;\n * config validation rejects it and the pipeline refuses it as defense in depth.\n */\nexport type Pricing =\n | { readonly type: 'free' }\n | {\n readonly type: 'fixed';\n readonly amount: DecimalAmount;\n readonly currency: string;\n }\n | {\n readonly type: 'dynamic';\n readonly resolver: string;\n };\n\n/**\n * A merchant capability exposed to agents. Protocol adapters map it outward and\n * never define their own parallel notion of a resource.\n */\nexport interface CommerceResource {\n readonly id: string;\n readonly name: string;\n readonly description?: string;\n readonly inputSchema?: JsonSchema;\n readonly outputSchema?: JsonSchema;\n readonly handler: BackendHandler;\n readonly pricing: Pricing;\n readonly exposedVia: readonly ProtocolName[];\n readonly paymentMethods: readonly PaymentMethodName[];\n /**\n * Authorization the buyer must present in addition to payment. Opt-in per\n * resource. It sits beside `paymentMethods`, not inside it, because an\n * authorization method is not a payment rail and must never be selectable as\n * one.\n */\n readonly authorization?: {\n readonly required: readonly AuthorizationMethodName[];\n };\n}\n\n/** Read-only view of every configured resource */\nexport interface ResourceRegistry {\n get(id: string): CommerceResource | undefined;\n list(): readonly CommerceResource[];\n /** Resources exposed through a given protocol surface */\n listExposedVia(protocol: ProtocolName): readonly CommerceResource[];\n has(id: string): boolean;\n}\n","/**\n * Canonical transaction model. FROZEN CONTRACT.\n *\n * A transaction links a paid purchase's request, payment attempt, optional\n * authorization hold, backend call and receipt by ID. PaymentAttempt owns the\n * payment status; journal readers must read it from the attempt rather than\n * maintain a separate copy.\n */\nimport type { AuthorizationRecord } from './authorization';\nimport type { DecimalAmount, IsoTimestamp, PaymentMethodName, ProtocolName } from './common';\nimport type { PaymentAttempt } from './receipt';\n\n/**\n * States derived by {@link transactionState}. Experimental: may change in a\n * minor release.\n */\nexport const TRANSACTION_STATES = [\n 'payment-pending',\n 'payment-failed',\n 'payment-uncertain',\n 'settled-undelivered',\n 'delivery-started',\n 'delivery-unknown',\n 'delivered',\n] as const;\n\n/**\n * Open to state names added by later releases; consumers must handle values\n * outside {@link TRANSACTION_STATES}. Experimental: may change in a minor release.\n */\nexport type TransactionState = (typeof TRANSACTION_STATES)[number] | (string & {});\n\n/** Last hold state communicated to the authorization provider */\nexport type AuthorizationHoldState = 'reserved' | 'consumed' | 'released' | 'uncertain';\n\n/**\n * Store writes reported as failed during an execution. Consumers must handle\n * unlisted labels that later releases may add.\n */\nexport type PersistenceFailure = 'payment-attempt' | 'receipt' | 'journal' | (string & {});\n\n/**\n * Journal record for a paid purchase, starting with replay reservation.\n * Store only references and digests, never payment proofs, signatures, mandates\n * or input bodies. Experimental: may change in a minor release.\n */\nexport interface Transaction {\n readonly id: string;\n /** The request that created it */\n readonly requestId: string;\n readonly resourceId: string;\n readonly protocol: ProtocolName;\n /** Cached derived state; readers must recompute it with {@link transactionState} */\n readonly state: TransactionState;\n readonly payment: {\n readonly provider: PaymentMethodName;\n readonly attemptId: string;\n readonly replayKey: string;\n /** Read from PaymentAttempt, not maintained independently */\n readonly status: PaymentAttempt['status'];\n readonly amount: DecimalAmount;\n readonly currency: string;\n readonly network?: string;\n readonly asset?: string;\n readonly payee?: string;\n readonly externalReference?: string;\n /**\n * Public coordinates for the provider's `reconcile` hook, governed by\n * `RECONCILIATION_METADATA_KEY`\n */\n readonly locator?: Readonly<Record<string, unknown>>;\n /** When the provider's `settle` was called */\n readonly settlingAt?: IsoTimestamp;\n /** The authorization cannot land after this */\n readonly expiresAt?: IsoTimestamp;\n };\n readonly authorization?: AuthorizationRecord & {\n /** The handle the authorization provider consumes or releases */\n readonly reservationId: string;\n readonly hold: AuthorizationHoldState;\n };\n readonly backend?: {\n readonly dispatchedAt: IsoTimestamp;\n /** Dispatch time plus the backend timeout and a margin */\n readonly deadlineAt: IsoTimestamp;\n /** 0 if the call ended without a status, such as a timeout or transport failure */\n readonly status?: number;\n readonly errorCode?: string;\n };\n readonly receiptId?: string;\n /** `sha256:` followed by the canonical JSON input digest in hex; omit for non-I-JSON input */\n readonly inputDigest?: string;\n /** Digest of pricing and settlement terms, excluding credentials */\n readonly configDigest: string;\n readonly persistenceFailures?: readonly PersistenceFailure[];\n readonly createdAt: IsoTimestamp;\n readonly updatedAt: IsoTimestamp;\n /** Time of the pipeline's last journal write before returning the outcome */\n readonly completedAt?: IsoTimestamp;\n}\n\n/** What {@link transactionState} reads */\nexport type TransactionFacts = Pick<Transaction, 'backend' | 'completedAt'> & {\n readonly payment: Pick<Transaction['payment'], 'status'>;\n};\n\nconst isSuccess = (status: number): boolean => status >= 200 && status <= 299;\n\n/**\n * Derive state from payment status, backend facts and pipeline completion.\n * For a settled payment, a dispatched call with no result after `deadlineAt`\n * means `delivery-unknown`; a timeout does not prove that the backend never ran.\n * Experimental: may change in a minor release.\n */\nexport function transactionState(\n facts: TransactionFacts,\n now: IsoTimestamp,\n): (typeof TRANSACTION_STATES)[number] {\n const { payment, backend, completedAt } = facts;\n if (payment.status === 'settlement-uncertain' || payment.status === 'failed') {\n return 'payment-uncertain';\n }\n if (payment.status === 'rejected') return 'payment-failed';\n\n // Invalid timestamps make the comparison false, treating the deadline as passed\n const waiting =\n backend !== undefined &&\n completedAt === undefined &&\n Date.parse(now) < Date.parse(backend.deadlineAt);\n if (payment.status !== 'settled') {\n return waiting && backend?.status === undefined ? 'delivery-started' : 'payment-pending';\n }\n\n if (backend === undefined) return 'settled-undelivered';\n const { status } = backend;\n if (status !== undefined && status !== 0 && !isSuccess(status)) return 'settled-undelivered';\n if (status !== undefined && isSuccess(status) && completedAt !== undefined) return 'delivered';\n // Wait until the deadline for a missing result or an unfinished 2xx flow.\n // Status 0 means the call already ended without a response.\n if (status !== 0 && waiting) return 'delivery-started';\n return 'delivery-unknown';\n}\n","/**\n * Gateway-defined wire envelopes and carriers. FROZEN CONTRACT.\n *\n * The HTTP routes and the MCP and A2A adapters build their \"payment required\"\n * and \"error\" bodies with these helpers, so those surfaces send the same\n * shapes. The ACP adapter maps errors to ACP's own error format instead.\n */\n\nimport { CommerceError, type CommerceErrorCode } from '../errors';\nimport { isRecord } from '../is-record';\nimport type { AuthorizationRequirement, AuthorizationSubmission } from './authorization';\nimport type { DecimalAmount, IsoTimestamp, PaymentMethodName } from './common';\nimport type { PaymentSubmission } from './payment';\nimport type { DeliveredOutcome, PaymentRequiredOutcome } from './request';\nimport type { CommerceResource } from './resource';\n\n/**\n * Reserved input property carrying a payment proof on protocols with no header\n * channel (MCP tool calls, A2A message data). HTTP uses a header instead.\n */\nexport const PAYMENT_INPUT_FIELD = '_payment';\n\n/**\n * HTTP request header carrying an x402 payment proof. MPP proofs use\n * `Authorization: Payment ...` instead.\n *\n * The x402 v2 header names, lowercased as Node presents incoming headers. v1's\n * `X-PAYMENT` / `X-PAYMENT-RESPONSE` pair is not accepted: honoring both\n * versions would mean two verification paths for the same money.\n */\nexport const PAYMENT_HEADER = 'payment-signature';\n\n/** HTTP response header carrying the settlement result */\nexport const PAYMENT_RESPONSE_HEADER = 'payment-response';\n\n/**\n * Reserved input property carrying an authorization proof, the counterpart of\n * {@link PAYMENT_INPUT_FIELD}.\n *\n * `_payment` is a bare string whose method is taken from the resource's first\n * payment method. This field is a `{ method, payload }` object, because the\n * method of a security control should be stated, not inferred.\n */\nexport const AUTHORIZATION_INPUT_FIELD = '_authorization';\n\n/**\n * Every input property name the gateway claims for itself. The config loader\n * rejects a resource declaring one, protocol adapters lift them out of client\n * input, and the pipeline strips them again as defense in depth.\n */\nexport const RESERVED_INPUT_FIELDS: readonly string[] = [\n PAYMENT_INPUT_FIELD,\n AUTHORIZATION_INPUT_FIELD,\n];\n\n/**\n * HTTP request header carrying the authorization proof: base64url-encoded JSON\n * of the same `{ method, payload }` object the reserved input field carries.\n *\n * An Agent Commerce carrier, not a header from any authorization\n * specification. It is namespaced rather than reusing `Authorization`, which\n * already carries other credentials, including MPP payment proofs.\n */\nexport const AUTHORIZATION_HEADER = 'agent-authorization';\n\n/**\n * Hard cap on the encoded `Agent-Authorization` header.\n *\n * Node's default limit is 16 KiB across all request headers, and a request over\n * it is refused before the gateway sees it. Capping well below that gives an\n * oversized proof a deterministic `AUTHORIZATION_INVALID` naming the limit.\n */\nexport const MAX_AUTHORIZATION_HEADER_BYTES = 8192;\n\n/**\n * HTTP response header carrying the base64 x402 challenge on a 402.\n *\n * The body still carries the richer {@link PaymentRequiredEnvelope}, the only\n * channel MCP has, but an x402 v2 client reads the challenge from this header\n * and ignores the body, so both are sent.\n */\nexport const PAYMENT_REQUIRED_HEADER = 'payment-required';\n\n/**\n * Key under which a protocol adapter attaches a {@link DeliverySummary} to its\n * result metadata: MCP's `CallToolResult._meta` and the A2A task artifact's\n * metadata.\n *\n * Part of the frozen contract because producer and consumer must agree on it;\n * both import this constant. Follows MCP's `<namespace>/<name>` convention for\n * `_meta` keys.\n */\nexport const DELIVERY_SUMMARY_META_KEY = 'agent-commerce/delivery';\n\nexport interface PaymentRequiredEnvelope {\n readonly status: 'payment-required';\n readonly code: 'PAYMENT_REQUIRED';\n readonly requestId: string;\n readonly resourceId: string;\n readonly message: string;\n readonly payment: {\n readonly provider: PaymentMethodName;\n readonly version: string;\n readonly amount: DecimalAmount;\n readonly currency: string;\n /**\n * @deprecated Read `accepts`: x402 offers use `payTo`; MPP challenges use\n * `request.recipient`. Omitted for multi-offer x402 challenges.\n */\n readonly destination?: string;\n /**\n * @deprecated Read `accepts`: x402 offers use `network`; MPP challenges use\n * the numeric `request.methodDetails.chainId`\n */\n readonly network?: string;\n /**\n * @deprecated Read `accepts`: x402 offers use `asset`; MPP challenges use\n * `request.currency`\n */\n readonly asset?: string;\n readonly expiresAt?: IsoTimestamp;\n /** Provider-native requirement objects, passed through verbatim */\n readonly accepts: readonly Readonly<Record<string, unknown>>[];\n /**\n * The provider's own challenge document, verbatim (see\n * {@link PaymentChallenge.envelope}). Present for providers that have one;\n * a buyer's protocol client can hand it straight to its SDK.\n */\n readonly envelope?: Readonly<Record<string, unknown>>;\n };\n /**\n * Present only when the resource also requires an authorization proof, so a\n * client learns before it spends anything that paying alone will not get the\n * resource delivered. A client that ignores the field sees the plain\n * envelope. The proof comes from the merchant's own approval flow, outside\n * the gateway.\n */\n readonly authorization?: {\n readonly required: readonly AuthorizationRequirement[];\n };\n}\n\nexport interface ErrorEnvelope {\n readonly status: 'error';\n readonly code: CommerceErrorCode;\n readonly message: string;\n readonly retryable: boolean;\n readonly requestId?: string;\n readonly resourceId?: string;\n readonly details?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * What a buyer learns about their own completed purchase: the request, whether\n * it settled, and the settlement reference they can check on-chain. The\n * merchant's ledger is not theirs to read, which is why `/api/receipts` is an\n * operator route behind `server.adminToken`.\n */\nexport interface DeliverySummary {\n readonly requestId: string;\n readonly resourceId: string;\n readonly receiptId: string;\n /** `false` marks a failed receipt write; do not treat `receiptId` as proof of persistence */\n readonly receiptCommitted?: false;\n readonly deliveredAt: IsoTimestamp;\n readonly payment?: {\n readonly status: 'verified' | 'settled' | 'rejected';\n readonly amount: DecimalAmount;\n readonly currency: string;\n /** Settlement reference, e.g. an on-chain transaction hash */\n readonly externalReference?: string;\n readonly network?: string;\n };\n}\n\n/** Build the payer-facing summary of a delivered outcome */\nexport function toDeliverySummary(outcome: DeliveredOutcome): DeliverySummary {\n const p = outcome.payment;\n return {\n requestId: outcome.requestId,\n resourceId: outcome.resourceId,\n receiptId: outcome.receipt.id,\n ...(outcome.persistenceFailures?.includes('receipt') ? { receiptCommitted: false } : {}),\n deliveredAt: outcome.receipt.deliveredAt,\n ...(p !== undefined\n ? {\n payment: {\n status: p.status,\n amount: p.amount,\n currency: p.currency,\n ...(p.externalReference !== undefined\n ? { externalReference: p.externalReference }\n : {}),\n ...(p.network !== undefined ? { network: p.network } : {}),\n },\n }\n : {}),\n };\n}\n\nexport function toPaymentRequiredEnvelope(\n outcome: PaymentRequiredOutcome,\n): PaymentRequiredEnvelope {\n const r = outcome.requirement;\n return {\n status: 'payment-required',\n code: 'PAYMENT_REQUIRED',\n requestId: outcome.requestId,\n resourceId: outcome.resourceId,\n message: `Payment of ${r.amount} ${r.currency} is required for resource \"${outcome.resourceId}\". Retry with a ${r.provider} payment proof.`,\n payment: {\n provider: r.provider,\n version: r.challenge.version,\n amount: r.amount,\n currency: r.currency,\n ...(r.destination !== undefined ? { destination: r.destination } : {}),\n ...(r.network !== undefined ? { network: r.network } : {}),\n ...(r.asset !== undefined ? { asset: r.asset } : {}),\n ...(r.expiresAt !== undefined ? { expiresAt: r.expiresAt } : {}),\n accepts: r.challenge.accepts,\n ...(r.challenge.envelope !== undefined ? { envelope: r.challenge.envelope } : {}),\n },\n ...(outcome.authorization !== undefined && outcome.authorization.length > 0\n ? { authorization: { required: outcome.authorization } }\n : {}),\n };\n}\n\nexport function toErrorEnvelope(error: CommerceError): ErrorEnvelope {\n const info = error.toInfo();\n return {\n status: 'error',\n code: info.code,\n message: info.message,\n retryable: info.retryable,\n ...(info.requestId !== undefined ? { requestId: info.requestId } : {}),\n ...(info.resourceId !== undefined ? { resourceId: info.resourceId } : {}),\n ...(info.details !== undefined ? { details: info.details } : {}),\n };\n}\n\nexport function isPaymentRequiredEnvelope(value: unknown): value is PaymentRequiredEnvelope {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as PaymentRequiredEnvelope).status === 'payment-required' &&\n typeof (value as PaymentRequiredEnvelope).payment === 'object'\n );\n}\n\n/**\n * Parses the `{ method, payload }` authorization object, whichever carrier\n * brought it. Absent returns `undefined`; malformed throws\n * `AUTHORIZATION_INVALID`.\n *\n * An unusable `_payment` is dropped, which leaves the buyer a 402 to act on. A\n * dropped authorization would instead come back as \"not authorized\", with no\n * way to tell a rejected mandate from a typo in the object around it.\n */\nexport function parseAuthorizationSubmission(\n value: unknown,\n requestId?: string,\n): AuthorizationSubmission | undefined {\n if (value === undefined || value === null) return undefined;\n\n const fail = (detail: string): never => {\n throw new CommerceError('AUTHORIZATION_INVALID', `Malformed authorization: ${detail}`, {\n ...(requestId !== undefined ? { requestId } : {}),\n });\n };\n\n if (!isRecord(value)) {\n return fail(`expected an object with \"method\" and \"payload\", got ${typeof value}`);\n }\n const method = value['method'];\n const payload = value['payload'];\n\n // Compared against the literal rather than a registry: a second method needs\n // a second verifier, a deliberate addition rather than a string that starts\n // working because a client sent it\n if (method !== 'ap2') {\n fail(`unsupported method ${typeof method === 'string' ? `\"${method}\"` : typeof method}`);\n }\n if (typeof payload !== 'string' || payload.length === 0) {\n fail('\"payload\" must be a non-empty string');\n }\n\n return { method: 'ap2', payload: payload as string };\n}\n\n/**\n * Decodes the base64url JSON `Agent-Authorization` header. The size check runs\n * on the encoded value, so an oversized header costs a length comparison rather\n * than a decode and a JSON parse.\n */\nexport function parseAuthorizationHeader(\n raw: string | readonly string[] | undefined,\n requestId?: string,\n): AuthorizationSubmission | undefined {\n const value = Array.isArray(raw) ? raw[0] : (raw as string | undefined);\n if (value === undefined || value.length === 0) return undefined;\n\n const fail = (detail: string): never => {\n throw new CommerceError('AUTHORIZATION_INVALID', `Malformed authorization: ${detail}`, {\n ...(requestId !== undefined ? { requestId } : {}),\n });\n };\n\n if (Buffer.byteLength(value, 'utf8') > MAX_AUTHORIZATION_HEADER_BYTES) {\n fail(`header exceeds the ${MAX_AUTHORIZATION_HEADER_BYTES}-byte limit`);\n }\n\n let decoded: unknown;\n try {\n decoded = JSON.parse(Buffer.from(value, 'base64url').toString('utf8'));\n } catch {\n // Nothing from the exception is repeated back: a JSON parse error quotes\n // the input it choked on, which here is whatever the caller sent\n fail('header is not base64url-encoded JSON');\n }\n return parseAuthorizationSubmission(decoded, requestId);\n}\n\n/**\n * Splits raw client input into resource input plus the reserved fields, for\n * protocols that carry them in the input object (MCP tool arguments, A2A\n * message data). HTTP carries both in headers.\n *\n * A payment proof is labeled with the resource's first payment method.\n * `createGateway` puts provider-backed methods first so the label matches the\n * pipeline's selection; a custom registry must keep that order. A resource with\n * no payment method gets no payment proof, so the request reaches the pipeline\n * unpaid.\n */\nexport function extractReservedInputFields(\n rawInput: Record<string, unknown>,\n resource: CommerceResource | undefined,\n requestId?: string,\n): {\n input: Record<string, unknown>;\n payment?: PaymentSubmission;\n authorization?: AuthorizationSubmission;\n} {\n const {\n [PAYMENT_INPUT_FIELD]: paymentValue,\n [AUTHORIZATION_INPUT_FIELD]: authorizationValue,\n ...input\n } = rawInput;\n\n const method = resource?.paymentMethods[0];\n const payment =\n typeof paymentValue === 'string' && paymentValue.length > 0 && method !== undefined\n ? ({ method, payload: paymentValue } satisfies PaymentSubmission)\n : undefined;\n const authorization = parseAuthorizationSubmission(authorizationValue, requestId);\n\n return {\n input,\n ...(payment !== undefined ? { payment } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n };\n}\n","/**\n * Minimal structural logger. Core does not depend on pino; the gateway injects\n * a pino instance that satisfies this shape.\n *\n * Never log secrets: private keys, seed phrases, Authorization headers or\n * payment authorization payloads.\n */\nexport interface Logger {\n debug(obj: Record<string, unknown>, msg?: string): void;\n info(obj: Record<string, unknown>, msg?: string): void;\n warn(obj: Record<string, unknown>, msg?: string): void;\n error(obj: Record<string, unknown>, msg?: string): void;\n child(bindings: Record<string, unknown>): Logger;\n}\n\n/** A logger that discards everything */\nexport const NOOP_LOGGER: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n child: () => NOOP_LOGGER,\n};\n","/**\n * Protocol adapter boundary. FROZEN CONTRACT.\n *\n * An adapter translates a protocol's wire format into a `CanonicalRequest`,\n * hands it to the execution pipeline and maps the outcome back. It must not\n * call merchant backends, implement payment logic or hold its own copy of the\n * canonical model. A failure while starting or serving one adapter must not\n * stop the others.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { AdapterDescriptor, AdapterHealth, ProtocolName } from '../domain/common';\nimport type { EventSink } from '../domain/event';\nimport type { ExecutionPipeline } from '../domain/request';\nimport type { ResourceRegistry } from '../domain/resource';\nimport type { Logger } from './logger';\nimport type { Clock, IdGenerator } from './runtime';\n\n/** Everything an adapter is given. Nothing else is available to it */\nexport interface ProtocolAdapterContext {\n readonly pipeline: ExecutionPipeline;\n readonly resources: ResourceRegistry;\n readonly events: EventSink;\n readonly logger: Logger;\n readonly clock: Clock;\n readonly ids: IdGenerator;\n /** Externally reachable base URL of the gateway, from config */\n readonly publicBaseUrl: string;\n}\n\nexport interface ProtocolAdapter {\n readonly name: ProtocolName;\n readonly descriptor: AdapterDescriptor;\n\n start(context: ProtocolAdapterContext): Promise<void>;\n health(): Promise<AdapterHealth>;\n stop(): Promise<void>;\n}\n\n/**\n * A protocol adapter served over HTTP. The gateway mounts `handleHttp` at\n * `mountPath` with raw Node request and response objects, so adapters stay\n * independent of the HTTP framework.\n *\n * Guarantee: `req` arrives with its body stream unread. The gateway suppresses\n * every body parser on the mount, so an adapter whose SDK reads the body itself\n * (MCP's Streamable HTTP transport) can do so. The adapter owns reading,\n * size-limiting beyond the gateway's own cap, and parsing.\n *\n * The guarantee can break silently. Fastify prefers its exact-match\n * `application/json` and `text/plain` parsers over a `'*'` wildcard, so a\n * wildcard no-op alone lets the JSON parser drain the body and the adapter\n * reads an empty stream. The MCP conformance suite drives `handleHttp` over a\n * bare `node:http` server and cannot catch it, so any change to adapter mounting\n * needs a test that POSTs a JSON body through the real gateway and asserts the\n * adapter received it intact.\n */\nexport interface HttpProtocolAdapter extends ProtocolAdapter {\n /** Path prefix the gateway mounts this adapter at, e.g. '/mcp' */\n readonly mountPath: string;\n handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void>;\n /**\n * Fixed paths this adapter owns outside its mount, for protocols whose\n * specification pins a discovery URL (A2A's `/.well-known/agent-card.json`).\n * The gateway mounts them with the same guarantees as `mountPath`: unread\n * body, concurrency cap and failure isolation.\n */\n readonly additionalHttpRoutes?: readonly AdapterHttpRoute[];\n}\n\n/**\n * One fixed, method-scoped route owned by an adapter. Unlike `mountPath` it\n * registers no wildcard and matches exactly the path given.\n */\nexport interface AdapterHttpRoute {\n readonly method: 'GET' | 'POST';\n /** Absolute gateway path, e.g. '/.well-known/agent-card.json' */\n readonly path: string;\n handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void>;\n}\n\nexport function isHttpProtocolAdapter(adapter: ProtocolAdapter): adapter is HttpProtocolAdapter {\n return typeof (adapter as HttpProtocolAdapter).handleHttp === 'function';\n}\n"]}
@@ -0,0 +1,107 @@
1
+ import { CommerceError } from './chunk-SYQLJXIU.js';
2
+
3
+ // src/gateway/optional-peer.ts
4
+ var MISSING_PACKAGE = /Cannot find package '([^']+)'/;
5
+ async function importOptionalPeer(feature, load) {
6
+ try {
7
+ return await load();
8
+ } catch (cause) {
9
+ if (cause?.code !== "ERR_MODULE_NOT_FOUND") throw cause;
10
+ const pkg = MISSING_PACKAGE.exec(cause.message)?.[1];
11
+ if (pkg === void 0) throw cause;
12
+ throw new CommerceError(
13
+ "CONFIG_INVALID",
14
+ `${feature} is enabled, but the package "${pkg}" is not installed. Install the optional peers it needs at the versions \`agent-commerce version\` lists, or disable it.`,
15
+ { cause }
16
+ );
17
+ }
18
+ }
19
+
20
+ // src/gateway/payment-providers.ts
21
+ function offerOptions(option) {
22
+ return {
23
+ network: option.network,
24
+ rpcUrl: option.rpcUrl,
25
+ asset: option.asset,
26
+ assetDecimals: option.assetDecimals,
27
+ payTo: option.payTo,
28
+ ...option.assetName !== void 0 ? { assetName: option.assetName } : {},
29
+ ...option.assetVersion !== void 0 ? { assetVersion: option.assetVersion } : {},
30
+ ...option.assetTransferMethod !== void 0 ? { assetTransferMethod: option.assetTransferMethod } : {}
31
+ };
32
+ }
33
+ async function createConfiguredPaymentProviders(payments, logger) {
34
+ const providers = [];
35
+ const { x402, mpp } = payments;
36
+ if (x402?.enabled) {
37
+ const { createX402PaymentProvider } = await importOptionalPeer(
38
+ "payments.x402",
39
+ () => import('./x402-WLYBLODI.js')
40
+ );
41
+ providers.push(
42
+ createX402PaymentProvider({
43
+ // Support manually built single-option configs without `options`
44
+ offers: (x402.options ?? [x402]).map(offerOptions),
45
+ ...x402.resourceOptions !== void 0 ? {
46
+ resourceOffers: Object.fromEntries(
47
+ Object.entries(x402.resourceOptions).map(([id, list]) => [
48
+ id,
49
+ list.map(offerOptions)
50
+ ])
51
+ )
52
+ } : {},
53
+ maxTimeoutSeconds: x402.maxTimeoutSeconds,
54
+ ...x402.paymentFlow !== void 0 ? { paymentFlow: x402.paymentFlow } : {},
55
+ ...x402.resourcePaymentFlows !== void 0 ? { resourcePaymentFlows: x402.resourcePaymentFlows } : {},
56
+ ...x402.resourceMimeTypes !== void 0 ? { resourceMimeTypes: x402.resourceMimeTypes } : {},
57
+ facilitator: x402.facilitator,
58
+ ...x402.allowMainnet !== void 0 ? { allowMainnet: x402.allowMainnet } : {},
59
+ ...x402.allowUnauthenticatedFacilitator !== void 0 ? { allowUnauthenticatedFacilitator: x402.allowUnauthenticatedFacilitator } : {},
60
+ ...x402.networks !== void 0 ? { customNetworks: x402.networks } : {},
61
+ // Pass quote settings only to x402; MPP builds a separate settlement
62
+ // provider without quotes
63
+ ...x402.quote !== void 0 ? { quote: x402.quote } : {},
64
+ logger
65
+ })
66
+ );
67
+ }
68
+ if (mpp?.enabled) {
69
+ const { createMppPaymentProvider } = await importOptionalPeer(
70
+ "payments.mpp",
71
+ () => import('./provider-6TKB5ADJ.js')
72
+ );
73
+ providers.push(
74
+ createMppPaymentProvider({
75
+ recipient: mpp.recipient,
76
+ asset: mpp.asset,
77
+ assetName: mpp.assetName,
78
+ assetVersion: mpp.assetVersion,
79
+ network: mpp.network,
80
+ realm: mpp.realm,
81
+ challengeSecret: mpp.challengeSecret,
82
+ ...mpp.challengeTtlSeconds !== void 0 ? { challengeTtlSeconds: mpp.challengeTtlSeconds } : {},
83
+ rpcUrl: mpp.rpcUrl,
84
+ facilitator: mpp.facilitator,
85
+ ...mpp.allowMainnet !== void 0 ? { allowMainnet: mpp.allowMainnet } : {},
86
+ ...mpp.allowUnauthenticatedFacilitator !== void 0 ? { allowUnauthenticatedFacilitator: mpp.allowUnauthenticatedFacilitator } : {},
87
+ ...mpp.paymentFlow !== void 0 ? { paymentFlow: mpp.paymentFlow } : {},
88
+ ...mpp.resourcePaymentFlows !== void 0 ? { resourcePaymentFlows: mpp.resourcePaymentFlows } : {},
89
+ logger
90
+ })
91
+ );
92
+ }
93
+ return providers;
94
+ }
95
+ async function createConfiguredAuthorizationProviders(authorization, logger) {
96
+ const ap2 = authorization?.ap2;
97
+ if (!ap2?.enabled) return [];
98
+ const { createAp2AuthorizationProvider } = await importOptionalPeer(
99
+ "authorization.ap2",
100
+ () => import('./ap2-YAPLERSC.js')
101
+ );
102
+ return [createAp2AuthorizationProvider({ config: ap2, logger })];
103
+ }
104
+
105
+ export { createConfiguredAuthorizationProviders, createConfiguredPaymentProviders, importOptionalPeer };
106
+ //# sourceMappingURL=chunk-JFVRG2HH.js.map
107
+ //# sourceMappingURL=chunk-JFVRG2HH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/gateway/optional-peer.ts","../../src/gateway/payment-providers.ts"],"names":[],"mappings":";;;AAGA,IAAM,eAAA,GAAkB,+BAAA;AAQxB,eAAsB,kBAAA,CAAsB,SAAiB,IAAA,EAAoC;AAC/F,EAAA,IAAI;AACF,IAAA,OAAO,MAAM,IAAA,EAAK;AAAA,EACpB,SAAS,KAAA,EAAO;AACd,IAAA,IAAK,KAAA,EAAwC,IAAA,KAAS,sBAAA,EAAwB,MAAM,KAAA;AACpF,IAAA,MAAM,MAAM,eAAA,CAAgB,IAAA,CAAM,KAAA,CAAgB,OAAO,IAAI,CAAC,CAAA;AAC9D,IAAA,IAAI,GAAA,KAAQ,QAAW,MAAM,KAAA;AAC7B,IAAA,MAAM,IAAI,aAAA;AAAA,MACR,gBAAA;AAAA,MACA,CAAA,EAAG,OAAO,CAAA,8BAAA,EAAiC,GAAG,CAAA,wHAAA,CAAA;AAAA,MAG9C,EAAE,KAAA;AAAM,KACV;AAAA,EACF;AACF;;;ACbA,SAAS,aAAa,MAAA,EAA4C;AAChE,EAAA,OAAO;AAAA,IACL,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,QAAQ,MAAA,CAAO,MAAA;AAAA,IACf,OAAO,MAAA,CAAO,KAAA;AAAA,IACd,eAAe,MAAA,CAAO,aAAA;AAAA,IACtB,OAAO,MAAA,CAAO,KAAA;AAAA,IACd,GAAI,OAAO,SAAA,KAAc,MAAA,GAAY,EAAE,SAAA,EAAW,MAAA,CAAO,SAAA,EAAU,GAAI,EAAC;AAAA,IACxE,GAAI,OAAO,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AAI,IAAI,YAAA,KAAiB,MAAA,GAAY,EAAE,YAAA,EAAc,GAAA,CAAI,YAAA,EAAa,GAAI,EAAC;AAAA,QAC3E,GAAI,IAAI,+BAAA,KAAoC,MAAA,GACxC,EAAE,+BAAA,EAAiC,GAAA,CAAI,+BAAA,EAAgC,GACvE,EAAC;AAAA,QACL,GAAI,IAAI,WAAA,KAAgB,MAAA,GAAY,EAAE,WAAA,EAAa,GAAA,CAAI,WAAA,EAAY,GAAI,EAAC;AAAA,QACxE,GAAI,IAAI,oBAAA,KAAyB,MAAA,GAC7B,EAAE,oBAAA,EAAsB,GAAA,CAAI,oBAAA,EAAqB,GACjD,EAAC;AAAA,QACL;AAAA,OACD;AAAA,KACH;AAAA,EACF;AACA,EAAA,OAAO,SAAA;AACT;AAMA,eAAsB,sCAAA,CACpB,eACA,MAAA,EACqC;AACrC,EAAA,MAAM,MAAM,aAAA,EAAe,GAAA;AAC3B,EAAA,IAAI,CAAC,GAAA,EAAK,OAAA,EAAS,OAAO,EAAC;AAC3B,EAAA,MAAM,EAAE,8BAAA,EAA+B,GAAI,MAAM,kBAAA;AAAA,IAC/C,mBAAA;AAAA,IACA,MAAM,OAAO,mBAAsB;AAAA,GACrC;AACA,EAAA,OAAO,CAAC,8BAAA,CAA+B,EAAE,QAAQ,GAAA,EAAK,MAAA,EAAQ,CAAC,CAAA;AACjE","file":"chunk-JFVRG2HH.js","sourcesContent":["import { CommerceError } from '../core';\n\n// Node's ERR_MODULE_NOT_FOUND message for a bare specifier it could not resolve\nconst MISSING_PACKAGE = /Cannot find package '([^']+)'/;\n\n/**\n * Loads the module behind an enabled config feature. A package that is not\n * installed becomes a CONFIG_INVALID naming the feature and the package,\n * instead of a resolver error pointing into a bundled chunk. Any other\n * failure, such as a missing file inside an installed package, is rethrown.\n */\nexport async function importOptionalPeer<T>(feature: string, load: () => Promise<T>): Promise<T> {\n try {\n return await load();\n } catch (cause) {\n if ((cause as NodeJS.ErrnoException | null)?.code !== 'ERR_MODULE_NOT_FOUND') throw cause;\n const pkg = MISSING_PACKAGE.exec((cause as Error).message)?.[1];\n if (pkg === undefined) throw cause;\n throw new CommerceError(\n 'CONFIG_INVALID',\n `${feature} is enabled, but the package \"${pkg}\" is not installed. Install the ` +\n 'optional peers it needs at the versions `agent-commerce version` lists, or ' +\n 'disable it.',\n { cause },\n );\n }\n}\n","/**\n * Builds enabled payment rails on demand. x402 needs no `mppx`; MPP uses\n * x402 internally and needs its EVM peers. Peer loading follows each rail's\n * `enabled` flag, not resource prices: an enabled rail needs its peers even\n * when every resource is free.\n */\nimport type { Ap2AuthorizationProvider } from '../authorization/ap2';\nimport type { GatewayConfig } from '../config';\nimport type { X402OptionConfig } from '../config/schema';\nimport type { Logger, PaymentProvider } from '../core';\nimport type { X402OfferOptions } from '../payments/x402';\nimport { importOptionalPeer } from './optional-peer';\n\nfunction offerOptions(option: X402OptionConfig): X402OfferOptions {\n return {\n network: option.network,\n rpcUrl: option.rpcUrl,\n asset: option.asset,\n assetDecimals: option.assetDecimals,\n payTo: option.payTo,\n ...(option.assetName !== undefined ? { assetName: option.assetName } : {}),\n ...(option.assetVersion !== undefined ? { assetVersion: option.assetVersion } : {}),\n ...(option.assetTransferMethod !== undefined\n ? { assetTransferMethod: option.assetTransferMethod }\n : {}),\n };\n}\n\nexport async function createConfiguredPaymentProviders(\n payments: GatewayConfig['payments'],\n logger: Logger,\n): Promise<PaymentProvider[]> {\n const providers: PaymentProvider[] = [];\n const { x402, mpp } = payments;\n if (x402?.enabled) {\n const { createX402PaymentProvider } = await importOptionalPeer(\n 'payments.x402',\n () => import('../payments/x402'),\n );\n providers.push(\n createX402PaymentProvider({\n // Support manually built single-option configs without `options`\n offers: (x402.options ?? [x402]).map(offerOptions),\n ...(x402.resourceOptions !== undefined\n ? {\n resourceOffers: Object.fromEntries(\n Object.entries(x402.resourceOptions).map(([id, list]) => [\n id,\n list.map(offerOptions),\n ]),\n ),\n }\n : {}),\n maxTimeoutSeconds: x402.maxTimeoutSeconds,\n ...(x402.paymentFlow !== undefined ? { paymentFlow: x402.paymentFlow } : {}),\n ...(x402.resourcePaymentFlows !== undefined\n ? { resourcePaymentFlows: x402.resourcePaymentFlows }\n : {}),\n ...(x402.resourceMimeTypes !== undefined\n ? { resourceMimeTypes: x402.resourceMimeTypes }\n : {}),\n facilitator: x402.facilitator,\n ...(x402.allowMainnet !== undefined ? { allowMainnet: x402.allowMainnet } : {}),\n ...(x402.allowUnauthenticatedFacilitator !== undefined\n ? { allowUnauthenticatedFacilitator: x402.allowUnauthenticatedFacilitator }\n : {}),\n ...(x402.networks !== undefined ? { customNetworks: x402.networks } : {}),\n // Pass quote settings only to x402; MPP builds a separate settlement\n // provider without quotes\n ...(x402.quote !== undefined ? { quote: x402.quote } : {}),\n logger,\n }),\n );\n }\n if (mpp?.enabled) {\n const { createMppPaymentProvider } = await importOptionalPeer(\n 'payments.mpp',\n () => import('../payments/mpp/provider'),\n );\n providers.push(\n createMppPaymentProvider({\n recipient: mpp.recipient as `0x${string}`,\n asset: mpp.asset as `0x${string}`,\n assetName: mpp.assetName,\n assetVersion: mpp.assetVersion,\n network: mpp.network,\n realm: mpp.realm,\n challengeSecret: mpp.challengeSecret,\n ...(mpp.challengeTtlSeconds !== undefined\n ? { challengeTtlSeconds: mpp.challengeTtlSeconds }\n : {}),\n rpcUrl: mpp.rpcUrl,\n facilitator: mpp.facilitator,\n ...(mpp.allowMainnet !== undefined ? { allowMainnet: mpp.allowMainnet } : {}),\n ...(mpp.allowUnauthenticatedFacilitator !== undefined\n ? { allowUnauthenticatedFacilitator: mpp.allowUnauthenticatedFacilitator }\n : {}),\n ...(mpp.paymentFlow !== undefined ? { paymentFlow: mpp.paymentFlow } : {}),\n ...(mpp.resourcePaymentFlows !== undefined\n ? { resourcePaymentFlows: mpp.resourcePaymentFlows }\n : {}),\n logger,\n }),\n );\n }\n return providers;\n}\n\n/**\n * Builds enabled authorization providers for CLI hold updates.\n * Each opens a replay database that the caller must close.\n */\nexport async function createConfiguredAuthorizationProviders(\n authorization: GatewayConfig['authorization'],\n logger: Logger,\n): Promise<Ap2AuthorizationProvider[]> {\n const ap2 = authorization?.ap2;\n if (!ap2?.enabled) return [];\n const { createAp2AuthorizationProvider } = await importOptionalPeer(\n 'authorization.ap2',\n () => import('../authorization/ap2'),\n );\n return [createAp2AuthorizationProvider({ config: ap2, logger })];\n}\n"]}
@@ -0,0 +1,8 @@
1
+ import 'module';
2
+
3
+ // src/version.ts
4
+ var PACKAGE_VERSION = "2.5.0" ;
5
+
6
+ export { PACKAGE_VERSION };
7
+ //# sourceMappingURL=chunk-M7NXVRU5.js.map
8
+ //# sourceMappingURL=chunk-M7NXVRU5.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/version.ts"],"names":[],"mappings":";;;AAsBO,IAAM,eAAA,GACmC,OAAA","file":"chunk-ITWNSS2B.js","sourcesContent":["/**\n * The package version, resolved once for the whole package.\n *\n * The build injects `__OAC_PACKAGE_VERSION__` (tsup.config.ts), because a\n * relative manifest path resolves from the wrong depth once `src/**` is\n * bundled. From source, the root manifest is read instead. `typeof` on an\n * undeclared identifier is safe, so the source path runs without the constant.\n */\nimport { createRequire } from 'node:module';\n\ndeclare const __OAC_PACKAGE_VERSION__: string | undefined;\n\nfunction readFromManifest(): string {\n try {\n const require = createRequire(import.meta.url);\n // src/version.ts -> repository root\n return (require('../package.json') as { version?: string }).version ?? '0.0.0-unknown';\n } catch {\n return '0.0.0-unknown';\n }\n}\n\nexport const PACKAGE_VERSION: string =\n typeof __OAC_PACKAGE_VERSION__ === 'string' ? __OAC_PACKAGE_VERSION__ : readFromManifest();\n"]}
1
+ {"version":3,"sources":["../../src/version.ts"],"names":[],"mappings":";;;AAsBO,IAAM,eAAA,GACmC,OAAA","file":"chunk-M7NXVRU5.js","sourcesContent":["/**\n * The package version, resolved once for the whole package.\n *\n * The build injects `__OAC_PACKAGE_VERSION__` (tsup.config.ts), because a\n * relative manifest path resolves from the wrong depth once `src/**` is\n * bundled. From source, the root manifest is read instead. `typeof` on an\n * undeclared identifier is safe, so the source path runs without the constant.\n */\nimport { createRequire } from 'node:module';\n\ndeclare const __OAC_PACKAGE_VERSION__: string | undefined;\n\nfunction readFromManifest(): string {\n try {\n const require = createRequire(import.meta.url);\n // src/version.ts -> repository root\n return (require('../package.json') as { version?: string }).version ?? '0.0.0-unknown';\n } catch {\n return '0.0.0-unknown';\n }\n}\n\nexport const PACKAGE_VERSION: string =\n typeof __OAC_PACKAGE_VERSION__ === 'string' ? __OAC_PACKAGE_VERSION__ : readFromManifest();\n"]}