@agent-score/commerce 2.5.0 → 2.6.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 (80) hide show
  1. package/README.md +19 -17
  2. package/dist/challenge/index.d.mts +26 -2
  3. package/dist/challenge/index.d.ts +26 -2
  4. package/dist/challenge/index.js +14 -5
  5. package/dist/challenge/index.js.map +1 -1
  6. package/dist/challenge/index.mjs +14 -5
  7. package/dist/challenge/index.mjs.map +1 -1
  8. package/dist/{checkout-McfNpZJf.d.ts → checkout-C4RD7M0Z.d.ts} +46 -13
  9. package/dist/{checkout-o17dIxHi.d.mts → checkout-CzB9f_jf.d.mts} +46 -13
  10. package/dist/core.d.mts +20 -9
  11. package/dist/core.d.ts +20 -9
  12. package/dist/core.js +35 -24
  13. package/dist/core.js.map +1 -1
  14. package/dist/core.mjs +35 -24
  15. package/dist/core.mjs.map +1 -1
  16. package/dist/discovery/index.d.mts +17 -2
  17. package/dist/discovery/index.d.ts +17 -2
  18. package/dist/discovery/index.js +36 -12
  19. package/dist/discovery/index.js.map +1 -1
  20. package/dist/discovery/index.mjs +35 -12
  21. package/dist/discovery/index.mjs.map +1 -1
  22. package/dist/{gate-CWP10xPQ.d.mts → gate-D2RP6bZg.d.ts} +109 -141
  23. package/dist/{gate-CWP10xPQ.d.ts → gate-GCXy4FHI.d.mts} +109 -141
  24. package/dist/identity/express.d.mts +3 -1
  25. package/dist/identity/express.d.ts +3 -1
  26. package/dist/identity/express.js +164 -55
  27. package/dist/identity/express.js.map +1 -1
  28. package/dist/identity/express.mjs +164 -55
  29. package/dist/identity/express.mjs.map +1 -1
  30. package/dist/identity/fastify.d.mts +3 -1
  31. package/dist/identity/fastify.d.ts +3 -1
  32. package/dist/identity/fastify.js +171 -57
  33. package/dist/identity/fastify.js.map +1 -1
  34. package/dist/identity/fastify.mjs +171 -57
  35. package/dist/identity/fastify.mjs.map +1 -1
  36. package/dist/identity/hono.d.mts +3 -1
  37. package/dist/identity/hono.d.ts +3 -1
  38. package/dist/identity/hono.js +159 -59
  39. package/dist/identity/hono.js.map +1 -1
  40. package/dist/identity/hono.mjs +159 -59
  41. package/dist/identity/hono.mjs.map +1 -1
  42. package/dist/identity/nextjs.d.mts +3 -1
  43. package/dist/identity/nextjs.d.ts +3 -1
  44. package/dist/identity/nextjs.js +153 -56
  45. package/dist/identity/nextjs.js.map +1 -1
  46. package/dist/identity/nextjs.mjs +153 -56
  47. package/dist/identity/nextjs.mjs.map +1 -1
  48. package/dist/identity/policy.d.mts +21 -2
  49. package/dist/identity/policy.d.ts +21 -2
  50. package/dist/identity/policy.js +22 -1
  51. package/dist/identity/policy.js.map +1 -1
  52. package/dist/identity/policy.mjs +21 -1
  53. package/dist/identity/policy.mjs.map +1 -1
  54. package/dist/identity/web.d.mts +3 -1
  55. package/dist/identity/web.d.ts +3 -1
  56. package/dist/identity/web.js +153 -56
  57. package/dist/identity/web.js.map +1 -1
  58. package/dist/identity/web.mjs +153 -56
  59. package/dist/identity/web.mjs.map +1 -1
  60. package/dist/index.d.mts +55 -10
  61. package/dist/index.d.ts +55 -10
  62. package/dist/index.js +2211 -500
  63. package/dist/index.js.map +1 -1
  64. package/dist/index.mjs +2203 -500
  65. package/dist/index.mjs.map +1 -1
  66. package/dist/payment/index.d.mts +1 -1
  67. package/dist/payment/index.d.ts +1 -1
  68. package/dist/payment/index.js +10 -2
  69. package/dist/payment/index.js.map +1 -1
  70. package/dist/payment/index.mjs +10 -2
  71. package/dist/payment/index.mjs.map +1 -1
  72. package/dist/stripe-multichain/index.js +1614 -266
  73. package/dist/stripe-multichain/index.js.map +1 -1
  74. package/dist/stripe-multichain/index.mjs +1614 -266
  75. package/dist/stripe-multichain/index.mjs.map +1 -1
  76. package/dist/types-D1slMt0H.d.mts +137 -0
  77. package/dist/types-D1slMt0H.d.ts +137 -0
  78. package/dist/{wwwauthenticate-CVaGUMjU.d.mts → wwwauthenticate-Dgm-_af9.d.mts} +11 -1
  79. package/dist/{wwwauthenticate-CVaGUMjU.d.ts → wwwauthenticate-Dgm-_af9.d.ts} +11 -1
  80. package/package.json +23 -18
package/dist/index.js CHANGED
@@ -5,11 +5,20 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __esm = (fn, res) => function __init() {
9
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
8
+ var __esm = (fn, res, err) => function __init() {
9
+ if (err) throw err[0];
10
+ try {
11
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
12
+ } catch (e) {
13
+ throw err = [e], e;
14
+ }
10
15
  };
11
16
  var __commonJS = (cb, mod) => function __require() {
12
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
17
+ try {
18
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
+ } catch (e) {
20
+ throw mod = 0, e;
21
+ }
13
22
  };
14
23
  var __export = (target, all) => {
15
24
  for (var name in all)
@@ -193,7 +202,7 @@ function mppPaymentHandler({
193
202
  networks: networks2
194
203
  }) {
195
204
  return {
196
- "sh.agentscore.payment.mpp": [{
205
+ "com.agentscore.payment.mpp": [{
197
206
  id: "mpp",
198
207
  version: HANDLER_VERSION,
199
208
  spec: `${SPEC_BASE}/mpp`,
@@ -214,7 +223,7 @@ function x402PaymentHandler({
214
223
  networks: networks2
215
224
  }) {
216
225
  return {
217
- "sh.agentscore.payment.x402": [{
226
+ "com.agentscore.payment.x402": [{
218
227
  id: "x402",
219
228
  version: HANDLER_VERSION,
220
229
  spec: `${SPEC_BASE}/x402`,
@@ -227,7 +236,7 @@ function stripeSptPaymentHandler({
227
236
  spec
228
237
  }) {
229
238
  return {
230
- "sh.agentscore.payment.stripe_spt": [{
239
+ "com.agentscore.payment.stripe_spt": [{
231
240
  id: "stripe-spt",
232
241
  version: HANDLER_VERSION,
233
242
  spec: `${SPEC_BASE}/stripe_spt`,
@@ -245,10 +254,10 @@ var init_ucp = __esm({
245
254
  fromJWK: ucpSigningKeyFromJWKImpl
246
255
  };
247
256
  DEFAULT_VERSION = "2026-04-08";
248
- AGENTSCORE_CAPABILITY_NAME = "sh.agentscore.identity";
257
+ AGENTSCORE_CAPABILITY_NAME = "com.agentscore.identity";
249
258
  AGENTSCORE_CAPABILITY_VERSION = "2026-04-08";
250
- AGENTSCORE_DEFAULT_SPEC_URL = "https://agentscore.sh/specification/identity";
251
- AGENTSCORE_DEFAULT_SCHEMA_URL = "https://agentscore.sh/schemas/ucp/sh-agentscore-identity-v1.json";
259
+ AGENTSCORE_DEFAULT_SPEC_URL = "https://www.agentscore.com/specification/identity";
260
+ AGENTSCORE_DEFAULT_SCHEMA_URL = "https://www.agentscore.com/schemas/ucp/com-agentscore-identity-v1.json";
252
261
  AGENTSCORE_EXTENDS = ["dev.ucp.shopping.checkout", "dev.ucp.shopping.cart"];
253
262
  RESERVED_TOP_LEVEL = /* @__PURE__ */ new Set([
254
263
  "ucp",
@@ -271,8 +280,8 @@ var init_ucp = __esm({
271
280
  ]);
272
281
  AGENTSCORE_UCP_CAPABILITY = AGENTSCORE_CAPABILITY_NAME;
273
282
  HANDLER_VERSION = "2026-04-08";
274
- SPEC_BASE = "https://agentscore.sh/specification/payment-handlers";
275
- SCHEMA_BASE = "https://agentscore.sh/schemas/payment-handlers";
283
+ SPEC_BASE = "https://www.agentscore.com/specification/payment-handlers";
284
+ SCHEMA_BASE = "https://www.agentscore.com/schemas/payment-handlers";
276
285
  CAIP2_TO_UCP_NETWORK = {
277
286
  "eip155:8453": "base-8453",
278
287
  "eip155:84532": "base-84532",
@@ -484,12 +493,12 @@ async function verifyUCPProfile(profile, jwks) {
484
493
  `UCP signature header kid must be a non-empty string; got ${kid === void 0 ? "undefined" : typeof kid}.`
485
494
  );
486
495
  }
487
- const matches = jwks.keys.filter(
496
+ const matches2 = jwks.keys.filter(
488
497
  (k) => k != null && typeof k === "object" && k.kid === kid
489
498
  );
490
- if (matches.length === 0) throw new UCPVerificationError("kid_not_found", `No JWK in JWKS matching kid=${JSON.stringify(kid)}.`);
491
- if (matches.length > 1) throw new UCPVerificationError("duplicate_kid", `JWKS contains ${matches.length} keys with kid=${JSON.stringify(kid)}; expected exactly one.`);
492
- const matchedKey = matches[0];
499
+ if (matches2.length === 0) throw new UCPVerificationError("kid_not_found", `No JWK in JWKS matching kid=${JSON.stringify(kid)}.`);
500
+ if (matches2.length > 1) throw new UCPVerificationError("duplicate_kid", `JWKS contains ${matches2.length} keys with kid=${JSON.stringify(kid)}; expected exactly one.`);
501
+ const matchedKey = matches2[0];
493
502
  if (matchedKey.use != null && matchedKey.use !== "sig") {
494
503
  throw new UCPVerificationError("unusable_key", `JWK with kid=${kid} has use=${JSON.stringify(matchedKey.use)}; expected "sig".`);
495
504
  }
@@ -499,7 +508,7 @@ async function verifyUCPProfile(profile, jwks) {
499
508
  `JWK alg ${JSON.stringify(matchedKey.alg)} does not match JWS header alg ${JSON.stringify(h.alg)}.`
500
509
  );
501
510
  }
502
- return jose.importJWK(matches[0], h.alg);
511
+ return jose.importJWK(matches2[0], h.alg);
503
512
  }
504
513
  );
505
514
  signedPayload = verified.payload;
@@ -728,7 +737,7 @@ var init_Errors = __esm({
728
737
  const docsBaseUrl = options.docsOrigin ?? _BaseError.prototype.docsOrigin;
729
738
  const docs = `${docsBaseUrl}${docsPath ?? ""}`;
730
739
  const showVersion = Boolean(options.version ?? _BaseError.prototype.showVersion);
731
- const version3 = options.version ?? _BaseError.prototype.version;
740
+ const version4 = options.version ?? _BaseError.prototype.version;
732
741
  const message = [
733
742
  shortMessage || "An error occurred.",
734
743
  ...options.metaMessages ? ["", ...options.metaMessages] : [],
@@ -736,7 +745,7 @@ var init_Errors = __esm({
736
745
  "",
737
746
  details ? `Details: ${details}` : void 0,
738
747
  docsPath ? `See: ${docs}` : void 0,
739
- showVersion ? `Version: ${version3}` : void 0
748
+ showVersion ? `Version: ${version4}` : void 0
740
749
  ] : []
741
750
  ].filter((x) => typeof x === "string").join("\n");
742
751
  super(message, options.cause ? { cause: options.cause } : void 0);
@@ -801,7 +810,7 @@ var init_Errors = __esm({
801
810
  this.docsPath = docsPath;
802
811
  this.shortMessage = shortMessage;
803
812
  this.showVersion = showVersion;
804
- this.version = version3;
813
+ this.version = version4;
805
814
  }
806
815
  walk(fn) {
807
816
  return walk(this, fn);
@@ -931,16 +940,16 @@ var init_hmac = __esm({
931
940
  this.blockLen = this.iHash.blockLen;
932
941
  this.outputLen = this.iHash.outputLen;
933
942
  const blockLen = this.blockLen;
934
- const pad3 = new Uint8Array(blockLen);
935
- pad3.set(key.length > blockLen ? hash3.create().update(key).digest() : key);
936
- for (let i = 0; i < pad3.length; i++)
937
- pad3[i] ^= 54;
938
- this.iHash.update(pad3);
943
+ const pad4 = new Uint8Array(blockLen);
944
+ pad4.set(key.length > blockLen ? hash3.create().update(key).digest() : key);
945
+ for (let i = 0; i < pad4.length; i++)
946
+ pad4[i] ^= 54;
947
+ this.iHash.update(pad4);
939
948
  this.oHash = hash3.create();
940
- for (let i = 0; i < pad3.length; i++)
941
- pad3[i] ^= 54 ^ 92;
942
- this.oHash.update(pad3);
943
- clean(pad3);
949
+ for (let i = 0; i < pad4.length; i++)
950
+ pad4[i] ^= 54 ^ 92;
951
+ this.oHash.update(pad4);
952
+ clean(pad4);
944
953
  }
945
954
  update(buf) {
946
955
  aexists(this);
@@ -1679,19 +1688,19 @@ function charCodeToBase16(char) {
1679
1688
  return void 0;
1680
1689
  }
1681
1690
  function pad(bytes, options = {}) {
1682
- const { dir, size: size3 = 32 } = options;
1683
- if (size3 === 0)
1691
+ const { dir, size: size4 = 32 } = options;
1692
+ if (size4 === 0)
1684
1693
  return bytes;
1685
- if (bytes.length > size3)
1694
+ if (bytes.length > size4)
1686
1695
  throw new SizeExceedsPaddingSizeError({
1687
1696
  size: bytes.length,
1688
- targetSize: size3,
1697
+ targetSize: size4,
1689
1698
  type: "Bytes"
1690
1699
  });
1691
- const paddedBytes = new Uint8Array(size3);
1692
- for (let i = 0; i < size3; i++) {
1700
+ const paddedBytes = new Uint8Array(size4);
1701
+ for (let i = 0; i < size4; i++) {
1693
1702
  const padEnd = dir === "right";
1694
- paddedBytes[padEnd ? i : size3 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1];
1703
+ paddedBytes[padEnd ? i : size4 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1];
1695
1704
  }
1696
1705
  return paddedBytes;
1697
1706
  }
@@ -1750,17 +1759,17 @@ function assertEndOffset2(value, start, end) {
1750
1759
  }
1751
1760
  }
1752
1761
  function pad2(hex_, options = {}) {
1753
- const { dir, size: size3 = 32 } = options;
1754
- if (size3 === 0)
1762
+ const { dir, size: size4 = 32 } = options;
1763
+ if (size4 === 0)
1755
1764
  return hex_;
1756
1765
  const hex3 = hex_.replace("0x", "");
1757
- if (hex3.length > size3 * 2)
1766
+ if (hex3.length > size4 * 2)
1758
1767
  throw new SizeExceedsPaddingSizeError2({
1759
1768
  size: Math.ceil(hex3.length / 2),
1760
- targetSize: size3,
1769
+ targetSize: size4,
1761
1770
  type: "Hex"
1762
1771
  });
1763
- return `0x${hex3[dir === "right" ? "padEnd" : "padStart"](size3 * 2, "0")}`;
1772
+ return `0x${hex3[dir === "right" ? "padEnd" : "padStart"](size4 * 2, "0")}`;
1764
1773
  }
1765
1774
  function trim2(value, options = {}) {
1766
1775
  const { dir = "left" } = options;
@@ -1917,14 +1926,14 @@ function fromBytes(value, options = {}) {
1917
1926
  return hex3;
1918
1927
  }
1919
1928
  function fromNumber(value, options = {}) {
1920
- const { signed, size: size3 } = options;
1929
+ const { signed, size: size4 } = options;
1921
1930
  const value_ = BigInt(value);
1922
1931
  let maxValue;
1923
- if (size3) {
1932
+ if (size4) {
1924
1933
  if (signed)
1925
- maxValue = (1n << BigInt(size3) * 8n - 1n) - 1n;
1934
+ maxValue = (1n << BigInt(size4) * 8n - 1n) - 1n;
1926
1935
  else
1927
- maxValue = 2n ** (BigInt(size3) * 8n) - 1n;
1936
+ maxValue = 2n ** (BigInt(size4) * 8n) - 1n;
1928
1937
  } else if (typeof value === "number") {
1929
1938
  maxValue = BigInt(Number.MAX_SAFE_INTEGER);
1930
1939
  }
@@ -1935,14 +1944,14 @@ function fromNumber(value, options = {}) {
1935
1944
  max: maxValue ? `${maxValue}${suffix}` : void 0,
1936
1945
  min: `${minValue}${suffix}`,
1937
1946
  signed,
1938
- size: size3,
1947
+ size: size4,
1939
1948
  value: `${value}${suffix}`
1940
1949
  });
1941
1950
  }
1942
- const stringValue = (signed && value_ < 0 ? BigInt.asUintN(size3 * 8, BigInt(value_)) : value_).toString(16);
1951
+ const stringValue = (signed && value_ < 0 ? BigInt.asUintN(size4 * 8, BigInt(value_)) : value_).toString(16);
1943
1952
  const hex3 = `0x${stringValue}`;
1944
- if (size3)
1945
- return padLeft(hex3, size3);
1953
+ if (size4)
1954
+ return padLeft(hex3, size4);
1946
1955
  return hex3;
1947
1956
  }
1948
1957
  function fromString(value, options = {}) {
@@ -1951,11 +1960,11 @@ function fromString(value, options = {}) {
1951
1960
  function isEqual(hexA, hexB) {
1952
1961
  return equalBytes(fromHex(hexA), fromHex(hexB));
1953
1962
  }
1954
- function padLeft(value, size3) {
1955
- return pad2(value, { dir: "left", size: size3 });
1963
+ function padLeft(value, size4) {
1964
+ return pad2(value, { dir: "left", size: size4 });
1956
1965
  }
1957
- function padRight(value, size3) {
1958
- return pad2(value, { dir: "right", size: size3 });
1966
+ function padRight(value, size4) {
1967
+ return pad2(value, { dir: "right", size: size4 });
1959
1968
  }
1960
1969
  function random2(length) {
1961
1970
  return fromBytes(random(length));
@@ -1984,8 +1993,8 @@ function toBigInt(hex3, options = {}) {
1984
1993
  const value = BigInt(hex3);
1985
1994
  if (!signed)
1986
1995
  return value;
1987
- const size3 = (hex3.length - 2) / 2;
1988
- const max_unsigned = (1n << BigInt(size3) * 8n) - 1n;
1996
+ const size4 = (hex3.length - 2) / 2;
1997
+ const max_unsigned = (1n << BigInt(size4) * 8n) - 1n;
1989
1998
  const max_signed = max_unsigned >> 1n;
1990
1999
  if (value <= max_signed)
1991
2000
  return value;
@@ -2005,16 +2014,16 @@ function toBytes2(hex3, options = {}) {
2005
2014
  return fromHex(hex3, options);
2006
2015
  }
2007
2016
  function toNumber(hex3, options = {}) {
2008
- const { signed, size: size3 } = options;
2009
- if (!signed && !size3)
2017
+ const { signed, size: size4 } = options;
2018
+ if (!signed && !size4)
2010
2019
  return Number(hex3);
2011
2020
  return Number(toBigInt(hex3, options));
2012
2021
  }
2013
2022
  function toString(hex3, options = {}) {
2014
- const { size: size3 } = options;
2023
+ const { size: size4 } = options;
2015
2024
  let bytes = fromHex(hex3);
2016
- if (size3) {
2017
- assertSize(bytes, size3);
2025
+ if (size4) {
2026
+ assertSize(bytes, size4);
2018
2027
  bytes = trimRight(bytes);
2019
2028
  }
2020
2029
  return new TextDecoder().decode(bytes);
@@ -2041,8 +2050,8 @@ var init_Hex = __esm({
2041
2050
  encoder = /* @__PURE__ */ new TextEncoder();
2042
2051
  hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, "0"));
2043
2052
  IntegerOutOfRangeError = class extends BaseError {
2044
- constructor({ max, min, signed, size: size3, value }) {
2045
- super(`Number \`${value}\` is not in safe${size3 ? ` ${size3 * 8}-bit` : ""}${signed ? " signed" : " unsigned"} integer range ${max ? `(\`${min}\` to \`${max}\`)` : `(above \`${min}\`)`}`);
2053
+ constructor({ max, min, signed, size: size4, value }) {
2054
+ super(`Number \`${value}\` is not in safe${size4 ? ` ${size4 * 8}-bit` : ""}${signed ? " signed" : " unsigned"} integer range ${max ? `(\`${min}\` to \`${max}\`)` : `(above \`${min}\`)`}`);
2046
2055
  Object.defineProperty(this, "name", {
2047
2056
  enumerable: true,
2048
2057
  configurable: true,
@@ -2119,8 +2128,8 @@ var init_Hex = __esm({
2119
2128
  }
2120
2129
  };
2121
2130
  SliceOffsetOutOfBoundsError2 = class extends BaseError {
2122
- constructor({ offset, position, size: size3 }) {
2123
- super(`Slice ${position === "start" ? "starting" : "ending"} at offset \`${offset}\` is out-of-bounds (size: \`${size3}\`).`);
2131
+ constructor({ offset, position, size: size4 }) {
2132
+ super(`Slice ${position === "start" ? "starting" : "ending"} at offset \`${offset}\` is out-of-bounds (size: \`${size4}\`).`);
2124
2133
  Object.defineProperty(this, "name", {
2125
2134
  enumerable: true,
2126
2135
  configurable: true,
@@ -2130,8 +2139,8 @@ var init_Hex = __esm({
2130
2139
  }
2131
2140
  };
2132
2141
  SizeExceedsPaddingSizeError2 = class extends BaseError {
2133
- constructor({ size: size3, targetSize, type }) {
2134
- super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (\`${size3}\`) exceeds padding size (\`${targetSize}\`).`);
2142
+ constructor({ size: size4, targetSize, type }) {
2143
+ super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (\`${size4}\`) exceeds padding size (\`${targetSize}\`).`);
2135
2144
  Object.defineProperty(this, "name", {
2136
2145
  enumerable: true,
2137
2146
  configurable: true,
@@ -2210,21 +2219,21 @@ function fromArray(value) {
2210
2219
  return value instanceof Uint8Array ? value : new Uint8Array(value);
2211
2220
  }
2212
2221
  function fromBoolean2(value, options = {}) {
2213
- const { size: size3 } = options;
2222
+ const { size: size4 } = options;
2214
2223
  const bytes = new Uint8Array(1);
2215
2224
  bytes[0] = Number(value);
2216
- if (typeof size3 === "number") {
2217
- assertSize(bytes, size3);
2218
- return padLeft2(bytes, size3);
2225
+ if (typeof size4 === "number") {
2226
+ assertSize(bytes, size4);
2227
+ return padLeft2(bytes, size4);
2219
2228
  }
2220
2229
  return bytes;
2221
2230
  }
2222
2231
  function fromHex(value, options = {}) {
2223
- const { size: size3 } = options;
2232
+ const { size: size4 } = options;
2224
2233
  let hex3 = value;
2225
- if (size3) {
2226
- assertSize2(value, size3);
2227
- hex3 = padRight(value, size3);
2234
+ if (size4) {
2235
+ assertSize2(value, size4);
2236
+ hex3 = padRight(value, size4);
2228
2237
  }
2229
2238
  let hexString = hex3.slice(2);
2230
2239
  if (hexString.length % 2)
@@ -2246,22 +2255,22 @@ function fromNumber2(value, options) {
2246
2255
  return fromHex(hex3);
2247
2256
  }
2248
2257
  function fromString2(value, options = {}) {
2249
- const { size: size3 } = options;
2258
+ const { size: size4 } = options;
2250
2259
  const bytes = encoder2.encode(value);
2251
- if (typeof size3 === "number") {
2252
- assertSize(bytes, size3);
2253
- return padRight2(bytes, size3);
2260
+ if (typeof size4 === "number") {
2261
+ assertSize(bytes, size4);
2262
+ return padRight2(bytes, size4);
2254
2263
  }
2255
2264
  return bytes;
2256
2265
  }
2257
2266
  function isEqual2(bytesA, bytesB) {
2258
2267
  return equalBytes(bytesA, bytesB);
2259
2268
  }
2260
- function padLeft2(value, size3) {
2261
- return pad(value, { dir: "left", size: size3 });
2269
+ function padLeft2(value, size4) {
2270
+ return pad(value, { dir: "left", size: size4 });
2262
2271
  }
2263
- function padRight2(value, size3) {
2264
- return pad(value, { dir: "right", size: size3 });
2272
+ function padRight2(value, size4) {
2273
+ return pad(value, { dir: "right", size: size4 });
2265
2274
  }
2266
2275
  function random(length) {
2267
2276
  return crypto.getRandomValues(new Uint8Array(length));
@@ -2278,17 +2287,17 @@ function slice2(value, start, end, options = {}) {
2278
2287
  return value_;
2279
2288
  }
2280
2289
  function toBigInt2(bytes, options = {}) {
2281
- const { size: size3 } = options;
2282
- if (typeof size3 !== "undefined")
2283
- assertSize(bytes, size3);
2290
+ const { size: size4 } = options;
2291
+ if (typeof size4 !== "undefined")
2292
+ assertSize(bytes, size4);
2284
2293
  const hex3 = fromBytes(bytes, options);
2285
2294
  return toBigInt(hex3, options);
2286
2295
  }
2287
2296
  function toBoolean2(bytes, options = {}) {
2288
- const { size: size3 } = options;
2297
+ const { size: size4 } = options;
2289
2298
  let bytes_ = bytes;
2290
- if (typeof size3 !== "undefined") {
2291
- assertSize(bytes_, size3);
2299
+ if (typeof size4 !== "undefined") {
2300
+ assertSize(bytes_, size4);
2292
2301
  bytes_ = trimLeft2(bytes_);
2293
2302
  }
2294
2303
  if (bytes_.length > 1 || bytes_[0] > 1)
@@ -2299,17 +2308,17 @@ function toHex(value, options = {}) {
2299
2308
  return fromBytes(value, options);
2300
2309
  }
2301
2310
  function toNumber2(bytes, options = {}) {
2302
- const { size: size3 } = options;
2303
- if (typeof size3 !== "undefined")
2304
- assertSize(bytes, size3);
2311
+ const { size: size4 } = options;
2312
+ if (typeof size4 !== "undefined")
2313
+ assertSize(bytes, size4);
2305
2314
  const hex3 = fromBytes(bytes, options);
2306
2315
  return toNumber(hex3, options);
2307
2316
  }
2308
2317
  function toString2(bytes, options = {}) {
2309
- const { size: size3 } = options;
2318
+ const { size: size4 } = options;
2310
2319
  let bytes_ = bytes;
2311
- if (typeof size3 !== "undefined") {
2312
- assertSize(bytes_, size3);
2320
+ if (typeof size4 !== "undefined") {
2321
+ assertSize(bytes_, size4);
2313
2322
  bytes_ = trimRight(bytes_);
2314
2323
  }
2315
2324
  return decoder.decode(bytes_);
@@ -2380,8 +2389,8 @@ var init_Bytes = __esm({
2380
2389
  }
2381
2390
  };
2382
2391
  SliceOffsetOutOfBoundsError = class extends BaseError {
2383
- constructor({ offset, position, size: size3 }) {
2384
- super(`Slice ${position === "start" ? "starting" : "ending"} at offset \`${offset}\` is out-of-bounds (size: \`${size3}\`).`);
2392
+ constructor({ offset, position, size: size4 }) {
2393
+ super(`Slice ${position === "start" ? "starting" : "ending"} at offset \`${offset}\` is out-of-bounds (size: \`${size4}\`).`);
2385
2394
  Object.defineProperty(this, "name", {
2386
2395
  enumerable: true,
2387
2396
  configurable: true,
@@ -2391,8 +2400,8 @@ var init_Bytes = __esm({
2391
2400
  }
2392
2401
  };
2393
2402
  SizeExceedsPaddingSizeError = class extends BaseError {
2394
- constructor({ size: size3, targetSize, type }) {
2395
- super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (\`${size3}\`) exceeds padding size (\`${targetSize}\`).`);
2403
+ constructor({ size: size4, targetSize, type }) {
2404
+ super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (\`${size4}\`) exceeds padding size (\`${targetSize}\`).`);
2396
2405
  Object.defineProperty(this, "name", {
2397
2406
  enumerable: true,
2398
2407
  configurable: true,
@@ -2462,7 +2471,7 @@ var init_lru = __esm({
2462
2471
  "node_modules/ox/_esm/core/internal/lru.js"() {
2463
2472
  "use strict";
2464
2473
  LruMap = class extends Map {
2465
- constructor(size3) {
2474
+ constructor(size4) {
2466
2475
  super();
2467
2476
  Object.defineProperty(this, "maxSize", {
2468
2477
  enumerable: true,
@@ -2470,7 +2479,7 @@ var init_lru = __esm({
2470
2479
  writable: true,
2471
2480
  value: void 0
2472
2481
  });
2473
- this.maxSize = size3;
2482
+ this.maxSize = size4;
2474
2483
  }
2475
2484
  get(key) {
2476
2485
  const value = super.get(key);
@@ -2531,11 +2540,11 @@ function assert3(value, options = {}) {
2531
2540
  });
2532
2541
  }
2533
2542
  }
2534
- function checksum2(address2) {
2535
- if (checksum.has(address2))
2536
- return checksum.get(address2);
2537
- assert3(address2, { strict: false });
2538
- const hexAddress = address2.substring(2).toLowerCase();
2543
+ function checksum2(address3) {
2544
+ if (checksum.has(address3))
2545
+ return checksum.get(address3);
2546
+ assert3(address3, { strict: false });
2547
+ const hexAddress = address3.substring(2).toLowerCase();
2539
2548
  const hash3 = keccak256(fromString2(hexAddress), { as: "Bytes" });
2540
2549
  const characters = hexAddress.split("");
2541
2550
  for (let i = 0; i < 40; i += 2) {
@@ -2547,7 +2556,7 @@ function checksum2(address2) {
2547
2556
  }
2548
2557
  }
2549
2558
  const result = `0x${characters.join("")}`;
2550
- checksum.set(address2, result);
2559
+ checksum.set(address3, result);
2551
2560
  return result;
2552
2561
  }
2553
2562
  var addressRegex, InvalidAddressError, InvalidInputError, InvalidChecksumError;
@@ -2560,8 +2569,8 @@ var init_Address = __esm({
2560
2569
  init_Hash();
2561
2570
  addressRegex = /^0x[a-fA-F0-9]{40}$/;
2562
2571
  InvalidAddressError = class extends BaseError {
2563
- constructor({ address: address2, cause }) {
2564
- super(`Address "${address2}" is invalid.`, {
2572
+ constructor({ address: address3, cause }) {
2573
+ super(`Address "${address3}" is invalid.`, {
2565
2574
  cause
2566
2575
  });
2567
2576
  Object.defineProperty(this, "name", {
@@ -2737,9 +2746,9 @@ var init_AbiParameters = __esm({
2737
2746
  (function(encodePacked2) {
2738
2747
  function encode2(type, value, isArray = false) {
2739
2748
  if (type === "address") {
2740
- const address2 = value;
2741
- assert3(address2);
2742
- return padLeft(address2.toLowerCase(), isArray ? 32 : 0);
2749
+ const address3 = value;
2750
+ assert3(address3);
2751
+ return padLeft(address3.toLowerCase(), isArray ? 32 : 0);
2743
2752
  }
2744
2753
  if (type === "string")
2745
2754
  return fromString(value);
@@ -2750,18 +2759,18 @@ var init_AbiParameters = __esm({
2750
2759
  const intMatch = type.match(integerRegex);
2751
2760
  if (intMatch) {
2752
2761
  const [_type, baseType, bits = "256"] = intMatch;
2753
- const size3 = Number.parseInt(bits, 10) / 8;
2762
+ const size4 = Number.parseInt(bits, 10) / 8;
2754
2763
  return fromNumber(value, {
2755
- size: isArray ? 32 : size3,
2764
+ size: isArray ? 32 : size4,
2756
2765
  signed: baseType === "int"
2757
2766
  });
2758
2767
  }
2759
2768
  const bytesMatch = type.match(bytesRegex);
2760
2769
  if (bytesMatch) {
2761
- const [_type, size3] = bytesMatch;
2762
- if (Number.parseInt(size3, 10) !== (value.length - 2) / 2)
2770
+ const [_type, size4] = bytesMatch;
2771
+ if (Number.parseInt(size4, 10) !== (value.length - 2) / 2)
2763
2772
  throw new BytesSizeMismatchError({
2764
- expectedSize: Number.parseInt(size3, 10),
2773
+ expectedSize: Number.parseInt(size4, 10),
2765
2774
  value
2766
2775
  });
2767
2776
  return padRight(value, isArray ? 32 : 0);
@@ -2916,7 +2925,7 @@ __export(Base64_exports, {
2916
2925
  toString: () => toString3
2917
2926
  });
2918
2927
  function fromBytes2(value, options = {}) {
2919
- const { pad: pad3 = true, url: url2 = false } = options;
2928
+ const { pad: pad4 = true, url: url2 = false } = options;
2920
2929
  const encoded = new Uint8Array(Math.ceil(value.length / 3) * 4);
2921
2930
  for (let i = 0, j = 0; j < value.length; i += 4, j += 3) {
2922
2931
  const y = (value[j] << 16) + (value[j + 1] << 8) + (value[j + 2] | 0);
@@ -2928,9 +2937,9 @@ function fromBytes2(value, options = {}) {
2928
2937
  const k = value.length % 3;
2929
2938
  const end = Math.floor(value.length / 3) * 4 + (k && k + 1);
2930
2939
  let base643 = decoder2.decode(new Uint8Array(encoded.buffer, 0, end));
2931
- if (pad3 && k === 1)
2940
+ if (pad4 && k === 1)
2932
2941
  base643 += "==";
2933
- if (pad3 && k === 2)
2942
+ if (pad4 && k === 2)
2934
2943
  base643 += "=";
2935
2944
  if (url2)
2936
2945
  base643 = base643.replaceAll("+", "-").replaceAll("/", "_");
@@ -2944,8 +2953,8 @@ function fromString3(value, options = {}) {
2944
2953
  }
2945
2954
  function toBytes3(value) {
2946
2955
  const base643 = value.replace(/=+$/, "");
2947
- const size3 = base643.length;
2948
- const decoded = new Uint8Array(size3 + 3);
2956
+ const size4 = base643.length;
2957
+ const decoded = new Uint8Array(size4 + 3);
2949
2958
  encoder3.encodeInto(base643 + "===", decoded);
2950
2959
  for (let i = 0, j = 0; i < base643.length; i += 4, j += 3) {
2951
2960
  const x = (characterToInteger[decoded[i]] << 18) + (characterToInteger[decoded[i + 1]] << 12) + (characterToInteger[decoded[i + 2]] << 6) + characterToInteger[decoded[i + 3]];
@@ -2953,7 +2962,7 @@ function toBytes3(value) {
2953
2962
  decoded[j + 1] = x >> 8 & 255;
2954
2963
  decoded[j + 2] = x & 255;
2955
2964
  }
2956
- const decodedSize = (size3 >> 2) * 3 + (size3 % 4 && size3 % 4 - 1);
2965
+ const decodedSize = (size4 >> 2) * 3 + (size4 % 4 && size4 % 4 - 1);
2957
2966
  return new Uint8Array(decoded.buffer, 0, decodedSize);
2958
2967
  }
2959
2968
  function toHex2(value) {
@@ -3235,8 +3244,8 @@ var init_Cbor = __esm({
3235
3244
  }
3236
3245
  };
3237
3246
  StringTooLargeError = class extends BaseError {
3238
- constructor({ size: size3 }) {
3239
- super(`String length exceeds maximum (4294967295): ${size3}`);
3247
+ constructor({ size: size4 }) {
3248
+ super(`String length exceeds maximum (4294967295): ${size4}`);
3240
3249
  Object.defineProperty(this, "name", {
3241
3250
  enumerable: true,
3242
3251
  configurable: true,
@@ -3246,8 +3255,8 @@ var init_Cbor = __esm({
3246
3255
  }
3247
3256
  };
3248
3257
  ArrayTooLargeError = class extends BaseError {
3249
- constructor({ size: size3 }) {
3250
- super(`Array length exceeds maximum (4294967295): ${size3}`);
3258
+ constructor({ size: size4 }) {
3259
+ super(`Array length exceeds maximum (4294967295): ${size4}`);
3251
3260
  Object.defineProperty(this, "name", {
3252
3261
  enumerable: true,
3253
3262
  configurable: true,
@@ -3257,8 +3266,8 @@ var init_Cbor = __esm({
3257
3266
  }
3258
3267
  };
3259
3268
  ObjectTooLargeError = class extends BaseError {
3260
- constructor({ size: size3 }) {
3261
- super(`Object size exceeds maximum (4294967295): ${size3}`);
3269
+ constructor({ size: size4 }) {
3270
+ super(`Object size exceeds maximum (4294967295): ${size4}`);
3262
3271
  Object.defineProperty(this, "name", {
3263
3272
  enumerable: true,
3264
3273
  configurable: true,
@@ -3268,8 +3277,8 @@ var init_Cbor = __esm({
3268
3277
  }
3269
3278
  };
3270
3279
  ByteStringTooLargeError = class extends BaseError {
3271
- constructor({ size: size3 }) {
3272
- super(`Byte string length exceeds maximum (4294967295): ${size3}`);
3280
+ constructor({ size: size4 }) {
3281
+ super(`Byte string length exceeds maximum (4294967295): ${size4}`);
3273
3282
  Object.defineProperty(this, "name", {
3274
3283
  enumerable: true,
3275
3284
  configurable: true,
@@ -3334,37 +3343,37 @@ var init_Cbor = __esm({
3334
3343
  };
3335
3344
  throw new NumberTooLargeError({ number: value.toString(10) });
3336
3345
  }
3337
- const positiveNumber = -1 - value;
3346
+ const positiveNumber2 = -1 - value;
3338
3347
  if (value >= -24)
3339
3348
  return {
3340
3349
  length: 1,
3341
- encode: (cursor) => cursor.pushUint8(32 + positiveNumber)
3350
+ encode: (cursor) => cursor.pushUint8(32 + positiveNumber2)
3342
3351
  };
3343
- if (positiveNumber <= 255)
3352
+ if (positiveNumber2 <= 255)
3344
3353
  return {
3345
3354
  length: 2,
3346
3355
  // 1 byte prefix + 1 byte uint8
3347
3356
  encode: (cursor) => {
3348
3357
  cursor.pushUint8(56);
3349
- cursor.pushUint8(positiveNumber);
3358
+ cursor.pushUint8(positiveNumber2);
3350
3359
  }
3351
3360
  };
3352
- if (positiveNumber <= 65535)
3361
+ if (positiveNumber2 <= 65535)
3353
3362
  return {
3354
3363
  length: 3,
3355
3364
  // 1 byte prefix + 2 bytes uint16
3356
3365
  encode: (cursor) => {
3357
3366
  cursor.pushUint8(57);
3358
- cursor.pushUint16(positiveNumber);
3367
+ cursor.pushUint16(positiveNumber2);
3359
3368
  }
3360
3369
  };
3361
- if (positiveNumber <= 4294967295)
3370
+ if (positiveNumber2 <= 4294967295)
3362
3371
  return {
3363
3372
  length: 5,
3364
3373
  // 1 byte prefix + 4 bytes uint32
3365
3374
  encode: (cursor) => {
3366
3375
  cursor.pushUint8(58);
3367
- cursor.pushUint32(positiveNumber);
3376
+ cursor.pushUint32(positiveNumber2);
3368
3377
  }
3369
3378
  };
3370
3379
  throw new NumberTooLargeError({ number: value.toString(10) });
@@ -3372,142 +3381,142 @@ var init_Cbor = __esm({
3372
3381
  getEncodable2.number = number4;
3373
3382
  function string4(value) {
3374
3383
  const encoded = fromString2(value);
3375
- const size3 = encoded.length;
3376
- if (size3 <= 23)
3384
+ const size4 = encoded.length;
3385
+ if (size4 <= 23)
3377
3386
  return {
3378
- length: 1 + size3,
3387
+ length: 1 + size4,
3379
3388
  // 1 byte prefix + size bytes
3380
3389
  encode(cursor) {
3381
- cursor.pushUint8(96 + size3);
3382
- if (size3 > 0)
3390
+ cursor.pushUint8(96 + size4);
3391
+ if (size4 > 0)
3383
3392
  cursor.pushBytes(encoded);
3384
3393
  }
3385
3394
  };
3386
- if (size3 <= 255)
3395
+ if (size4 <= 255)
3387
3396
  return {
3388
- length: 2 + size3,
3397
+ length: 2 + size4,
3389
3398
  // 1 byte prefix + 1 byte uint8 + size bytes
3390
3399
  encode(cursor) {
3391
3400
  cursor.pushUint8(120);
3392
- cursor.pushUint8(size3);
3401
+ cursor.pushUint8(size4);
3393
3402
  cursor.pushBytes(encoded);
3394
3403
  }
3395
3404
  };
3396
- if (size3 <= 65535)
3405
+ if (size4 <= 65535)
3397
3406
  return {
3398
- length: 3 + size3,
3407
+ length: 3 + size4,
3399
3408
  // 1 byte prefix + 2 bytes uint16 + size bytes
3400
3409
  encode(cursor) {
3401
3410
  cursor.pushUint8(121);
3402
- cursor.pushUint16(size3);
3411
+ cursor.pushUint16(size4);
3403
3412
  cursor.pushBytes(encoded);
3404
3413
  }
3405
3414
  };
3406
- if (size3 <= 4294967295)
3415
+ if (size4 <= 4294967295)
3407
3416
  return {
3408
- length: 5 + size3,
3417
+ length: 5 + size4,
3409
3418
  // 1 byte prefix + 4 bytes uint32 + size bytes
3410
3419
  encode(cursor) {
3411
3420
  cursor.pushUint8(122);
3412
- cursor.pushUint32(size3);
3421
+ cursor.pushUint32(size4);
3413
3422
  cursor.pushBytes(encoded);
3414
3423
  }
3415
3424
  };
3416
- throw new StringTooLargeError({ size: size3 });
3425
+ throw new StringTooLargeError({ size: size4 });
3417
3426
  }
3418
3427
  getEncodable2.string = string4;
3419
3428
  function array2(value) {
3420
3429
  const items = value.map((item) => getEncodable2(item));
3421
3430
  const bodyLength = items.reduce((acc, item) => acc + item.length, 0);
3422
- const size3 = value.length;
3423
- if (size3 <= 23)
3431
+ const size4 = value.length;
3432
+ if (size4 <= 23)
3424
3433
  return {
3425
3434
  length: 1 + bodyLength,
3426
3435
  // 1 byte prefix + body length
3427
3436
  encode(cursor) {
3428
- cursor.pushUint8(128 + size3);
3437
+ cursor.pushUint8(128 + size4);
3429
3438
  for (const item of items)
3430
3439
  item.encode(cursor);
3431
3440
  }
3432
3441
  };
3433
- if (size3 <= 255)
3442
+ if (size4 <= 255)
3434
3443
  return {
3435
3444
  length: 2 + bodyLength,
3436
3445
  // 1 byte prefix + 1 byte uint8 + body length
3437
3446
  encode(cursor) {
3438
3447
  cursor.pushUint8(152);
3439
- cursor.pushUint8(size3);
3448
+ cursor.pushUint8(size4);
3440
3449
  for (const item of items)
3441
3450
  item.encode(cursor);
3442
3451
  }
3443
3452
  };
3444
- if (size3 <= 65535)
3453
+ if (size4 <= 65535)
3445
3454
  return {
3446
3455
  length: 3 + bodyLength,
3447
3456
  // 1 byte prefix + 2 bytes uint16 + body length
3448
3457
  encode(cursor) {
3449
3458
  cursor.pushUint8(153);
3450
- cursor.pushUint16(size3);
3459
+ cursor.pushUint16(size4);
3451
3460
  for (const item of items)
3452
3461
  item.encode(cursor);
3453
3462
  }
3454
3463
  };
3455
- if (size3 <= 4294967295)
3464
+ if (size4 <= 4294967295)
3456
3465
  return {
3457
3466
  length: 5 + bodyLength,
3458
3467
  // 1 byte prefix + 4 bytes uint32 + body length
3459
3468
  encode(cursor) {
3460
3469
  cursor.pushUint8(154);
3461
- cursor.pushUint32(size3);
3470
+ cursor.pushUint32(size4);
3462
3471
  for (const item of items)
3463
3472
  item.encode(cursor);
3464
3473
  }
3465
3474
  };
3466
- throw new ArrayTooLargeError({ size: size3 });
3475
+ throw new ArrayTooLargeError({ size: size4 });
3467
3476
  }
3468
3477
  getEncodable2.array = array2;
3469
3478
  function byteString(value) {
3470
- const size3 = value.byteLength;
3471
- if (size3 <= 23)
3479
+ const size4 = value.byteLength;
3480
+ if (size4 <= 23)
3472
3481
  return {
3473
- length: 1 + size3,
3482
+ length: 1 + size4,
3474
3483
  // 1 byte prefix + size bytes
3475
3484
  encode(cursor) {
3476
- cursor.pushUint8(64 + size3);
3485
+ cursor.pushUint8(64 + size4);
3477
3486
  cursor.pushBytes(value);
3478
3487
  }
3479
3488
  };
3480
- if (size3 <= 255)
3489
+ if (size4 <= 255)
3481
3490
  return {
3482
- length: 2 + size3,
3491
+ length: 2 + size4,
3483
3492
  // 1 byte prefix + 1 byte uint8 + size bytes
3484
3493
  encode(cursor) {
3485
3494
  cursor.pushUint8(88);
3486
- cursor.pushUint8(size3);
3495
+ cursor.pushUint8(size4);
3487
3496
  cursor.pushBytes(value);
3488
3497
  }
3489
3498
  };
3490
- if (size3 <= 65535)
3499
+ if (size4 <= 65535)
3491
3500
  return {
3492
- length: 3 + size3,
3501
+ length: 3 + size4,
3493
3502
  // 1 byte prefix + 2 bytes uint16 + size bytes
3494
3503
  encode(cursor) {
3495
3504
  cursor.pushUint8(89);
3496
- cursor.pushUint16(size3);
3505
+ cursor.pushUint16(size4);
3497
3506
  cursor.pushBytes(value);
3498
3507
  }
3499
3508
  };
3500
- if (size3 <= 4294967295)
3509
+ if (size4 <= 4294967295)
3501
3510
  return {
3502
- length: 5 + size3,
3511
+ length: 5 + size4,
3503
3512
  // 1 byte prefix + 4 bytes uint32 + size bytes
3504
3513
  encode(cursor) {
3505
3514
  cursor.pushUint8(90);
3506
- cursor.pushUint32(size3);
3515
+ cursor.pushUint32(size4);
3507
3516
  cursor.pushBytes(value);
3508
3517
  }
3509
3518
  };
3510
- throw new ByteStringTooLargeError({ size: size3 });
3519
+ throw new ByteStringTooLargeError({ size: size4 });
3511
3520
  }
3512
3521
  getEncodable2.byteString = byteString;
3513
3522
  function object2(value) {
@@ -3517,59 +3526,59 @@ var init_Cbor = __esm({
3517
3526
  value: getEncodable2(value[key])
3518
3527
  }));
3519
3528
  const bodyLength = entries.reduce((acc, entry) => acc + entry.key.length + entry.value.length, 0);
3520
- const size3 = keys.length;
3521
- if (size3 <= 23)
3529
+ const size4 = keys.length;
3530
+ if (size4 <= 23)
3522
3531
  return {
3523
3532
  length: 1 + bodyLength,
3524
3533
  // 1 byte prefix + body length
3525
3534
  encode(cursor) {
3526
- cursor.pushUint8(160 + size3);
3535
+ cursor.pushUint8(160 + size4);
3527
3536
  for (const entry of entries) {
3528
3537
  entry.key.encode(cursor);
3529
3538
  entry.value.encode(cursor);
3530
3539
  }
3531
3540
  }
3532
3541
  };
3533
- if (size3 <= 255)
3542
+ if (size4 <= 255)
3534
3543
  return {
3535
3544
  length: 2 + bodyLength,
3536
3545
  // 1 byte prefix + 1 byte uint8 + body length
3537
3546
  encode(cursor) {
3538
3547
  cursor.pushUint8(184);
3539
- cursor.pushUint8(size3);
3548
+ cursor.pushUint8(size4);
3540
3549
  for (const entry of entries) {
3541
3550
  entry.key.encode(cursor);
3542
3551
  entry.value.encode(cursor);
3543
3552
  }
3544
3553
  }
3545
3554
  };
3546
- if (size3 <= 65535)
3555
+ if (size4 <= 65535)
3547
3556
  return {
3548
3557
  length: 3 + bodyLength,
3549
3558
  // 1 byte prefix + 2 bytes uint16 + body length
3550
3559
  encode(cursor) {
3551
3560
  cursor.pushUint8(185);
3552
- cursor.pushUint16(size3);
3561
+ cursor.pushUint16(size4);
3553
3562
  for (const entry of entries) {
3554
3563
  entry.key.encode(cursor);
3555
3564
  entry.value.encode(cursor);
3556
3565
  }
3557
3566
  }
3558
3567
  };
3559
- if (size3 <= 4294967295)
3568
+ if (size4 <= 4294967295)
3560
3569
  return {
3561
3570
  length: 5 + bodyLength,
3562
3571
  // 1 byte prefix + 4 bytes uint32 + body length
3563
3572
  encode(cursor) {
3564
3573
  cursor.pushUint8(186);
3565
- cursor.pushUint32(size3);
3574
+ cursor.pushUint32(size4);
3566
3575
  for (const entry of entries) {
3567
3576
  entry.key.encode(cursor);
3568
3577
  entry.value.encode(cursor);
3569
3578
  }
3570
3579
  }
3571
3580
  };
3572
- throw new ObjectTooLargeError({ size: size3 });
3581
+ throw new ObjectTooLargeError({ size: size4 });
3573
3582
  }
3574
3583
  getEncodable2.object = object2;
3575
3584
  function map2(value) {
@@ -3577,55 +3586,55 @@ var init_Cbor = __esm({
3577
3586
  for (const [k, v] of value)
3578
3587
  entries.push({ key: getEncodable2(k), value: getEncodable2(v) });
3579
3588
  const bodyLength = entries.reduce((acc, entry) => acc + entry.key.length + entry.value.length, 0);
3580
- const size3 = value.size;
3581
- if (size3 <= 23)
3589
+ const size4 = value.size;
3590
+ if (size4 <= 23)
3582
3591
  return {
3583
3592
  length: 1 + bodyLength,
3584
3593
  encode(cursor) {
3585
- cursor.pushUint8(160 + size3);
3594
+ cursor.pushUint8(160 + size4);
3586
3595
  for (const entry of entries) {
3587
3596
  entry.key.encode(cursor);
3588
3597
  entry.value.encode(cursor);
3589
3598
  }
3590
3599
  }
3591
3600
  };
3592
- if (size3 <= 255)
3601
+ if (size4 <= 255)
3593
3602
  return {
3594
3603
  length: 2 + bodyLength,
3595
3604
  encode(cursor) {
3596
3605
  cursor.pushUint8(184);
3597
- cursor.pushUint8(size3);
3606
+ cursor.pushUint8(size4);
3598
3607
  for (const entry of entries) {
3599
3608
  entry.key.encode(cursor);
3600
3609
  entry.value.encode(cursor);
3601
3610
  }
3602
3611
  }
3603
3612
  };
3604
- if (size3 <= 65535)
3613
+ if (size4 <= 65535)
3605
3614
  return {
3606
3615
  length: 3 + bodyLength,
3607
3616
  encode(cursor) {
3608
3617
  cursor.pushUint8(185);
3609
- cursor.pushUint16(size3);
3618
+ cursor.pushUint16(size4);
3610
3619
  for (const entry of entries) {
3611
3620
  entry.key.encode(cursor);
3612
3621
  entry.value.encode(cursor);
3613
3622
  }
3614
3623
  }
3615
3624
  };
3616
- if (size3 <= 4294967295)
3625
+ if (size4 <= 4294967295)
3617
3626
  return {
3618
3627
  length: 5 + bodyLength,
3619
3628
  encode(cursor) {
3620
3629
  cursor.pushUint8(186);
3621
- cursor.pushUint32(size3);
3630
+ cursor.pushUint32(size4);
3622
3631
  for (const entry of entries) {
3623
3632
  entry.key.encode(cursor);
3624
3633
  entry.value.encode(cursor);
3625
3634
  }
3626
3635
  }
3627
3636
  };
3628
- throw new ObjectTooLargeError({ size: size3 });
3637
+ throw new ObjectTooLargeError({ size: size4 });
3629
3638
  }
3630
3639
  getEncodable2.map = map2;
3631
3640
  })(getEncodable || (getEncodable = {}));
@@ -5061,6 +5070,60 @@ var init_BodyDigest = __esm({
5061
5070
  }
5062
5071
  });
5063
5072
 
5073
+ // node_modules/mppx/dist/Constants.js
5074
+ var Constants_exports = {};
5075
+ __export(Constants_exports, {
5076
+ Headers: () => Headers2,
5077
+ Intents: () => Intents,
5078
+ MethodDetailKeys: () => MethodDetailKeys,
5079
+ Methods: () => Methods,
5080
+ Schemes: () => Schemes,
5081
+ SessionProtocols: () => SessionProtocols,
5082
+ getMethodDetail: () => getMethodDetail
5083
+ });
5084
+ function getMethodDetail(methodDetails, key) {
5085
+ if (!methodDetails || typeof methodDetails !== "object")
5086
+ return void 0;
5087
+ return methodDetails[key];
5088
+ }
5089
+ var Headers2, Schemes, Methods, Intents, MethodDetailKeys, SessionProtocols;
5090
+ var init_Constants = __esm({
5091
+ "node_modules/mppx/dist/Constants.js"() {
5092
+ "use strict";
5093
+ Headers2 = {
5094
+ acceptPayment: "Accept-Payment",
5095
+ authorization: "Authorization",
5096
+ paymentReceipt: "Payment-Receipt",
5097
+ paymentSession: "Payment-Session",
5098
+ paymentSessionSnapshot: "Payment-Session-Snapshot",
5099
+ wwwAuthenticate: "WWW-Authenticate"
5100
+ };
5101
+ Schemes = {
5102
+ payment: "Payment"
5103
+ };
5104
+ Methods = {
5105
+ evm: "evm",
5106
+ stripe: "stripe",
5107
+ tempo: "tempo"
5108
+ };
5109
+ Intents = {
5110
+ charge: "charge",
5111
+ session: "session",
5112
+ subscription: "subscription"
5113
+ };
5114
+ MethodDetailKeys = {
5115
+ sessionProtocol: "sessionProtocol",
5116
+ sessionSnapshot: "sessionSnapshot"
5117
+ };
5118
+ SessionProtocols = {
5119
+ /** Legacy contract-backed Tempo session protocol. */
5120
+ v1: "v1",
5121
+ /** TIP-1034 precompile-backed Tempo session protocol. */
5122
+ v2: "v2"
5123
+ };
5124
+ }
5125
+ });
5126
+
5064
5127
  // node_modules/mppx/dist/PaymentRequest.js
5065
5128
  var PaymentRequest_exports = {};
5066
5129
  __export(PaymentRequest_exports, {
@@ -6223,10 +6286,10 @@ var init_regexes = __esm({
6223
6286
  duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
6224
6287
  extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
6225
6288
  guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
6226
- uuid = (version3) => {
6227
- if (!version3)
6289
+ uuid = (version4) => {
6290
+ if (!version4)
6228
6291
  return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
6229
- return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version3}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
6292
+ return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version4}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
6230
6293
  };
6231
6294
  uuid4 = /* @__PURE__ */ uuid(4);
6232
6295
  uuid6 = /* @__PURE__ */ uuid(6);
@@ -6515,8 +6578,8 @@ var init_checks = __esm({
6515
6578
  });
6516
6579
  inst._zod.check = (payload) => {
6517
6580
  const input = payload.value;
6518
- const size3 = input.size;
6519
- if (size3 <= def.maximum)
6581
+ const size4 = input.size;
6582
+ if (size4 <= def.maximum)
6520
6583
  return;
6521
6584
  payload.issues.push({
6522
6585
  origin: getSizableOrigin(input),
@@ -6543,8 +6606,8 @@ var init_checks = __esm({
6543
6606
  });
6544
6607
  inst._zod.check = (payload) => {
6545
6608
  const input = payload.value;
6546
- const size3 = input.size;
6547
- if (size3 >= def.minimum)
6609
+ const size4 = input.size;
6610
+ if (size4 >= def.minimum)
6548
6611
  return;
6549
6612
  payload.issues.push({
6550
6613
  origin: getSizableOrigin(input),
@@ -6572,10 +6635,10 @@ var init_checks = __esm({
6572
6635
  });
6573
6636
  inst._zod.check = (payload) => {
6574
6637
  const input = payload.value;
6575
- const size3 = input.size;
6576
- if (size3 === def.size)
6638
+ const size4 = input.size;
6639
+ if (size4 === def.size)
6577
6640
  return;
6578
- const tooBig = size3 > def.size;
6641
+ const tooBig = size4 > def.size;
6579
6642
  payload.issues.push({
6580
6643
  origin: getSizableOrigin(input),
6581
6644
  ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size },
@@ -7624,7 +7687,7 @@ var init_schemas = __esm({
7624
7687
  try {
7625
7688
  if (parts.length !== 2)
7626
7689
  throw new Error();
7627
- const [address2, prefix] = parts;
7690
+ const [address3, prefix] = parts;
7628
7691
  if (!prefix)
7629
7692
  throw new Error();
7630
7693
  const prefixNum = Number(prefix);
@@ -7632,7 +7695,7 @@ var init_schemas = __esm({
7632
7695
  throw new Error();
7633
7696
  if (prefixNum < 0 || prefixNum > 128)
7634
7697
  throw new Error();
7635
- new URL(`http://[${address2}]`);
7698
+ new URL(`http://[${address3}]`);
7636
7699
  } catch {
7637
7700
  payload.issues.push({
7638
7701
  code: "invalid_format",
@@ -15985,11 +16048,11 @@ function _minSize(minimum, params) {
15985
16048
  });
15986
16049
  }
15987
16050
  // @__NO_SIDE_EFFECTS__
15988
- function _size(size3, params) {
16051
+ function _size(size4, params) {
15989
16052
  return new $ZodCheckSizeEquals({
15990
16053
  check: "size_equals",
15991
16054
  ...normalizeParams(params),
15992
- size: size3
16055
+ size: size4
15993
16056
  });
15994
16057
  }
15995
16058
  // @__NO_SIDE_EFFECTS__
@@ -19403,7 +19466,7 @@ function fromMethod2(method, parameters) {
19403
19466
  const { description, digest, expires, id, meta: meta4, realm, secretKey } = parameters;
19404
19467
  const request = fromMethod(method, parameters.request);
19405
19468
  return from4({
19406
- ...id ? { id } : { secretKey },
19469
+ ...id !== void 0 ? { id } : { secretKey },
19407
19470
  realm,
19408
19471
  method: methodName,
19409
19472
  intent,
@@ -19416,23 +19479,28 @@ function fromMethod2(method, parameters) {
19416
19479
  }
19417
19480
  function serialize2(challenge) {
19418
19481
  const parts = [
19419
- `id="${challenge.id}"`,
19420
- `realm="${challenge.realm}"`,
19421
- `method="${challenge.method}"`,
19422
- `intent="${challenge.intent}"`,
19423
- `request="${serialize(challenge.request)}"`
19482
+ authParam("id", challenge.id),
19483
+ authParam("realm", challenge.realm),
19484
+ authParam("method", challenge.method),
19485
+ authParam("intent", challenge.intent),
19486
+ authParam("request", serialize(challenge.request))
19424
19487
  ];
19425
19488
  if (challenge.description !== void 0)
19426
- parts.push(`description="${challenge.description}"`);
19489
+ parts.push(authParam("description", challenge.description));
19427
19490
  if (challenge.digest !== void 0)
19428
- parts.push(`digest="${challenge.digest}"`);
19491
+ parts.push(authParam("digest", challenge.digest));
19429
19492
  if (challenge.expires !== void 0)
19430
- parts.push(`expires="${challenge.expires}"`);
19493
+ parts.push(authParam("expires", challenge.expires));
19431
19494
  if (challenge.opaque !== void 0)
19432
- parts.push(`opaque="${challenge.opaque}"`);
19495
+ parts.push(authParam("opaque", challenge.opaque));
19433
19496
  else if (challenge.meta !== void 0)
19434
- parts.push(`opaque="${serialize(challenge.meta)}"`);
19435
- return `Payment ${parts.join(", ")}`;
19497
+ parts.push(authParam("opaque", serialize(challenge.meta)));
19498
+ return `${Schemes.payment} ${parts.join(", ")}`;
19499
+ }
19500
+ function authParam(name, value) {
19501
+ if (/[\r\n]/.test(value))
19502
+ throw new Error("Invalid quoted-string value.");
19503
+ return `${name}="${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
19436
19504
  }
19437
19505
  function deserialize2(value, options) {
19438
19506
  const params = extractPaymentAuthParams(value);
@@ -19442,6 +19510,8 @@ function deserialize2(value, options) {
19442
19510
  const { request, opaque, ...rest } = result;
19443
19511
  if (!request)
19444
19512
  throw new Error("Missing request parameter.");
19513
+ if (request.length > maxRequestParameterLength)
19514
+ throw new Error("Request parameter too large.");
19445
19515
  if (rest.method && !/^[a-z][a-z0-9:_-]*$/.test(rest.method))
19446
19516
  throw new Error(`Invalid method: "${rest.method}". Must be lowercase per spec.`);
19447
19517
  return from4({
@@ -19451,7 +19521,7 @@ function deserialize2(value, options) {
19451
19521
  }, options);
19452
19522
  }
19453
19523
  function extractPaymentAuthParams(header) {
19454
- const token = "Payment";
19524
+ const token = Schemes.payment;
19455
19525
  let inQuotes = false;
19456
19526
  let escaped = false;
19457
19527
  for (let i = 0; i < header.length; i++) {
@@ -19520,23 +19590,30 @@ function readAuthParamValue(input, start) {
19520
19590
  }
19521
19591
  function readQuotedAuthParamValue(input, start) {
19522
19592
  let i = start;
19523
- let value = "";
19524
19593
  let escaped = false;
19594
+ let segmentStart = start;
19595
+ let parts;
19525
19596
  while (i < input.length) {
19526
19597
  const char = input[i];
19527
19598
  i++;
19528
19599
  if (escaped) {
19529
- value += char;
19600
+ parts ??= [];
19601
+ parts.push(char);
19602
+ segmentStart = i;
19530
19603
  escaped = false;
19531
19604
  continue;
19532
19605
  }
19533
19606
  if (char === "\\") {
19607
+ parts ??= [];
19608
+ parts.push(input.slice(segmentStart, i - 1));
19609
+ segmentStart = i;
19534
19610
  escaped = true;
19535
19611
  continue;
19536
19612
  }
19537
- if (char === '"')
19613
+ if (char === '"') {
19614
+ const value = parts ? [...parts, input.slice(segmentStart, i - 1)].join("") : input.slice(start, i - 1);
19538
19615
  return [value, i];
19539
- value += char;
19616
+ }
19540
19617
  }
19541
19618
  throw new Error("Unterminated quoted-string.");
19542
19619
  }
@@ -19547,9 +19624,9 @@ function startsWithSchemeToken(value, index, token) {
19547
19624
  return Boolean(next && /\s/.test(next));
19548
19625
  }
19549
19626
  function fromHeaders(headers, options) {
19550
- const header = headers.get("WWW-Authenticate");
19627
+ const header = headers.get(Headers2.wwwAuthenticate);
19551
19628
  if (!header)
19552
- throw new Error("Missing WWW-Authenticate header.");
19629
+ throw new Error(`Missing ${Headers2.wwwAuthenticate} header.`);
19553
19630
  return deserialize2(header, options);
19554
19631
  }
19555
19632
  function fromResponse(response, options) {
@@ -19563,14 +19640,15 @@ function fromResponseList(response, options) {
19563
19640
  return fromHeadersList(response.headers, options);
19564
19641
  }
19565
19642
  function fromHeadersList(headers, options) {
19566
- const header = headers.get("WWW-Authenticate");
19643
+ const header = headers.get(Headers2.wwwAuthenticate);
19567
19644
  if (!header)
19568
- throw new Error("Missing WWW-Authenticate header.");
19645
+ throw new Error(`Missing ${Headers2.wwwAuthenticate} header.`);
19569
19646
  return deserializeList(header, options);
19570
19647
  }
19571
19648
  function deserializeList(value, options) {
19572
19649
  const starts = [];
19573
- for (const match of value.matchAll(/Payment\s+/gi)) {
19650
+ const schemePattern = new RegExp(`${Schemes.payment}\\s+`, "gi");
19651
+ for (const match of value.matchAll(schemePattern)) {
19574
19652
  starts.push(match.index);
19575
19653
  }
19576
19654
  if (starts.length === 0)
@@ -19606,14 +19684,16 @@ function computeId(challenge, options) {
19606
19684
  const mac3 = Hash_exports.hmac256(key, data, { as: "Bytes" });
19607
19685
  return Base64_exports.fromBytes(mac3, { url: true, pad: false });
19608
19686
  }
19609
- var Schema;
19687
+ var maxRequestParameterLength, Schema;
19610
19688
  var init_Challenge = __esm({
19611
19689
  "node_modules/mppx/dist/Challenge.js"() {
19612
19690
  "use strict";
19613
19691
  init_esm2();
19692
+ init_Constants();
19614
19693
  init_constantTimeEqual();
19615
19694
  init_PaymentRequest();
19616
19695
  init_zod();
19696
+ maxRequestParameterLength = 16 * 1024;
19617
19697
  Schema = object({
19618
19698
  /** Optional human-readable description of the payment. */
19619
19699
  description: optional(string2()),
@@ -19622,7 +19702,7 @@ var init_Challenge = __esm({
19622
19702
  /** Optional expiration timestamp (ISO 8601). */
19623
19703
  expires: optional(datetime3()),
19624
19704
  /** Unique challenge identifier (HMAC-bound). */
19625
- id: string2(),
19705
+ id: string2().check(_minLength(1)),
19626
19706
  /** Intent type (e.g., "charge", "session"). */
19627
19707
  intent: string2(),
19628
19708
  /** Payment method (e.g., "tempo", "stripe"). */
@@ -19652,7 +19732,7 @@ __export(Credential_exports, {
19652
19732
  serialize: () => serialize3
19653
19733
  });
19654
19734
  function deserialize3(value) {
19655
- const prefixMatch = value.match(/^Payment\s+(.+)$/i);
19735
+ const prefixMatch = value.match(new RegExp(`^${Schemes.payment}\\s+(.+)$`, "i"));
19656
19736
  if (!prefixMatch?.[1])
19657
19737
  throw new MissingPaymentSchemeError();
19658
19738
  try {
@@ -19701,7 +19781,7 @@ function from5(parameters) {
19701
19781
  };
19702
19782
  }
19703
19783
  function fromRequest(request) {
19704
- const header = request.headers.get("Authorization");
19784
+ const header = request.headers.get(Headers2.authorization);
19705
19785
  if (!header)
19706
19786
  throw new MissingAuthorizationHeaderError();
19707
19787
  const payment = extractPaymentScheme(header);
@@ -19723,11 +19803,11 @@ function serialize3(credential) {
19723
19803
  };
19724
19804
  const json2 = JSON.stringify(wire);
19725
19805
  const encoded = Base64_exports.fromString(json2, { pad: false, url: true });
19726
- return `Payment ${encoded}`;
19806
+ return `${Schemes.payment} ${encoded}`;
19727
19807
  }
19728
19808
  function extractPaymentScheme(header) {
19729
- const schemes = header.split(",").map((s) => s.trim());
19730
- return schemes.find((s) => /^Payment\s+/i.test(s)) ?? null;
19809
+ const schemes2 = header.split(",").map((s) => s.trim());
19810
+ return schemes2.find((s) => new RegExp(`^${Schemes.payment}\\s+`, "i").test(s)) ?? null;
19731
19811
  }
19732
19812
  var MissingAuthorizationHeaderError, MissingPaymentSchemeError, InvalidCredentialEncodingError;
19733
19813
  var init_Credential = __esm({
@@ -19735,6 +19815,7 @@ var init_Credential = __esm({
19735
19815
  "use strict";
19736
19816
  init_esm2();
19737
19817
  init_Challenge();
19818
+ init_Constants();
19738
19819
  init_PaymentRequest();
19739
19820
  MissingAuthorizationHeaderError = class extends Error {
19740
19821
  name = "MissingAuthorizationHeaderError";
@@ -19765,6 +19846,7 @@ __export(Errors_exports2, {
19765
19846
  ChannelClosedError: () => ChannelClosedError,
19766
19847
  ChannelNotFoundError: () => ChannelNotFoundError,
19767
19848
  DeltaTooSmallError: () => DeltaTooSmallError,
19849
+ Hints: () => Hints,
19768
19850
  InsufficientBalanceError: () => InsufficientBalanceError,
19769
19851
  InvalidChallengeError: () => InvalidChallengeError,
19770
19852
  InvalidPayloadError: () => InvalidPayloadError,
@@ -19779,13 +19861,20 @@ __export(Errors_exports2, {
19779
19861
  SignerMismatchError: () => SignerMismatchError,
19780
19862
  VerificationFailedError: () => VerificationFailedError
19781
19863
  });
19782
- var PaymentError, MalformedCredentialError, InvalidChallengeError, VerificationFailedError, PaymentActionRequiredError, PaymentExpiredError, PaymentRequiredError2, InvalidPayloadError, BadRequestError, PaymentInsufficientError, PaymentMethodUnsupportedError, InsufficientBalanceError, InvalidSignatureError, SignerMismatchError, AmountExceedsDepositError, DeltaTooSmallError, ChannelNotFoundError, ChannelClosedError;
19864
+ var Hints, PaymentError, MalformedCredentialError, InvalidChallengeError, VerificationFailedError, PaymentActionRequiredError, PaymentExpiredError, PaymentRequiredError2, InvalidPayloadError, BadRequestError, PaymentInsufficientError, PaymentMethodUnsupportedError, InsufficientBalanceError, InvalidSignatureError, SignerMismatchError, AmountExceedsDepositError, DeltaTooSmallError, ChannelNotFoundError, ChannelClosedError;
19783
19865
  var init_Errors2 = __esm({
19784
19866
  "node_modules/mppx/dist/Errors.js"() {
19785
19867
  "use strict";
19868
+ Hints = {
19869
+ paymentRequired: "Use a supported wallet to pay for this resource using one of the supported payment methods returned in the WWW-Authenticate header. See https://mpp.dev/tools/wallet.md",
19870
+ malformedCredential: "Use a supported wallet to construct valid credentials for one of the supported payment methods returned in the WWW-Authenticate header. See https://mpp.dev/tools/wallet.md",
19871
+ methodUnsupported: "Use a supported wallet to pay for this resource using one of the supported payment methods returned in the WWW-Authenticate header. See https://mpp.dev/tools/wallet.md"
19872
+ };
19786
19873
  PaymentError = class extends Error {
19787
19874
  /** HTTP status code. */
19788
19875
  status = 402;
19876
+ /** Actionable hint for resolving the error (RFC 9457 extension member). */
19877
+ hint;
19789
19878
  /** Converts the error to RFC 9457 Problem Details format. */
19790
19879
  toProblemDetails(challengeId) {
19791
19880
  return {
@@ -19793,6 +19882,7 @@ var init_Errors2 = __esm({
19793
19882
  title: this.title,
19794
19883
  status: this.status,
19795
19884
  detail: this.message,
19885
+ ...this.hint && { hint: this.hint },
19796
19886
  ...challengeId && { challengeId }
19797
19887
  };
19798
19888
  }
@@ -19802,6 +19892,7 @@ var init_Errors2 = __esm({
19802
19892
  title = "Malformed Credential";
19803
19893
  status = 402;
19804
19894
  type = "https://paymentauth.org/problems/malformed-credential";
19895
+ hint = Hints.malformedCredential;
19805
19896
  constructor(options = {}) {
19806
19897
  const { reason } = options;
19807
19898
  super(reason ? `Credential is malformed: ${reason}.` : "Credential is malformed.");
@@ -19850,6 +19941,7 @@ var init_Errors2 = __esm({
19850
19941
  name = "PaymentRequiredError";
19851
19942
  title = "Payment Required";
19852
19943
  type = "https://paymentauth.org/problems/payment-required";
19944
+ hint = Hints.paymentRequired;
19853
19945
  constructor(options = {}) {
19854
19946
  const { description } = options;
19855
19947
  const parts = ["Payment is required"];
@@ -19891,6 +19983,7 @@ var init_Errors2 = __esm({
19891
19983
  title = "Method Unsupported";
19892
19984
  status = 400;
19893
19985
  type = "https://paymentauth.org/problems/method-unsupported";
19986
+ hint = Hints.methodUnsupported;
19894
19987
  constructor(options = {}) {
19895
19988
  const { method } = options;
19896
19989
  super(method ? `Payment method "${method}" is not supported.` : "Payment method is not supported.");
@@ -20023,147 +20116,1120 @@ var init_Expires = __esm({
20023
20116
  }
20024
20117
  });
20025
20118
 
20026
- // node_modules/mppx/dist/Mcp.js
20027
- var Mcp_exports = {};
20028
- __export(Mcp_exports, {
20029
- credentialMetaKey: () => credentialMetaKey,
20030
- paymentRequiredCode: () => paymentRequiredCode,
20031
- paymentVerificationFailedCode: () => paymentVerificationFailedCode,
20032
- receiptMetaKey: () => receiptMetaKey
20119
+ // node_modules/viem/_esm/utils/data/isHex.js
20120
+ function isHex(value, { strict = true } = {}) {
20121
+ if (!value)
20122
+ return false;
20123
+ if (typeof value !== "string")
20124
+ return false;
20125
+ return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith("0x");
20126
+ }
20127
+ var init_isHex = __esm({
20128
+ "node_modules/viem/_esm/utils/data/isHex.js"() {
20129
+ "use strict";
20130
+ }
20033
20131
  });
20034
- var paymentRequiredCode, paymentVerificationFailedCode, credentialMetaKey, receiptMetaKey;
20035
- var init_Mcp = __esm({
20036
- "node_modules/mppx/dist/Mcp.js"() {
20132
+
20133
+ // node_modules/viem/_esm/utils/data/size.js
20134
+ function size3(value) {
20135
+ if (isHex(value, { strict: false }))
20136
+ return Math.ceil((value.length - 2) / 2);
20137
+ return value.length;
20138
+ }
20139
+ var init_size = __esm({
20140
+ "node_modules/viem/_esm/utils/data/size.js"() {
20037
20141
  "use strict";
20038
- paymentRequiredCode = -32042;
20039
- paymentVerificationFailedCode = -32043;
20040
- credentialMetaKey = "org.paymentauth/credential";
20041
- receiptMetaKey = "org.paymentauth/receipt";
20142
+ init_isHex();
20042
20143
  }
20043
20144
  });
20044
20145
 
20045
- // node_modules/mppx/dist/Method.js
20046
- var Method_exports = {};
20047
- __export(Method_exports, {
20048
- from: () => from6,
20049
- toClient: () => toClient,
20050
- toServer: () => toServer
20146
+ // node_modules/viem/_esm/errors/version.js
20147
+ var version3;
20148
+ var init_version2 = __esm({
20149
+ "node_modules/viem/_esm/errors/version.js"() {
20150
+ "use strict";
20151
+ version3 = "2.54.4";
20152
+ }
20051
20153
  });
20052
- function from6(method) {
20053
- return method;
20154
+
20155
+ // node_modules/viem/_esm/errors/base.js
20156
+ function walk2(err, fn) {
20157
+ if (fn?.(err))
20158
+ return err;
20159
+ if (err && typeof err === "object" && "cause" in err && err.cause !== void 0)
20160
+ return walk2(err.cause, fn);
20161
+ return fn ? null : err;
20054
20162
  }
20055
- function toClient(method, options) {
20056
- const { context, createCredential } = options;
20057
- return {
20058
- ...method,
20059
- context,
20060
- createCredential
20061
- };
20163
+ var errorConfig, BaseError3;
20164
+ var init_base = __esm({
20165
+ "node_modules/viem/_esm/errors/base.js"() {
20166
+ "use strict";
20167
+ init_version2();
20168
+ errorConfig = {
20169
+ getDocsUrl: ({ docsBaseUrl, docsPath = "", docsSlug }) => docsPath ? `${docsBaseUrl ?? "https://viem.sh"}${docsPath}${docsSlug ? `#${docsSlug}` : ""}` : void 0,
20170
+ version: `viem@${version3}`
20171
+ };
20172
+ BaseError3 = class _BaseError extends Error {
20173
+ constructor(shortMessage, args = {}) {
20174
+ const details = (() => {
20175
+ if (args.cause instanceof _BaseError)
20176
+ return args.cause.details;
20177
+ if (args.cause?.message)
20178
+ return args.cause.message;
20179
+ return args.details;
20180
+ })();
20181
+ const docsPath = (() => {
20182
+ if (args.cause instanceof _BaseError)
20183
+ return args.cause.docsPath || args.docsPath;
20184
+ return args.docsPath;
20185
+ })();
20186
+ const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath });
20187
+ const message = [
20188
+ shortMessage || "An error occurred.",
20189
+ "",
20190
+ ...args.metaMessages ? [...args.metaMessages, ""] : [],
20191
+ ...docsUrl ? [`Docs: ${docsUrl}`] : [],
20192
+ ...details ? [`Details: ${details}`] : [],
20193
+ ...errorConfig.version ? [`Version: ${errorConfig.version}`] : []
20194
+ ].join("\n");
20195
+ super(message, args.cause ? { cause: args.cause } : void 0);
20196
+ Object.defineProperty(this, "details", {
20197
+ enumerable: true,
20198
+ configurable: true,
20199
+ writable: true,
20200
+ value: void 0
20201
+ });
20202
+ Object.defineProperty(this, "docsPath", {
20203
+ enumerable: true,
20204
+ configurable: true,
20205
+ writable: true,
20206
+ value: void 0
20207
+ });
20208
+ Object.defineProperty(this, "metaMessages", {
20209
+ enumerable: true,
20210
+ configurable: true,
20211
+ writable: true,
20212
+ value: void 0
20213
+ });
20214
+ Object.defineProperty(this, "shortMessage", {
20215
+ enumerable: true,
20216
+ configurable: true,
20217
+ writable: true,
20218
+ value: void 0
20219
+ });
20220
+ Object.defineProperty(this, "version", {
20221
+ enumerable: true,
20222
+ configurable: true,
20223
+ writable: true,
20224
+ value: void 0
20225
+ });
20226
+ Object.defineProperty(this, "name", {
20227
+ enumerable: true,
20228
+ configurable: true,
20229
+ writable: true,
20230
+ value: "BaseError"
20231
+ });
20232
+ this.details = details;
20233
+ this.docsPath = docsPath;
20234
+ this.metaMessages = args.metaMessages;
20235
+ this.name = args.name ?? this.name;
20236
+ this.shortMessage = shortMessage;
20237
+ this.version = version3;
20238
+ }
20239
+ walk(fn) {
20240
+ return walk2(this, fn);
20241
+ }
20242
+ };
20243
+ }
20244
+ });
20245
+
20246
+ // node_modules/viem/_esm/errors/data.js
20247
+ var SizeExceedsPaddingSizeError3;
20248
+ var init_data = __esm({
20249
+ "node_modules/viem/_esm/errors/data.js"() {
20250
+ "use strict";
20251
+ init_base();
20252
+ SizeExceedsPaddingSizeError3 = class extends BaseError3 {
20253
+ constructor({ size: size4, targetSize, type }) {
20254
+ super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size4}) exceeds padding size (${targetSize}).`, { name: "SizeExceedsPaddingSizeError" });
20255
+ }
20256
+ };
20257
+ }
20258
+ });
20259
+
20260
+ // node_modules/viem/_esm/utils/data/pad.js
20261
+ function pad3(hexOrBytes, { dir, size: size4 = 32 } = {}) {
20262
+ if (typeof hexOrBytes === "string")
20263
+ return padHex(hexOrBytes, { dir, size: size4 });
20264
+ return padBytes(hexOrBytes, { dir, size: size4 });
20062
20265
  }
20063
- function toServer(method, options) {
20064
- const { authorize, defaults, extensions, html, request, respond, stableBinding, transport, verify: verify3 } = options;
20065
- return {
20066
- ...method,
20067
- authorize,
20068
- defaults,
20069
- extensions,
20070
- html,
20071
- request,
20072
- respond,
20073
- stableBinding,
20074
- transport,
20075
- verify: verify3
20076
- };
20266
+ function padHex(hex_, { dir, size: size4 = 32 } = {}) {
20267
+ if (size4 === null)
20268
+ return hex_;
20269
+ const hex3 = hex_.replace("0x", "");
20270
+ if (hex3.length > size4 * 2)
20271
+ throw new SizeExceedsPaddingSizeError3({
20272
+ size: Math.ceil(hex3.length / 2),
20273
+ targetSize: size4,
20274
+ type: "hex"
20275
+ });
20276
+ return `0x${hex3[dir === "right" ? "padEnd" : "padStart"](size4 * 2, "0")}`;
20077
20277
  }
20078
- var init_Method = __esm({
20079
- "node_modules/mppx/dist/Method.js"() {
20278
+ function padBytes(bytes, { dir, size: size4 = 32 } = {}) {
20279
+ if (size4 === null)
20280
+ return bytes;
20281
+ if (bytes.length > size4)
20282
+ throw new SizeExceedsPaddingSizeError3({
20283
+ size: bytes.length,
20284
+ targetSize: size4,
20285
+ type: "bytes"
20286
+ });
20287
+ const paddedBytes = new Uint8Array(size4);
20288
+ for (let i = 0; i < size4; i++) {
20289
+ const padEnd = dir === "right";
20290
+ paddedBytes[padEnd ? i : size4 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1];
20291
+ }
20292
+ return paddedBytes;
20293
+ }
20294
+ var init_pad = __esm({
20295
+ "node_modules/viem/_esm/utils/data/pad.js"() {
20080
20296
  "use strict";
20297
+ init_data();
20081
20298
  }
20082
20299
  });
20083
20300
 
20084
- // node_modules/mppx/dist/Receipt.js
20085
- var Receipt_exports = {};
20086
- __export(Receipt_exports, {
20087
- Schema: () => Schema2,
20088
- deserialize: () => deserialize4,
20089
- from: () => from7,
20090
- fromResponse: () => fromResponse2,
20091
- serialize: () => serialize4
20301
+ // node_modules/viem/_esm/errors/encoding.js
20302
+ var IntegerOutOfRangeError2, SizeOverflowError3;
20303
+ var init_encoding = __esm({
20304
+ "node_modules/viem/_esm/errors/encoding.js"() {
20305
+ "use strict";
20306
+ init_base();
20307
+ IntegerOutOfRangeError2 = class extends BaseError3 {
20308
+ constructor({ max, min, signed, size: size4, value }) {
20309
+ super(`Number "${value}" is not in safe ${size4 ? `${size4 * 8}-bit ${signed ? "signed" : "unsigned"} ` : ""}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: "IntegerOutOfRangeError" });
20310
+ }
20311
+ };
20312
+ SizeOverflowError3 = class extends BaseError3 {
20313
+ constructor({ givenSize, maxSize }) {
20314
+ super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: "SizeOverflowError" });
20315
+ }
20316
+ };
20317
+ }
20092
20318
  });
20093
- function deserialize4(encoded) {
20094
- const json2 = Base64_exports.toString(encoded);
20095
- return from7(JSON.parse(json2));
20319
+
20320
+ // node_modules/viem/_esm/utils/encoding/fromHex.js
20321
+ function assertSize3(hexOrBytes, { size: size4 }) {
20322
+ if (size3(hexOrBytes) > size4)
20323
+ throw new SizeOverflowError3({
20324
+ givenSize: size3(hexOrBytes),
20325
+ maxSize: size4
20326
+ });
20096
20327
  }
20097
- function from7(parameters) {
20098
- return Schema2.parse(parameters);
20328
+ var init_fromHex = __esm({
20329
+ "node_modules/viem/_esm/utils/encoding/fromHex.js"() {
20330
+ "use strict";
20331
+ init_encoding();
20332
+ init_size();
20333
+ }
20334
+ });
20335
+
20336
+ // node_modules/viem/_esm/utils/encoding/toHex.js
20337
+ function toHex3(value, opts = {}) {
20338
+ if (typeof value === "number" || typeof value === "bigint")
20339
+ return numberToHex(value, opts);
20340
+ if (typeof value === "string") {
20341
+ return stringToHex(value, opts);
20342
+ }
20343
+ if (typeof value === "boolean")
20344
+ return boolToHex(value, opts);
20345
+ return bytesToHex(value, opts);
20099
20346
  }
20100
- function serialize4(receipt) {
20101
- const json2 = JSON.stringify(receipt);
20102
- return Base64_exports.fromString(json2, { pad: false, url: true });
20347
+ function boolToHex(value, opts = {}) {
20348
+ const hex3 = `0x${Number(value)}`;
20349
+ if (typeof opts.size === "number") {
20350
+ assertSize3(hex3, { size: opts.size });
20351
+ return pad3(hex3, { size: opts.size });
20352
+ }
20353
+ return hex3;
20103
20354
  }
20104
- function fromResponse2(response) {
20105
- const header = response.headers.get("Payment-Receipt");
20106
- if (!header)
20107
- throw new Error("Missing Payment-Receipt header.");
20108
- return deserialize4(header);
20355
+ function bytesToHex(value, opts = {}) {
20356
+ let string4 = "";
20357
+ for (let i = 0; i < value.length; i++) {
20358
+ string4 += hexes2[value[i]];
20359
+ }
20360
+ const hex3 = `0x${string4}`;
20361
+ if (typeof opts.size === "number") {
20362
+ assertSize3(hex3, { size: opts.size });
20363
+ return pad3(hex3, { dir: "right", size: opts.size });
20364
+ }
20365
+ return hex3;
20109
20366
  }
20110
- var Schema2;
20111
- var init_Receipt = __esm({
20112
- "node_modules/mppx/dist/Receipt.js"() {
20113
- "use strict";
20114
- init_esm2();
20115
- init_zod();
20116
- Schema2 = object({
20117
- /** Payment method used (e.g., "tempo", "stripe"). */
20118
- method: string2(),
20119
- /** Method-specific reference (e.g., transaction hash). */
20120
- reference: string2(),
20121
- /** Optional external reference ID echoed from the credential payload. */
20122
- externalId: optional(string2()),
20123
- /** Optional server-issued subscription identifier for recurring payments. */
20124
- subscriptionId: optional(string2()),
20125
- /** Payment status. Always "success" — failures use 402 + Problem Details. */
20126
- status: literal("success"),
20127
- /** RFC 3339 settlement timestamp. */
20128
- timestamp: datetime3()
20367
+ function numberToHex(value_, opts = {}) {
20368
+ const { signed, size: size4 } = opts;
20369
+ const value = BigInt(value_);
20370
+ let maxValue;
20371
+ if (size4) {
20372
+ if (signed)
20373
+ maxValue = (1n << BigInt(size4) * 8n - 1n) - 1n;
20374
+ else
20375
+ maxValue = 2n ** (BigInt(size4) * 8n) - 1n;
20376
+ } else if (typeof value_ === "number") {
20377
+ maxValue = BigInt(Number.MAX_SAFE_INTEGER);
20378
+ }
20379
+ const minValue = typeof maxValue === "bigint" && signed ? -maxValue - 1n : 0;
20380
+ if (maxValue && value > maxValue || value < minValue) {
20381
+ const suffix = typeof value_ === "bigint" ? "n" : "";
20382
+ throw new IntegerOutOfRangeError2({
20383
+ max: maxValue ? `${maxValue}${suffix}` : void 0,
20384
+ min: `${minValue}${suffix}`,
20385
+ signed,
20386
+ size: size4,
20387
+ value: `${value_}${suffix}`
20129
20388
  });
20130
20389
  }
20390
+ const hex3 = `0x${(signed && value < 0 ? (1n << BigInt(size4 * 8)) + BigInt(value) : value).toString(16)}`;
20391
+ if (size4)
20392
+ return pad3(hex3, { size: size4 });
20393
+ return hex3;
20394
+ }
20395
+ function stringToHex(value_, opts = {}) {
20396
+ const value = encoder4.encode(value_);
20397
+ return bytesToHex(value, opts);
20398
+ }
20399
+ var hexes2, encoder4;
20400
+ var init_toHex = __esm({
20401
+ "node_modules/viem/_esm/utils/encoding/toHex.js"() {
20402
+ "use strict";
20403
+ init_encoding();
20404
+ init_pad();
20405
+ init_fromHex();
20406
+ hexes2 = /* @__PURE__ */ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, "0"));
20407
+ encoder4 = /* @__PURE__ */ new TextEncoder();
20408
+ }
20131
20409
  });
20132
20410
 
20133
- // node_modules/mppx/dist/Store.js
20134
- var Store_exports = {};
20135
- __export(Store_exports, {
20136
- cloudflare: () => cloudflare,
20137
- from: () => from8,
20138
- memory: () => memory,
20139
- redis: () => redis,
20140
- upstash: () => upstash
20141
- });
20142
- function from8(store) {
20143
- return store;
20411
+ // node_modules/viem/_esm/utils/encoding/toBytes.js
20412
+ function toBytes4(value, opts = {}) {
20413
+ if (typeof value === "number" || typeof value === "bigint")
20414
+ return numberToBytes(value, opts);
20415
+ if (typeof value === "boolean")
20416
+ return boolToBytes(value, opts);
20417
+ if (isHex(value))
20418
+ return hexToBytes(value, opts);
20419
+ return stringToBytes(value, opts);
20144
20420
  }
20145
- function wrapJsonUpdate(update) {
20146
- if (!update)
20147
- return {};
20148
- return {
20149
- async update(key, fn) {
20150
- return update(key, (current) => {
20151
- const parsed = current == null ? null : Json_exports.parse(current);
20152
- const change = fn(parsed);
20153
- if (change.op !== "set")
20154
- return change;
20155
- return { ...change, value: Json_exports.stringify(change.value) };
20156
- });
20157
- }
20158
- };
20421
+ function boolToBytes(value, opts = {}) {
20422
+ const bytes = new Uint8Array(1);
20423
+ bytes[0] = Number(value);
20424
+ if (typeof opts.size === "number") {
20425
+ assertSize3(bytes, { size: opts.size });
20426
+ return pad3(bytes, { size: opts.size });
20427
+ }
20428
+ return bytes;
20159
20429
  }
20160
- function cloudflare(kv) {
20161
- return from8({
20162
- async get(key) {
20163
- const raw = await kv.get(key);
20164
- if (raw == null)
20165
- return null;
20166
- return Json_exports.parse(raw);
20430
+ function charCodeToBase162(char) {
20431
+ if (char >= charCodeMap2.zero && char <= charCodeMap2.nine)
20432
+ return char - charCodeMap2.zero;
20433
+ if (char >= charCodeMap2.A && char <= charCodeMap2.F)
20434
+ return char - (charCodeMap2.A - 10);
20435
+ if (char >= charCodeMap2.a && char <= charCodeMap2.f)
20436
+ return char - (charCodeMap2.a - 10);
20437
+ return void 0;
20438
+ }
20439
+ function hexToBytes(hex_, opts = {}) {
20440
+ let hex3 = hex_;
20441
+ if (opts.size) {
20442
+ assertSize3(hex3, { size: opts.size });
20443
+ hex3 = pad3(hex3, { dir: "right", size: opts.size });
20444
+ }
20445
+ let hexString = hex3.slice(2);
20446
+ if (hexString.length % 2)
20447
+ hexString = `0${hexString}`;
20448
+ const length = hexString.length / 2;
20449
+ const bytes = new Uint8Array(length);
20450
+ for (let index = 0, j = 0; index < length; index++) {
20451
+ const nibbleLeft = charCodeToBase162(hexString.charCodeAt(j++));
20452
+ const nibbleRight = charCodeToBase162(hexString.charCodeAt(j++));
20453
+ if (nibbleLeft === void 0 || nibbleRight === void 0) {
20454
+ throw new BaseError3(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`);
20455
+ }
20456
+ bytes[index] = nibbleLeft * 16 + nibbleRight;
20457
+ }
20458
+ return bytes;
20459
+ }
20460
+ function numberToBytes(value, opts) {
20461
+ const hex3 = numberToHex(value, opts);
20462
+ return hexToBytes(hex3);
20463
+ }
20464
+ function stringToBytes(value, opts = {}) {
20465
+ const bytes = encoder5.encode(value);
20466
+ if (typeof opts.size === "number") {
20467
+ assertSize3(bytes, { size: opts.size });
20468
+ return pad3(bytes, { dir: "right", size: opts.size });
20469
+ }
20470
+ return bytes;
20471
+ }
20472
+ var encoder5, charCodeMap2;
20473
+ var init_toBytes = __esm({
20474
+ "node_modules/viem/_esm/utils/encoding/toBytes.js"() {
20475
+ "use strict";
20476
+ init_base();
20477
+ init_isHex();
20478
+ init_pad();
20479
+ init_fromHex();
20480
+ init_toHex();
20481
+ encoder5 = /* @__PURE__ */ new TextEncoder();
20482
+ charCodeMap2 = {
20483
+ zero: 48,
20484
+ nine: 57,
20485
+ A: 65,
20486
+ F: 70,
20487
+ a: 97,
20488
+ f: 102
20489
+ };
20490
+ }
20491
+ });
20492
+
20493
+ // node_modules/viem/_esm/utils/hash/keccak256.js
20494
+ function keccak2562(value, to_) {
20495
+ const to = to_ || "hex";
20496
+ const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes4(value) : value);
20497
+ if (to === "bytes")
20498
+ return bytes;
20499
+ return toHex3(bytes);
20500
+ }
20501
+ var init_keccak256 = __esm({
20502
+ "node_modules/viem/_esm/utils/hash/keccak256.js"() {
20503
+ "use strict";
20504
+ init_sha3();
20505
+ init_isHex();
20506
+ init_toBytes();
20507
+ init_toHex();
20508
+ }
20509
+ });
20510
+
20511
+ // node_modules/viem/_esm/errors/address.js
20512
+ var InvalidAddressError2;
20513
+ var init_address = __esm({
20514
+ "node_modules/viem/_esm/errors/address.js"() {
20515
+ "use strict";
20516
+ init_base();
20517
+ InvalidAddressError2 = class extends BaseError3 {
20518
+ constructor({ address: address3 }) {
20519
+ super(`Address "${address3}" is invalid.`, {
20520
+ metaMessages: [
20521
+ "- Address must be a hex value of 20 bytes (40 hex characters).",
20522
+ "- Address must match its checksum counterpart."
20523
+ ],
20524
+ name: "InvalidAddressError"
20525
+ });
20526
+ }
20527
+ };
20528
+ }
20529
+ });
20530
+
20531
+ // node_modules/viem/_esm/utils/lru.js
20532
+ var LruMap2;
20533
+ var init_lru2 = __esm({
20534
+ "node_modules/viem/_esm/utils/lru.js"() {
20535
+ "use strict";
20536
+ LruMap2 = class extends Map {
20537
+ constructor(size4) {
20538
+ super();
20539
+ Object.defineProperty(this, "maxSize", {
20540
+ enumerable: true,
20541
+ configurable: true,
20542
+ writable: true,
20543
+ value: void 0
20544
+ });
20545
+ this.maxSize = size4;
20546
+ }
20547
+ get(key) {
20548
+ const value = super.get(key);
20549
+ if (super.has(key)) {
20550
+ super.delete(key);
20551
+ super.set(key, value);
20552
+ }
20553
+ return value;
20554
+ }
20555
+ set(key, value) {
20556
+ if (super.has(key))
20557
+ super.delete(key);
20558
+ super.set(key, value);
20559
+ if (this.maxSize && this.size > this.maxSize) {
20560
+ const firstKey = super.keys().next().value;
20561
+ if (firstKey !== void 0)
20562
+ super.delete(firstKey);
20563
+ }
20564
+ return this;
20565
+ }
20566
+ };
20567
+ }
20568
+ });
20569
+
20570
+ // node_modules/viem/_esm/utils/address/getAddress.js
20571
+ function checksumAddress(address_, chainId) {
20572
+ if (checksumAddressCache.has(`${address_}.${chainId}`))
20573
+ return checksumAddressCache.get(`${address_}.${chainId}`);
20574
+ const hexAddress = chainId ? `${chainId}${address_.toLowerCase()}` : address_.substring(2).toLowerCase();
20575
+ const hash3 = keccak2562(stringToBytes(hexAddress), "bytes");
20576
+ const address3 = (chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress).split("");
20577
+ for (let i = 0; i < 40; i += 2) {
20578
+ if (hash3[i >> 1] >> 4 >= 8 && address3[i]) {
20579
+ address3[i] = address3[i].toUpperCase();
20580
+ }
20581
+ if ((hash3[i >> 1] & 15) >= 8 && address3[i + 1]) {
20582
+ address3[i + 1] = address3[i + 1].toUpperCase();
20583
+ }
20584
+ }
20585
+ const result = `0x${address3.join("")}`;
20586
+ checksumAddressCache.set(`${address_}.${chainId}`, result);
20587
+ return result;
20588
+ }
20589
+ function getAddress(address3, chainId) {
20590
+ if (!isAddress(address3, { strict: false }))
20591
+ throw new InvalidAddressError2({ address: address3 });
20592
+ return checksumAddress(address3, chainId);
20593
+ }
20594
+ var checksumAddressCache;
20595
+ var init_getAddress = __esm({
20596
+ "node_modules/viem/_esm/utils/address/getAddress.js"() {
20597
+ "use strict";
20598
+ init_address();
20599
+ init_toBytes();
20600
+ init_keccak256();
20601
+ init_lru2();
20602
+ init_isAddress();
20603
+ checksumAddressCache = /* @__PURE__ */ new LruMap2(8192);
20604
+ }
20605
+ });
20606
+
20607
+ // node_modules/viem/_esm/utils/address/isAddress.js
20608
+ function isAddress(address3, options) {
20609
+ const { strict = true } = options ?? {};
20610
+ const cacheKey2 = `${address3}.${strict}`;
20611
+ if (isAddressCache.has(cacheKey2))
20612
+ return isAddressCache.get(cacheKey2);
20613
+ const result = (() => {
20614
+ if (!addressRegex2.test(address3))
20615
+ return false;
20616
+ if (address3.toLowerCase() === address3)
20617
+ return true;
20618
+ if (strict)
20619
+ return checksumAddress(address3) === address3;
20620
+ return true;
20621
+ })();
20622
+ isAddressCache.set(cacheKey2, result);
20623
+ return result;
20624
+ }
20625
+ var addressRegex2, isAddressCache;
20626
+ var init_isAddress = __esm({
20627
+ "node_modules/viem/_esm/utils/address/isAddress.js"() {
20628
+ "use strict";
20629
+ init_lru2();
20630
+ init_getAddress();
20631
+ addressRegex2 = /^0x[a-fA-F0-9]{40}$/;
20632
+ isAddressCache = /* @__PURE__ */ new LruMap2(8192);
20633
+ }
20634
+ });
20635
+
20636
+ // node_modules/viem/_esm/errors/unit.js
20637
+ var InvalidDecimalNumberError;
20638
+ var init_unit = __esm({
20639
+ "node_modules/viem/_esm/errors/unit.js"() {
20640
+ "use strict";
20641
+ init_base();
20642
+ InvalidDecimalNumberError = class extends BaseError3 {
20643
+ constructor({ value }) {
20644
+ super(`Number \`${value}\` is not a valid decimal number.`, {
20645
+ name: "InvalidDecimalNumberError"
20646
+ });
20647
+ }
20648
+ };
20649
+ }
20650
+ });
20651
+
20652
+ // node_modules/viem/_esm/utils/unit/parseUnits.js
20653
+ function parseUnits(value, decimals) {
20654
+ if (!/^(-?)([0-9]*)\.?([0-9]*)$/.test(value))
20655
+ throw new InvalidDecimalNumberError({ value });
20656
+ let [integer2, fraction = "0"] = value.split(".");
20657
+ const negative = integer2.startsWith("-");
20658
+ if (negative)
20659
+ integer2 = integer2.slice(1);
20660
+ fraction = fraction.replace(/(0+)$/, "");
20661
+ if (decimals === 0) {
20662
+ if (Math.round(Number(`.${fraction}`)) === 1)
20663
+ integer2 = `${BigInt(integer2) + 1n}`;
20664
+ fraction = "";
20665
+ } else if (fraction.length > decimals) {
20666
+ const [left, unit, right] = [
20667
+ fraction.slice(0, decimals - 1),
20668
+ fraction.slice(decimals - 1, decimals),
20669
+ fraction.slice(decimals)
20670
+ ];
20671
+ const rounded = Math.round(Number(`${unit}.${right}`));
20672
+ if (rounded > 9)
20673
+ fraction = `${BigInt(left) + BigInt(1)}0`.padStart(left.length + 1, "0");
20674
+ else
20675
+ fraction = `${left}${rounded}`;
20676
+ if (fraction.length > decimals) {
20677
+ fraction = fraction.slice(1);
20678
+ integer2 = `${BigInt(integer2) + 1n}`;
20679
+ }
20680
+ fraction = fraction.slice(0, decimals);
20681
+ } else {
20682
+ fraction = fraction.padEnd(decimals, "0");
20683
+ }
20684
+ return BigInt(`${negative ? "-" : ""}${integer2}${fraction}`);
20685
+ }
20686
+ var init_parseUnits = __esm({
20687
+ "node_modules/viem/_esm/utils/unit/parseUnits.js"() {
20688
+ "use strict";
20689
+ init_unit();
20690
+ }
20691
+ });
20692
+
20693
+ // node_modules/viem/_esm/index.js
20694
+ var init_esm3 = __esm({
20695
+ "node_modules/viem/_esm/index.js"() {
20696
+ "use strict";
20697
+ init_getAddress();
20698
+ init_parseUnits();
20699
+ }
20700
+ });
20701
+
20702
+ // node_modules/mppx/dist/x402/Assets.js
20703
+ var Assets_exports = {};
20704
+ __export(Assets_exports, {
20705
+ base: () => base,
20706
+ baseSepolia: () => baseSepolia,
20707
+ define: () => define,
20708
+ fromToken: () => fromToken,
20709
+ isAsset: () => isAsset,
20710
+ isRawAddress: () => isRawAddress,
20711
+ isToken: () => isToken,
20712
+ matches: () => matches,
20713
+ resolve: () => resolve,
20714
+ toChainId: () => toChainId,
20715
+ toNetwork: () => toNetwork
20716
+ });
20717
+ function define(parameters) {
20718
+ return {
20719
+ [knownAsset]: true,
20720
+ address: parameters.address,
20721
+ decimals: parameters.decimals,
20722
+ network: parameters.network,
20723
+ transfer: parameters.transfer
20724
+ };
20725
+ }
20726
+ function fromToken(token, parameters) {
20727
+ const resolved = token(parameters.chainId);
20728
+ return define({
20729
+ address: resolved.address,
20730
+ decimals: resolved.decimals,
20731
+ network: toNetwork(parameters.chainId),
20732
+ transfer: withTokenDefaults(parameters.transfer, resolved)
20733
+ });
20734
+ }
20735
+ function isAsset(value) {
20736
+ if (typeof value !== "object" || value === null)
20737
+ return false;
20738
+ return value[knownAsset] === true;
20739
+ }
20740
+ function isToken(value) {
20741
+ return typeof value === "function" && typeof value.addresses === "object" && typeof value.decimals === "number";
20742
+ }
20743
+ function isRawAddress(currency) {
20744
+ return typeof currency === "string";
20745
+ }
20746
+ function resolve(currency, network) {
20747
+ if (isAsset(currency)) {
20748
+ if (currency.network !== network)
20749
+ return void 0;
20750
+ return {
20751
+ address: currency.address,
20752
+ decimals: currency.decimals,
20753
+ transfer: currency.transfer
20754
+ };
20755
+ }
20756
+ if (isToken(currency)) {
20757
+ const address3 = currency.addresses[toChainId(network)];
20758
+ if (!address3)
20759
+ return void 0;
20760
+ return {
20761
+ address: address3,
20762
+ decimals: currency.decimals,
20763
+ name: currency.name
20764
+ };
20765
+ }
20766
+ return {
20767
+ address: currency
20768
+ };
20769
+ }
20770
+ function matches(currency, acceptedCurrency, network) {
20771
+ const resolved = resolve(currency, network);
20772
+ if (!resolved)
20773
+ return false;
20774
+ return getAddress(resolved.address) === getAddress(acceptedCurrency);
20775
+ }
20776
+ function toNetwork(chainId) {
20777
+ return `eip155:${chainId}`;
20778
+ }
20779
+ function toChainId(network) {
20780
+ return Number(network.slice("eip155:".length));
20781
+ }
20782
+ function withTokenDefaults(transfer, token) {
20783
+ if (transfer.type !== "eip3009")
20784
+ return transfer;
20785
+ if (transfer.name)
20786
+ return { ...transfer, name: transfer.name };
20787
+ if (!token.name)
20788
+ throw new Error("EIP-3009 token assets require a token name.");
20789
+ return {
20790
+ ...transfer,
20791
+ name: token.name
20792
+ };
20793
+ }
20794
+ var knownAsset, base, baseSepolia;
20795
+ var init_Assets = __esm({
20796
+ "node_modules/mppx/dist/x402/Assets.js"() {
20797
+ "use strict";
20798
+ init_esm3();
20799
+ knownAsset = /* @__PURE__ */ Symbol("mppx.x402.asset");
20800
+ base = {
20801
+ USDC: define({
20802
+ address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
20803
+ decimals: 6,
20804
+ network: "eip155:8453",
20805
+ transfer: {
20806
+ // USDC's EIP-712 domain name differs between Base and Base Sepolia.
20807
+ name: "USD Coin",
20808
+ type: "eip3009",
20809
+ version: "2"
20810
+ }
20811
+ })
20812
+ };
20813
+ baseSepolia = {
20814
+ USDC: define({
20815
+ address: "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
20816
+ decimals: 6,
20817
+ network: "eip155:84532",
20818
+ transfer: {
20819
+ // Base Sepolia test USDC signs with the shorter EIP-712 domain name.
20820
+ name: "USDC",
20821
+ type: "eip3009",
20822
+ version: "2"
20823
+ }
20824
+ })
20825
+ };
20826
+ }
20827
+ });
20828
+
20829
+ // node_modules/mppx/dist/evm/Assets.js
20830
+ var Assets_exports2 = {};
20831
+ __export(Assets_exports2, {
20832
+ base: () => base,
20833
+ baseSepolia: () => baseSepolia,
20834
+ define: () => define,
20835
+ fromToken: () => fromToken,
20836
+ isAsset: () => isAsset,
20837
+ isRawAddress: () => isRawAddress,
20838
+ isToken: () => isToken,
20839
+ matches: () => matches,
20840
+ resolve: () => resolve,
20841
+ toChainId: () => toChainId,
20842
+ toNetwork: () => toNetwork
20843
+ });
20844
+ var init_Assets2 = __esm({
20845
+ "node_modules/mppx/dist/evm/Assets.js"() {
20846
+ "use strict";
20847
+ init_Assets();
20848
+ }
20849
+ });
20850
+
20851
+ // node_modules/mppx/dist/evm/Chains.js
20852
+ var Chains_exports = {};
20853
+ __export(Chains_exports, {
20854
+ base: () => base2,
20855
+ baseSepolia: () => baseSepolia2
20856
+ });
20857
+ var base2, baseSepolia2;
20858
+ var init_Chains = __esm({
20859
+ "node_modules/mppx/dist/evm/Chains.js"() {
20860
+ "use strict";
20861
+ base2 = 8453;
20862
+ baseSepolia2 = 84532;
20863
+ }
20864
+ });
20865
+
20866
+ // node_modules/mppx/dist/Method.js
20867
+ var Method_exports = {};
20868
+ __export(Method_exports, {
20869
+ from: () => from6,
20870
+ toClient: () => toClient,
20871
+ toServer: () => toServer
20872
+ });
20873
+ function from6(method) {
20874
+ return method;
20875
+ }
20876
+ function toClient(method, options) {
20877
+ const { canHandleChallenge, context, createCredential } = options;
20878
+ return {
20879
+ ...method,
20880
+ canHandleChallenge,
20881
+ context,
20882
+ createCredential
20883
+ };
20884
+ }
20885
+ function toServer(method, options) {
20886
+ const { alias, authorize, defaults, extensions, html, preflight, request, respond, stableBinding, transport, verify: verify3 } = options;
20887
+ return {
20888
+ ...method,
20889
+ alias,
20890
+ authorize,
20891
+ defaults,
20892
+ extensions,
20893
+ html,
20894
+ preflight,
20895
+ request,
20896
+ respond,
20897
+ stableBinding,
20898
+ transport,
20899
+ verify: verify3
20900
+ };
20901
+ }
20902
+ var init_Method = __esm({
20903
+ "node_modules/mppx/dist/Method.js"() {
20904
+ "use strict";
20905
+ }
20906
+ });
20907
+
20908
+ // node_modules/mppx/dist/evm/Types.js
20909
+ var Types_exports = {};
20910
+ __export(Types_exports, {
20911
+ AuthorizationConfigSchema: () => AuthorizationConfigSchema,
20912
+ AuthorizationPayloadSchema: () => AuthorizationPayloadSchema,
20913
+ ChargePayloadSchema: () => ChargePayloadSchema,
20914
+ ChargeRequestInputSchema: () => ChargeRequestInputSchema,
20915
+ ChargeRequestSchema: () => ChargeRequestSchema,
20916
+ MethodDetailsSchema: () => MethodDetailsSchema,
20917
+ authorizationDomain: () => authorizationDomain,
20918
+ authorizationTypes: () => authorizationTypes,
20919
+ challengeHash: () => challengeHash,
20920
+ chargeIntent: () => chargeIntent,
20921
+ credentialTypes: () => credentialTypes,
20922
+ eip3009: () => eip3009,
20923
+ evmNetworkPrefix: () => evmNetworkPrefix,
20924
+ networkOf: () => networkOf,
20925
+ paymentMethod: () => paymentMethod,
20926
+ toSource: () => toSource
20927
+ });
20928
+ function authorizationDomain(parameters) {
20929
+ return {
20930
+ chainId: parameters.chainId,
20931
+ name: parameters.authorization.name,
20932
+ verifyingContract: parameters.currency,
20933
+ version: parameters.authorization.version
20934
+ };
20935
+ }
20936
+ function challengeHash(challenge) {
20937
+ return Hash_exports.keccak256(Bytes_exports.fromString(`${challenge.id}${challenge.realm}`), {
20938
+ as: "Hex"
20939
+ });
20940
+ }
20941
+ function networkOf(chainId) {
20942
+ return `${evmNetworkPrefix}${chainId}`;
20943
+ }
20944
+ function toSource(parameters) {
20945
+ return `did:pkh:eip155:${parameters.chainId}:${parameters.address}`;
20946
+ }
20947
+ var paymentMethod, chargeIntent, evmNetworkPrefix, eip3009, credentialTypes, atomicAmount, AuthorizationConfigSchema, MethodDetailsSchema, ChargeRequestSchema, ChargeRequestInputSchema, AuthorizationPayloadSchema, ChargePayloadSchema, authorizationTypes;
20948
+ var init_Types = __esm({
20949
+ "node_modules/mppx/dist/evm/Types.js"() {
20950
+ "use strict";
20951
+ init_esm2();
20952
+ init_zod();
20953
+ paymentMethod = "evm";
20954
+ chargeIntent = "charge";
20955
+ evmNetworkPrefix = "eip155:";
20956
+ eip3009 = "eip3009";
20957
+ credentialTypes = ["authorization"];
20958
+ atomicAmount = string2().check(_regex(/^\d+$/, "Invalid atomic amount"));
20959
+ AuthorizationConfigSchema = object({
20960
+ name: string2().check(_minLength(1)),
20961
+ version: string2().check(_minLength(1))
20962
+ });
20963
+ MethodDetailsSchema = object({
20964
+ chainId: number2(),
20965
+ credentialTypes: optional(array(_enum2(credentialTypes)).check(_minLength(1))),
20966
+ decimals: optional(number2()),
20967
+ permit2Address: optional(address()),
20968
+ splits: optional(array(object({
20969
+ amount: atomicAmount,
20970
+ recipient: address()
20971
+ })))
20972
+ });
20973
+ ChargeRequestSchema = object({
20974
+ amount: atomicAmount,
20975
+ currency: address(),
20976
+ description: optional(string2()),
20977
+ externalId: optional(string2()),
20978
+ methodDetails: MethodDetailsSchema,
20979
+ recipient: address()
20980
+ });
20981
+ ChargeRequestInputSchema = object({
20982
+ amount: amount(),
20983
+ chainId: number2(),
20984
+ currency: address(),
20985
+ credentialTypes: optional(array(_enum2(credentialTypes)).check(_minLength(1))),
20986
+ decimals: number2(),
20987
+ description: optional(string2()),
20988
+ externalId: optional(string2()),
20989
+ permit2Address: optional(address()),
20990
+ recipient: address(),
20991
+ splits: optional(array(object({
20992
+ amount: atomicAmount,
20993
+ recipient: address()
20994
+ })))
20995
+ });
20996
+ AuthorizationPayloadSchema = object({
20997
+ from: address(),
20998
+ nonce: hash2(),
20999
+ signature: signature(),
21000
+ to: address(),
21001
+ type: literal("authorization"),
21002
+ validAfter: atomicAmount,
21003
+ validBefore: atomicAmount,
21004
+ value: atomicAmount
21005
+ });
21006
+ ChargePayloadSchema = AuthorizationPayloadSchema;
21007
+ authorizationTypes = {
21008
+ TransferWithAuthorization: [
21009
+ { name: "from", type: "address" },
21010
+ { name: "to", type: "address" },
21011
+ { name: "value", type: "uint256" },
21012
+ { name: "validAfter", type: "uint256" },
21013
+ { name: "validBefore", type: "uint256" },
21014
+ { name: "nonce", type: "bytes32" }
21015
+ ]
21016
+ };
21017
+ }
21018
+ });
21019
+
21020
+ // node_modules/mppx/dist/evm/Methods.js
21021
+ var Methods_exports = {};
21022
+ __export(Methods_exports, {
21023
+ charge: () => charge
21024
+ });
21025
+ var charge;
21026
+ var init_Methods = __esm({
21027
+ "node_modules/mppx/dist/evm/Methods.js"() {
21028
+ "use strict";
21029
+ init_esm3();
21030
+ init_Method();
21031
+ init_zod();
21032
+ init_Types();
21033
+ charge = from6({
21034
+ name: paymentMethod,
21035
+ intent: chargeIntent,
21036
+ schema: {
21037
+ credential: {
21038
+ payload: ChargePayloadSchema
21039
+ },
21040
+ request: pipe(ChargeRequestInputSchema, transform(({ amount: amount2, chainId, credentialTypes: credentialTypes2 = ["authorization"], currency, decimals, permit2Address, recipient, splits, ...request }) => ({
21041
+ ...request,
21042
+ amount: parseUnits(amount2, decimals).toString(),
21043
+ currency: getAddress(currency),
21044
+ methodDetails: {
21045
+ chainId,
21046
+ credentialTypes: credentialTypes2,
21047
+ decimals,
21048
+ ...permit2Address ? { permit2Address: getAddress(permit2Address) } : {},
21049
+ ...splits ? { splits } : {}
21050
+ },
21051
+ recipient: getAddress(recipient)
21052
+ })))
21053
+ }
21054
+ });
21055
+ }
21056
+ });
21057
+
21058
+ // node_modules/mppx/dist/evm/index.js
21059
+ var evm_exports = {};
21060
+ __export(evm_exports, {
21061
+ Assets: () => Assets_exports2,
21062
+ AuthorizationConfigSchema: () => AuthorizationConfigSchema,
21063
+ AuthorizationPayloadSchema: () => AuthorizationPayloadSchema,
21064
+ Chains: () => Chains_exports,
21065
+ ChargePayloadSchema: () => ChargePayloadSchema,
21066
+ ChargeRequestInputSchema: () => ChargeRequestInputSchema,
21067
+ ChargeRequestSchema: () => ChargeRequestSchema,
21068
+ MethodDetailsSchema: () => MethodDetailsSchema,
21069
+ Methods: () => Methods_exports,
21070
+ Types: () => Types_exports,
21071
+ assets: () => Assets_exports2,
21072
+ authorizationDomain: () => authorizationDomain,
21073
+ authorizationTypes: () => authorizationTypes,
21074
+ chains: () => Chains_exports,
21075
+ challengeHash: () => challengeHash,
21076
+ charge: () => charge,
21077
+ chargeIntent: () => chargeIntent,
21078
+ credentialTypes: () => credentialTypes,
21079
+ eip3009: () => eip3009,
21080
+ evmNetworkPrefix: () => evmNetworkPrefix,
21081
+ networkOf: () => networkOf,
21082
+ paymentMethod: () => paymentMethod,
21083
+ toSource: () => toSource
21084
+ });
21085
+ var init_evm = __esm({
21086
+ "node_modules/mppx/dist/evm/index.js"() {
21087
+ "use strict";
21088
+ init_Assets2();
21089
+ init_Chains();
21090
+ init_Methods();
21091
+ init_Types();
21092
+ init_Assets2();
21093
+ init_Chains();
21094
+ init_Methods();
21095
+ init_Types();
21096
+ }
21097
+ });
21098
+
21099
+ // node_modules/mppx/dist/Mcp.js
21100
+ var Mcp_exports = {};
21101
+ __export(Mcp_exports, {
21102
+ credentialMetaKey: () => credentialMetaKey,
21103
+ paymentRequiredCode: () => paymentRequiredCode,
21104
+ paymentRequiredMetaKey: () => paymentRequiredMetaKey,
21105
+ paymentVerificationFailedCode: () => paymentVerificationFailedCode,
21106
+ receiptMetaKey: () => receiptMetaKey
21107
+ });
21108
+ var paymentRequiredCode, paymentVerificationFailedCode, credentialMetaKey, paymentRequiredMetaKey, receiptMetaKey;
21109
+ var init_Mcp = __esm({
21110
+ "node_modules/mppx/dist/Mcp.js"() {
21111
+ "use strict";
21112
+ paymentRequiredCode = -32042;
21113
+ paymentVerificationFailedCode = -32043;
21114
+ credentialMetaKey = "org.paymentauth/credential";
21115
+ paymentRequiredMetaKey = "org.paymentauth/payment-required";
21116
+ receiptMetaKey = "org.paymentauth/receipt";
21117
+ }
21118
+ });
21119
+
21120
+ // node_modules/mppx/dist/Receipt.js
21121
+ var Receipt_exports = {};
21122
+ __export(Receipt_exports, {
21123
+ Schema: () => Schema2,
21124
+ deserialize: () => deserialize4,
21125
+ from: () => from7,
21126
+ fromResponse: () => fromResponse2,
21127
+ serialize: () => serialize4
21128
+ });
21129
+ function deserialize4(encoded) {
21130
+ const json2 = Base64_exports.toString(encoded);
21131
+ return from7(JSON.parse(json2));
21132
+ }
21133
+ function from7(parameters) {
21134
+ return Schema2.parse(parameters);
21135
+ }
21136
+ function serialize4(receipt) {
21137
+ const json2 = JSON.stringify(receipt);
21138
+ return Base64_exports.fromString(json2, { pad: false, url: true });
21139
+ }
21140
+ function fromResponse2(response) {
21141
+ const header = response.headers.get(Headers2.paymentReceipt);
21142
+ if (!header)
21143
+ throw new Error(`Missing ${Headers2.paymentReceipt} header.`);
21144
+ return deserialize4(header);
21145
+ }
21146
+ var Schema2;
21147
+ var init_Receipt = __esm({
21148
+ "node_modules/mppx/dist/Receipt.js"() {
21149
+ "use strict";
21150
+ init_esm2();
21151
+ init_Constants();
21152
+ init_zod();
21153
+ Schema2 = object({
21154
+ /** Payment method used (e.g., "tempo", "stripe"). */
21155
+ method: string2(),
21156
+ /** Method-specific reference (e.g., transaction hash). */
21157
+ reference: string2(),
21158
+ /** Optional external reference ID echoed from the credential payload. */
21159
+ externalId: optional(string2()),
21160
+ /** Optional server-issued subscription identifier for recurring payments. */
21161
+ subscriptionId: optional(string2()),
21162
+ /** Payment status. Always "success" — failures use 402 + Problem Details. */
21163
+ status: literal("success"),
21164
+ /** RFC 3339 settlement timestamp. */
21165
+ timestamp: datetime3()
21166
+ });
21167
+ }
21168
+ });
21169
+
21170
+ // node_modules/mppx/dist/Store.js
21171
+ var Store_exports = {};
21172
+ __export(Store_exports, {
21173
+ cloudflare: () => cloudflare,
21174
+ from: () => from8,
21175
+ memory: () => memory,
21176
+ redis: () => redis,
21177
+ upstash: () => upstash
21178
+ });
21179
+ function from8(store, options) {
21180
+ return withKeyPrefix(store, options?.keyPrefix);
21181
+ }
21182
+ function withKeyPrefix(store, keyPrefix = "") {
21183
+ if (!keyPrefix)
21184
+ return store;
21185
+ const cached2 = keyPrefixCache.get(store)?.get(keyPrefix);
21186
+ if (cached2)
21187
+ return cached2;
21188
+ const backing = store;
21189
+ const prefixedKey = (key) => `${keyPrefix}${key}`;
21190
+ const prefixed = from8({
21191
+ async get(key) {
21192
+ return backing.get(prefixedKey(key));
21193
+ },
21194
+ async put(key, value) {
21195
+ await backing.put(prefixedKey(key), value);
21196
+ },
21197
+ async delete(key) {
21198
+ await backing.delete(prefixedKey(key));
21199
+ },
21200
+ ..."update" in store ? {
21201
+ async update(key, fn) {
21202
+ return store.update(prefixedKey(key), fn);
21203
+ }
21204
+ } : {}
21205
+ });
21206
+ const cachedByPrefix = keyPrefixCache.get(store) ?? /* @__PURE__ */ new Map();
21207
+ cachedByPrefix.set(keyPrefix, prefixed);
21208
+ keyPrefixCache.set(store, cachedByPrefix);
21209
+ return prefixed;
21210
+ }
21211
+ function wrapJsonUpdate(update) {
21212
+ if (!update)
21213
+ return {};
21214
+ return {
21215
+ async update(key, fn) {
21216
+ return update(key, (current) => {
21217
+ const parsed = current == null ? null : Json_exports.parse(current);
21218
+ const change = fn(parsed);
21219
+ if (change.op !== "set")
21220
+ return change;
21221
+ return { ...change, value: Json_exports.stringify(change.value) };
21222
+ });
21223
+ }
21224
+ };
21225
+ }
21226
+ function cloudflare(kv, options) {
21227
+ return from8({
21228
+ async get(key) {
21229
+ const raw = await kv.get(key);
21230
+ if (raw == null)
21231
+ return null;
21232
+ return Json_exports.parse(raw);
20167
21233
  },
20168
21234
  async put(key, value) {
20169
21235
  await kv.put(key, Json_exports.stringify(value));
@@ -20172,9 +21238,9 @@ function cloudflare(kv) {
20172
21238
  await kv.delete(key);
20173
21239
  },
20174
21240
  ...wrapJsonUpdate(kv.update)
20175
- });
21241
+ }, options);
20176
21242
  }
20177
- function memory() {
21243
+ function memory(options) {
20178
21244
  const store = /* @__PURE__ */ new Map();
20179
21245
  return from8({
20180
21246
  async get(key) {
@@ -20198,9 +21264,9 @@ function memory() {
20198
21264
  store.delete(key);
20199
21265
  return change.result;
20200
21266
  }
20201
- });
21267
+ }, options);
20202
21268
  }
20203
- function redis(client) {
21269
+ function redis(client, options) {
20204
21270
  return from8({
20205
21271
  async get(key) {
20206
21272
  const raw = await client.get(key);
@@ -20215,9 +21281,9 @@ function redis(client) {
20215
21281
  await client.del(key);
20216
21282
  },
20217
21283
  ...wrapJsonUpdate(client.update)
20218
- });
21284
+ }, options);
20219
21285
  }
20220
- function upstash(redis2) {
21286
+ function upstash(redis2, options) {
20221
21287
  return from8({
20222
21288
  async get(key) {
20223
21289
  return await redis2.get(key);
@@ -20231,12 +21297,288 @@ function upstash(redis2) {
20231
21297
  ...redis2.update ? {
20232
21298
  update: redis2.update
20233
21299
  } : {}
20234
- });
21300
+ }, options);
20235
21301
  }
21302
+ var keyPrefixCache;
20236
21303
  var init_Store = __esm({
20237
21304
  "node_modules/mppx/dist/Store.js"() {
20238
21305
  "use strict";
20239
21306
  init_esm2();
21307
+ keyPrefixCache = /* @__PURE__ */ new WeakMap();
21308
+ }
21309
+ });
21310
+
21311
+ // node_modules/mppx/dist/internal/HeaderCodec.js
21312
+ function createJson(schema) {
21313
+ return {
21314
+ encode(value) {
21315
+ return Base64_exports.fromString(JSON.stringify(schema.parse(value)));
21316
+ },
21317
+ decode(value) {
21318
+ try {
21319
+ return schema.parse(JSON.parse(Base64_exports.toString(value)));
21320
+ } catch {
21321
+ throw new InvalidJsonHeaderError();
21322
+ }
21323
+ }
21324
+ };
21325
+ }
21326
+ var InvalidJsonHeaderError;
21327
+ var init_HeaderCodec = __esm({
21328
+ "node_modules/mppx/dist/internal/HeaderCodec.js"() {
21329
+ "use strict";
21330
+ init_esm2();
21331
+ InvalidJsonHeaderError = class extends Error {
21332
+ name = "InvalidJsonHeaderError";
21333
+ constructor() {
21334
+ super("Invalid base64 JSON header.");
21335
+ }
21336
+ };
21337
+ }
21338
+ });
21339
+
21340
+ // node_modules/mppx/dist/x402/Types.js
21341
+ var Types_exports2 = {};
21342
+ __export(Types_exports2, {
21343
+ ExactEip3009PayloadSchema: () => ExactEip3009PayloadSchema,
21344
+ ExactPayloadSchema: () => ExactPayloadSchema,
21345
+ ExactPermit2PayloadSchema: () => ExactPermit2PayloadSchema,
21346
+ ExactTransferSchema: () => ExactTransferSchema,
21347
+ ExtensionSchema: () => ExtensionSchema,
21348
+ ExtensionsSchema: () => ExtensionsSchema,
21349
+ PaymentPayloadSchema: () => PaymentPayloadSchema,
21350
+ PaymentRequiredSchema: () => PaymentRequiredSchema,
21351
+ PaymentRequirementsSchema: () => PaymentRequirementsSchema,
21352
+ ResourceInfoSchema: () => ResourceInfoSchema,
21353
+ SettleResponseSchema: () => SettleResponseSchema,
21354
+ VerifyResponseSchema: () => VerifyResponseSchema,
21355
+ assetTransferMethods: () => assetTransferMethods,
21356
+ evmNetworkPrefix: () => evmNetworkPrefix2,
21357
+ exactIntent: () => exactIntent,
21358
+ paymentMethod: () => paymentMethod2,
21359
+ paymentRequiredHeader: () => paymentRequiredHeader,
21360
+ paymentResponseHeader: () => paymentResponseHeader,
21361
+ paymentSignatureHeader: () => paymentSignatureHeader,
21362
+ schemes: () => schemes,
21363
+ syntheticChallengeIdPrefix: () => syntheticChallengeIdPrefix,
21364
+ toPaymentRequirements: () => toPaymentRequirements,
21365
+ versions: () => versions
21366
+ });
21367
+ function toPaymentRequirements(request) {
21368
+ const { extensions: _extensions, resource: _resource, ...paymentRequirements } = request;
21369
+ return PaymentRequirementsSchema.parse(paymentRequirements);
21370
+ }
21371
+ var versions, paymentMethod2, exactIntent, schemes, assetTransferMethods, evmNetworkPrefix2, syntheticChallengeIdPrefix, paymentRequiredHeader, paymentSignatureHeader, paymentResponseHeader, nonEmptyString, positiveNumber, atomicAmount2, address2, evmNetwork, ResourceInfoSchema, ExactTransferSchema, PaymentRequirementsSchema, ExtensionSchema, ExtensionsSchema, PaymentRequiredSchema, ExactEip3009PayloadSchema, ExactPermit2PayloadSchema, ExactPayloadSchema, PaymentPayloadSchema, VerifyResponseSchema, SettleResponseSchema;
21372
+ var init_Types2 = __esm({
21373
+ "node_modules/mppx/dist/x402/Types.js"() {
21374
+ "use strict";
21375
+ init_zod();
21376
+ versions = [2];
21377
+ paymentMethod2 = "evm";
21378
+ exactIntent = "charge";
21379
+ schemes = ["exact"];
21380
+ assetTransferMethods = ["eip3009", "permit2"];
21381
+ evmNetworkPrefix2 = "eip155:";
21382
+ syntheticChallengeIdPrefix = "x402:";
21383
+ paymentRequiredHeader = "PAYMENT-REQUIRED";
21384
+ paymentSignatureHeader = "PAYMENT-SIGNATURE";
21385
+ paymentResponseHeader = "PAYMENT-RESPONSE";
21386
+ nonEmptyString = string2().check(_minLength(1));
21387
+ positiveNumber = number2().check(refine((value) => value > 0, "Must be positive"));
21388
+ atomicAmount2 = string2().check(_regex(/^\d+$/, "Invalid atomic amount"));
21389
+ address2 = address();
21390
+ evmNetwork = string2().check(_regex(new RegExp(`^${evmNetworkPrefix2}\\d+$`), "Invalid EVM CAIP-2 network"));
21391
+ ResourceInfoSchema = object({
21392
+ description: optional(string2()),
21393
+ iconUrl: optional(string2()),
21394
+ mimeType: optional(string2()),
21395
+ serviceName: optional(string2()),
21396
+ tags: optional(array(string2())),
21397
+ url: nonEmptyString
21398
+ });
21399
+ ExactTransferSchema = discriminatedUnion("type", [
21400
+ object({
21401
+ name: nonEmptyString,
21402
+ type: literal("eip3009"),
21403
+ version: nonEmptyString
21404
+ }),
21405
+ object({
21406
+ name: optional(string2()),
21407
+ type: literal("permit2"),
21408
+ version: optional(string2())
21409
+ })
21410
+ ]);
21411
+ PaymentRequirementsSchema = object({
21412
+ amount: atomicAmount2,
21413
+ asset: nonEmptyString,
21414
+ extra: optional(record(string2(), unknown())),
21415
+ maxTimeoutSeconds: positiveNumber,
21416
+ network: evmNetwork,
21417
+ payTo: nonEmptyString,
21418
+ scheme: _enum2(schemes)
21419
+ });
21420
+ ExtensionSchema = object({
21421
+ info: record(string2(), unknown()),
21422
+ schema: record(string2(), unknown())
21423
+ });
21424
+ ExtensionsSchema = record(string2(), ExtensionSchema);
21425
+ PaymentRequiredSchema = object({
21426
+ accepts: array(PaymentRequirementsSchema).check(_minLength(1)),
21427
+ error: optional(string2()),
21428
+ extensions: optional(ExtensionsSchema),
21429
+ resource: ResourceInfoSchema,
21430
+ x402Version: literal(2)
21431
+ });
21432
+ ExactEip3009PayloadSchema = object({
21433
+ authorization: object({
21434
+ from: address2,
21435
+ nonce: hash2(),
21436
+ to: address2,
21437
+ validAfter: atomicAmount2,
21438
+ validBefore: atomicAmount2,
21439
+ value: atomicAmount2
21440
+ }),
21441
+ signature: signature()
21442
+ });
21443
+ ExactPermit2PayloadSchema = object({
21444
+ permit2Authorization: object({
21445
+ deadline: atomicAmount2,
21446
+ from: address2,
21447
+ nonce: atomicAmount2,
21448
+ permitted: object({
21449
+ amount: atomicAmount2,
21450
+ token: address2
21451
+ }),
21452
+ spender: address2,
21453
+ witness: object({
21454
+ to: address2,
21455
+ validAfter: atomicAmount2
21456
+ })
21457
+ }),
21458
+ signature: signature()
21459
+ });
21460
+ ExactPayloadSchema = union([ExactEip3009PayloadSchema, ExactPermit2PayloadSchema]);
21461
+ PaymentPayloadSchema = object({
21462
+ accepted: PaymentRequirementsSchema,
21463
+ extensions: optional(ExtensionsSchema),
21464
+ payload: ExactPayloadSchema,
21465
+ resource: optional(ResourceInfoSchema),
21466
+ x402Version: literal(2)
21467
+ });
21468
+ VerifyResponseSchema = object({
21469
+ extensions: optional(ExtensionsSchema),
21470
+ extra: optional(record(string2(), unknown())),
21471
+ invalidMessage: optional(string2()),
21472
+ invalidReason: optional(string2()),
21473
+ isValid: boolean2(),
21474
+ payer: optional(string2())
21475
+ });
21476
+ SettleResponseSchema = object({
21477
+ amount: optional(atomicAmount2),
21478
+ errorMessage: optional(string2()),
21479
+ errorReason: optional(string2()),
21480
+ extensions: optional(ExtensionsSchema),
21481
+ extra: optional(record(string2(), unknown())),
21482
+ network: nonEmptyString,
21483
+ payer: optional(string2()),
21484
+ success: boolean2(),
21485
+ transaction: string2()
21486
+ });
21487
+ }
21488
+ });
21489
+
21490
+ // node_modules/mppx/dist/x402/Header.js
21491
+ var Header_exports = {};
21492
+ __export(Header_exports, {
21493
+ decodePaymentRequired: () => decodePaymentRequired,
21494
+ decodePaymentRequiredEnvelope: () => decodePaymentRequiredEnvelope,
21495
+ decodePaymentResponse: () => decodePaymentResponse,
21496
+ decodePaymentSignature: () => decodePaymentSignature,
21497
+ encodePaymentRequired: () => encodePaymentRequired,
21498
+ encodePaymentResponse: () => encodePaymentResponse,
21499
+ encodePaymentSignature: () => encodePaymentSignature
21500
+ });
21501
+ function decodePaymentRequiredEnvelope(value) {
21502
+ try {
21503
+ const parsed = JSON.parse(Base64_exports.toString(value));
21504
+ return parsePaymentRequiredEnvelope(parsed);
21505
+ } catch {
21506
+ throw new InvalidJsonHeaderError();
21507
+ }
21508
+ }
21509
+ var paymentRequired, paymentSignature, paymentResponse, encodePaymentRequired, decodePaymentRequired, encodePaymentSignature, decodePaymentSignature, encodePaymentResponse, decodePaymentResponse, parsePaymentRequiredEnvelope;
21510
+ var init_Header = __esm({
21511
+ "node_modules/mppx/dist/x402/Header.js"() {
21512
+ "use strict";
21513
+ init_esm2();
21514
+ init_HeaderCodec();
21515
+ init_Types2();
21516
+ paymentRequired = createJson(PaymentRequiredSchema);
21517
+ paymentSignature = createJson(PaymentPayloadSchema);
21518
+ paymentResponse = createJson(SettleResponseSchema);
21519
+ encodePaymentRequired = paymentRequired.encode;
21520
+ decodePaymentRequired = paymentRequired.decode;
21521
+ encodePaymentSignature = paymentSignature.encode;
21522
+ decodePaymentSignature = paymentSignature.decode;
21523
+ encodePaymentResponse = paymentResponse.encode;
21524
+ decodePaymentResponse = paymentResponse.decode;
21525
+ parsePaymentRequiredEnvelope = (value) => {
21526
+ if (!value || typeof value !== "object" || Array.isArray(value))
21527
+ throw new InvalidJsonHeaderError();
21528
+ const record2 = value;
21529
+ if (record2.x402Version !== 2 || !Array.isArray(record2.accepts))
21530
+ throw new InvalidJsonHeaderError();
21531
+ const resource = ResourceInfoSchema.parse(record2.resource);
21532
+ const extensions = record2.extensions === void 0 ? void 0 : ExtensionsSchema.parse(record2.extensions);
21533
+ return {
21534
+ accepts: record2.accepts,
21535
+ ...extensions ? { extensions } : {},
21536
+ resource,
21537
+ x402Version: 2
21538
+ };
21539
+ };
21540
+ }
21541
+ });
21542
+
21543
+ // node_modules/mppx/dist/x402/index.js
21544
+ var x402_exports = {};
21545
+ __export(x402_exports, {
21546
+ Assets: () => Assets_exports,
21547
+ ExactEip3009PayloadSchema: () => ExactEip3009PayloadSchema,
21548
+ ExactPayloadSchema: () => ExactPayloadSchema,
21549
+ ExactPermit2PayloadSchema: () => ExactPermit2PayloadSchema,
21550
+ ExactTransferSchema: () => ExactTransferSchema,
21551
+ ExtensionSchema: () => ExtensionSchema,
21552
+ ExtensionsSchema: () => ExtensionsSchema,
21553
+ Header: () => Header_exports,
21554
+ PaymentPayloadSchema: () => PaymentPayloadSchema,
21555
+ PaymentRequiredSchema: () => PaymentRequiredSchema,
21556
+ PaymentRequirementsSchema: () => PaymentRequirementsSchema,
21557
+ ResourceInfoSchema: () => ResourceInfoSchema,
21558
+ SettleResponseSchema: () => SettleResponseSchema,
21559
+ Types: () => Types_exports2,
21560
+ VerifyResponseSchema: () => VerifyResponseSchema,
21561
+ assetTransferMethods: () => assetTransferMethods,
21562
+ assets: () => Assets_exports,
21563
+ evmNetworkPrefix: () => evmNetworkPrefix2,
21564
+ exactIntent: () => exactIntent,
21565
+ paymentMethod: () => paymentMethod2,
21566
+ paymentRequiredHeader: () => paymentRequiredHeader,
21567
+ paymentResponseHeader: () => paymentResponseHeader,
21568
+ paymentSignatureHeader: () => paymentSignatureHeader,
21569
+ schemes: () => schemes,
21570
+ syntheticChallengeIdPrefix: () => syntheticChallengeIdPrefix,
21571
+ toPaymentRequirements: () => toPaymentRequirements,
21572
+ versions: () => versions
21573
+ });
21574
+ var init_x402 = __esm({
21575
+ "node_modules/mppx/dist/x402/index.js"() {
21576
+ "use strict";
21577
+ init_Assets();
21578
+ init_Header();
21579
+ init_Types2();
21580
+ init_Assets();
21581
+ init_Types2();
20240
21582
  }
20241
21583
  });
20242
21584
 
@@ -20245,6 +21587,7 @@ var dist_exports = {};
20245
21587
  __export(dist_exports, {
20246
21588
  BodyDigest: () => BodyDigest_exports,
20247
21589
  Challenge: () => Challenge_exports,
21590
+ Constants: () => Constants_exports,
20248
21591
  Credential: () => Credential_exports,
20249
21592
  Errors: () => Errors_exports2,
20250
21593
  Expires: () => Expires_exports,
@@ -20253,6 +21596,8 @@ __export(dist_exports, {
20253
21596
  PaymentRequest: () => PaymentRequest_exports,
20254
21597
  Receipt: () => Receipt_exports,
20255
21598
  Store: () => Store_exports,
21599
+ evm: () => evm_exports,
21600
+ x402: () => x402_exports,
20256
21601
  z: () => zod_exports
20257
21602
  });
20258
21603
  var init_dist2 = __esm({
@@ -20260,14 +21605,17 @@ var init_dist2 = __esm({
20260
21605
  "use strict";
20261
21606
  init_BodyDigest();
20262
21607
  init_Challenge();
21608
+ init_Constants();
20263
21609
  init_Credential();
20264
21610
  init_Errors2();
20265
21611
  init_Expires();
21612
+ init_evm();
20266
21613
  init_Mcp();
20267
21614
  init_Method();
20268
21615
  init_PaymentRequest();
20269
21616
  init_Receipt();
20270
21617
  init_Store();
21618
+ init_x402();
20271
21619
  init_zod();
20272
21620
  }
20273
21621
  });
@@ -20295,12 +21643,20 @@ var init_usdc = __esm({
20295
21643
  });
20296
21644
 
20297
21645
  // src/payment/wwwauthenticate.ts
20298
- function paymentRequiredHeader({
21646
+ function paymentRequiredHeader2({
20299
21647
  x402Version,
20300
21648
  accepts,
20301
- resource
21649
+ resource,
21650
+ extensions
20302
21651
  }) {
20303
- return Buffer.from(JSON.stringify({ x402Version, accepts, ...resource ? { resource } : {} })).toString("base64");
21652
+ return Buffer.from(
21653
+ JSON.stringify({
21654
+ x402Version,
21655
+ accepts,
21656
+ ...resource ? { resource } : {},
21657
+ ...extensions && Object.keys(extensions).length > 0 ? { extensions } : {}
21658
+ })
21659
+ ).toString("base64");
20304
21660
  }
20305
21661
  var init_wwwauthenticate = __esm({
20306
21662
  "src/payment/wwwauthenticate.ts"() {
@@ -20595,7 +21951,7 @@ function buildDiscoveryProbeResponse(opts) {
20595
21951
  if (opts.x402Sample) {
20596
21952
  const x402Version = opts.x402Sample.version ?? 2;
20597
21953
  const sampleAccepts = opts.x402Sample.accepts ?? (opts.x402Sample.networks ?? []).map((n) => sampleX402AcceptForNetwork(n, opts.x402Sample.amountAtomic ?? "1000000")).filter((e) => e !== null);
20598
- headers["payment-required"] = paymentRequiredHeader({
21954
+ headers["payment-required"] = paymentRequiredHeader2({
20599
21955
  x402Version,
20600
21956
  accepts: sampleAccepts,
20601
21957
  ...opts.x402Sample.resourceUrl ? { resource: { url: opts.x402Sample.resourceUrl, mimeType: "application/json" } } : {}
@@ -20860,6 +22216,7 @@ __export(index_exports, {
20860
22216
  AGENTSCORE_CANONICAL_ISSUER: () => AGENTSCORE_CANONICAL_ISSUER,
20861
22217
  AGENTSCORE_UCP_CAPABILITY: () => AGENTSCORE_UCP_CAPABILITY,
20862
22218
  AGENT_IDENTITY_HEADER: () => AGENT_IDENTITY_HEADER,
22219
+ AIP_A2A_EXTENSION_URI: () => AIP_A2A_EXTENSION_URI,
20863
22220
  AIP_COVERED_COMPONENTS: () => AIP_COVERED_COMPONENTS,
20864
22221
  AIP_SIGNATURE_TAG: () => AIP_SIGNATURE_TAG,
20865
22222
  Checkout: () => Checkout,
@@ -20868,15 +22225,18 @@ __export(index_exports, {
20868
22225
  HARD_MAX_CACHE_SECONDS: () => HARD_MAX_CACHE_SECONDS,
20869
22226
  JWKS_WELL_KNOWN_PATH: () => JWKS_WELL_KNOWN_PATH,
20870
22227
  JwksCache: () => JwksCache,
22228
+ MAX_POP_WINDOW_SECONDS: () => MAX_POP_WINDOW_SECONDS,
20871
22229
  UCPSigningKey: () => UCPSigningKey,
20872
22230
  UCPVerificationError: () => UCPVerificationError,
20873
22231
  UCP_A2A_EXTENSION_URI: () => UCP_A2A_EXTENSION_URI,
22232
+ aipA2AExtension: () => aipA2AExtension,
20874
22233
  aipErrorCode: () => aipErrorCode,
20875
22234
  aipErrorStatus: () => aipErrorStatus,
20876
22235
  buildA2AAgentCard: () => buildA2AAgentCard,
20877
22236
  buildAgentMemoryHint: () => buildAgentMemoryHint,
20878
22237
  buildAipErrorBody: () => buildAipErrorBody,
20879
22238
  buildAipTrustedIssuers: () => buildAipTrustedIssuers,
22239
+ buildAipWeakAuthBody: () => buildAipWeakAuthBody,
20880
22240
  buildContactSupportNextSteps: () => buildContactSupportNextSteps,
20881
22241
  buildDefaultCheckoutRails: () => buildDefaultCheckoutRails,
20882
22242
  buildGateFromPolicy: () => buildGateFromPolicy,
@@ -20887,12 +22247,15 @@ __export(index_exports, {
20887
22247
  buildVerificationRequiredBody: () => buildVerificationRequiredBody,
20888
22248
  buildVerifyContextFromRequest: () => buildVerifyContextFromRequest,
20889
22249
  canonicalizeIssuer: () => canonicalizeIssuer,
22250
+ checkTrustRequirements: () => checkTrustRequirements,
20890
22251
  computeFirstCheckout: () => computeFirstCheckout,
20891
22252
  createDefaultOnDenied: () => createDefaultOnDenied,
20892
22253
  createQuoteCache: () => createQuoteCache,
20893
22254
  defaultReadOnlyOnDenied: () => defaultReadOnlyOnDenied,
20894
22255
  denialReasonStatus: () => denialReasonStatus,
20895
22256
  denialReasonToBody: () => denialReasonToBody,
22257
+ evaluateAipParts: () => evaluateAipParts,
22258
+ evaluateAipRequest: () => evaluateAipRequest,
20896
22259
  extractOwnerScope: () => extractOwnerScope,
20897
22260
  extractPaymentSigner: () => extractPaymentSigner,
20898
22261
  extractPaymentSignerFromAuth: () => extractPaymentSignerFromAuth,
@@ -20913,6 +22276,7 @@ __export(index_exports, {
20913
22276
  loadUCPSigningKeyFromEnv: () => loadUCPSigningKeyFromEnv,
20914
22277
  makeMppxComposeHook: () => makeMppxComposeHook,
20915
22278
  mppPaymentHandler: () => mppPaymentHandler,
22279
+ normalizeAddress: () => normalizeAddress,
20916
22280
  pricingResult: () => pricingResult,
20917
22281
  readX402PaymentHeader: () => readX402PaymentHeader,
20918
22282
  runGateWithEnforcement: () => runGateWithEnforcement,
@@ -20964,7 +22328,7 @@ function buildSignerMismatchBody({
20964
22328
  learnMoreUrl
20965
22329
  }) {
20966
22330
  if (result.kind === "pass") return null;
20967
- const learnMoreUrlResolved = learnMoreUrl ?? "https://docs.agentscore.sh/guides/agent-identity";
22331
+ const learnMoreUrlResolved = learnMoreUrl ?? "https://docs.agentscore.com/guides/agent-identity";
20968
22332
  if (result.kind === "wallet_signer_mismatch") {
20969
22333
  const linkedWallets = result.linkedWallets ?? [];
20970
22334
  const userMessageResolved = userMessage ?? (linkedWallets.length > 0 ? `Sign the payment with one of the wallets linked to this operator: ${linkedWallets.join(", ")}. Then retry.` : "Sign the payment with the same wallet you claimed via X-Wallet-Address, or switch to X-Operator-Token for rail-independent identity.");
@@ -21014,7 +22378,7 @@ function verificationAgentInstructions({
21014
22378
  extra
21015
22379
  } = {}) {
21016
22380
  const baseSteps = [
21017
- "Present the verify_url directly to the user \u2014 it is a complete, ready-to-open URL with the session token already embedded (e.g. https://agentscore.sh/verify?session=sess_...). Do NOT modify or construct the URL yourself.",
22381
+ "Present the verify_url directly to the user \u2014 it is a complete, ready-to-open URL with the session token already embedded (e.g. https://www.agentscore.com/verify?session=sess_...). Do NOT modify or construct the URL yourself.",
21018
22382
  `Immediately begin polling poll_url every ${pollIntervalSeconds} seconds with header X-Poll-Secret set to poll_secret. The user will complete verification in their browser while you poll in the background.`,
21019
22383
  "The user visits the URL, signs in, completes identity verification (photo ID + selfie via Stripe Identity), and closes the tab. They do NOT need to copy or paste anything back to you.",
21020
22384
  'When your poll returns status "verified", extract operator_token from the response. This is a one-time value \u2014 save it immediately. Subsequent polls return status "consumed" without the token.',
@@ -21063,7 +22427,7 @@ var IDENTITY_VERIFICATION_REQUIRED_FALLBACK_INSTRUCTIONS = JSON.stringify({
21063
22427
  var API_ERROR_INSTRUCTIONS = JSON.stringify({
21064
22428
  action: "retry_with_backoff",
21065
22429
  steps: [
21066
- "Verification is temporarily unavailable. Retry the request after 5\u201330 seconds with exponential backoff.",
22430
+ "Verification is temporarily unavailable. Retry the request after 5-30 seconds with exponential backoff.",
21067
22431
  "This is NOT a compliance denial \u2014 the user does not need to re-verify their identity. Send the same identity headers (X-Wallet-Address or X-Operator-Token) on retry.",
21068
22432
  "If the request continues to fail after 3+ retries (~60 seconds total), surface the error to the user with the merchant's support contact."
21069
22433
  ],
@@ -21166,12 +22530,12 @@ function denialReasonToBody(reason) {
21166
22530
 
21167
22531
  // src/address.ts
21168
22532
  var SOLANA_BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
21169
- var isSolanaAddress = (address2) => SOLANA_BASE58_RE.test(address2) && !address2.startsWith("0x");
21170
- var normalizeAddress = (address2) => {
21171
- if (isSolanaAddress(address2)) {
21172
- return address2;
22533
+ var isSolanaAddress = (address3) => SOLANA_BASE58_RE.test(address3) && !address3.startsWith("0x");
22534
+ var normalizeAddress = (address3) => {
22535
+ if (isSolanaAddress(address3)) {
22536
+ return address3;
21173
22537
  }
21174
- return address2.toLowerCase();
22538
+ return address3.toLowerCase();
21175
22539
  };
21176
22540
 
21177
22541
  // src/cache.ts
@@ -21230,7 +22594,7 @@ function stripTrailingSlashes(s) {
21230
22594
  while (end > 0 && s.charCodeAt(end - 1) === 47) end--;
21231
22595
  return end === s.length ? s : s.slice(0, end);
21232
22596
  }
21233
- var CANONICAL_AGENTSCORE_API = "https://api.agentscore.sh";
22597
+ var CANONICAL_AGENTSCORE_API = "https://api.agentscore.com";
21234
22598
  var WALLET_SIGNER_MISMATCH_INSTRUCTIONS = JSON.stringify({
21235
22599
  action: "resign_or_switch_to_operator_token",
21236
22600
  steps: [
@@ -21262,7 +22626,7 @@ function buildAgentMemoryHint(aipTrustedIssuers) {
21262
22626
  return {
21263
22627
  save_for_future_agentscore_gates: true,
21264
22628
  pattern_summary: "AgentScore is a cross-merchant identity substrate for agent commerce. Any endpoint that returns 403 missing_identity / identity_verification_required or 402 challenges referencing AgentScore uses the same identity system. One KYC works across all AgentScore merchants \u2014 no re-verification per site. Save this pattern (and the endpoints below) to persistent memory so future AgentScore encounters skip the cold-start session flow.",
21265
- quickstart: "https://docs.agentscore.sh/guides/agent-identity",
22629
+ quickstart: "https://docs.agentscore.com/guides/agent-identity",
21266
22630
  identity_check_endpoint: `${api}/v1/credentials`,
21267
22631
  identity_paths: {
21268
22632
  wallet: "If paying from a crypto wallet you have used before on any AgentScore merchant, send `X-Wallet-Address: 0x...`. Shortest path; no token lifecycle to manage.",
@@ -21279,7 +22643,7 @@ function buildAgentMemoryHint(aipTrustedIssuers) {
21279
22643
  }
21280
22644
  function createAgentScoreCore(options) {
21281
22645
  if (!options.apiKey) {
21282
- throw new Error("AgentScore API key is required. Get one at https://agentscore.sh/sign-up");
22646
+ throw new Error("AgentScore API key is required. Get one at https://www.agentscore.com/sign-up");
21283
22647
  }
21284
22648
  const {
21285
22649
  apiKey,
@@ -21290,7 +22654,7 @@ function createAgentScoreCore(options) {
21290
22654
  allowedJurisdictions,
21291
22655
  failOpen = false,
21292
22656
  cacheSeconds = 300,
21293
- baseUrl: rawBaseUrl = "https://api.agentscore.sh",
22657
+ baseUrl: rawBaseUrl = "https://api.agentscore.com",
21294
22658
  chain: gateChain,
21295
22659
  userAgent,
21296
22660
  createSessionOnMissing,
@@ -21298,7 +22662,7 @@ function createAgentScoreCore(options) {
21298
22662
  } = options;
21299
22663
  const baseUrl = stripTrailingSlashes(rawBaseUrl);
21300
22664
  const agentMemoryHint = buildAgentMemoryHint(aipTrustedIssuers);
21301
- const defaultUa = `@agent-score/commerce@${"2.5.0"}`;
22665
+ const defaultUa = `@agent-score/commerce@${"2.6.0"}`;
21302
22666
  const userAgentHeader = userAgent ? `${userAgent} (${defaultUa})` : defaultUa;
21303
22667
  const sdk = new import_sdk.AgentScore({ apiKey, baseUrl, userAgent: userAgentHeader });
21304
22668
  const sessionSdkCache = /* @__PURE__ */ new Map();
@@ -21316,7 +22680,6 @@ function createAgentScoreCore(options) {
21316
22680
  return s;
21317
22681
  }
21318
22682
  const cache = new TTLCache(cacheSeconds * 1e3);
21319
- const lastSignerRaw = /* @__PURE__ */ new Map();
21320
22683
  async function tryMintSessionDenial(ctx) {
21321
22684
  if (!createSessionOnMissing) return void 0;
21322
22685
  try {
@@ -21388,7 +22751,7 @@ function createAgentScoreCore(options) {
21388
22751
  ...aipStep,
21389
22752
  "If you have a wallet AND this merchant accepts a wallet-signing rail (Tempo MPP or x402 \u2014 see openapi.json x-payment-info): send X-Wallet-Address and retry. If the wallet is already linked to an AgentScore operator (via prior SIWE claim or prior captureWallet), this passes in one round trip. If the wallet is unlinked or the account has no KYC, the 403 will include a verify_url \u2014 share it with the user to claim the wallet + complete KYC, then retry.",
21390
22753
  "If step 1 is denied or you already have a stored operator_token (valid + not expired): send X-Operator-Token: opc_... and retry.",
21391
- "If neither applies: retry with NO identity header. Merchants that auto-create verification sessions (most AgentScore merchants do) return verify_url + session_id + poll_secret in the 403 body \u2014 share verify_url with the user, then poll poll_url every 5s with the X-Poll-Secret header until status=verified (the poll returns a one-time operator_token). If the retry returns the same bare 403, this merchant does not support self-service session bootstrapping \u2014 direct the user to https://agentscore.sh/sign-up to create an AgentScore identity and mint an operator_token from their dashboard (https://agentscore.sh/dashboard/verify). The user hands the opc_... to you, and you retry with X-Operator-Token."
22754
+ "If neither applies: retry with NO identity header. Merchants that auto-create verification sessions (most AgentScore merchants do) return verify_url + session_id + poll_secret in the 403 body \u2014 share verify_url with the user, then poll poll_url every 5s with the X-Poll-Secret header until status=verified (the poll returns a one-time operator_token). If the retry returns the same bare 403, this merchant does not support self-service session bootstrapping \u2014 direct the user to https://www.agentscore.com/sign-up to create an AgentScore identity and mint an operator_token from their dashboard (https://www.agentscore.com/dashboard/verify). The user hands the opc_... to you, and you retry with X-Operator-Token."
21392
22755
  ],
21393
22756
  user_message: "Try X-Wallet-Address first if you have a wallet and the merchant accepts Tempo/x402; fall back to a stored X-Operator-Token, then to the session/verify flow described in agent_memory.bootstrap."
21394
22757
  });
@@ -21401,21 +22764,26 @@ function createAgentScoreCore(options) {
21401
22764
  }
21402
22765
  };
21403
22766
  }
21404
- const cacheKey2 = identity.aipToken ? `aip:${(0, import_node_crypto.createHash)("sha256").update(identity.aipToken).digest("hex")}` : identity.operatorToken?.toLowerCase() ?? (identity.address ? normalizeAddress(identity.address) : "");
22767
+ const identityKey = identity.aipToken ? `aip:${(0, import_node_crypto.createHash)("sha256").update(identity.aipToken).digest("hex")}` : identity.operatorToken?.toLowerCase() ?? (identity.address ? normalizeAddress(identity.address) : "");
22768
+ const cacheKey2 = signer ? JSON.stringify([identityKey, signer.network, normalizeAddress(signer.address)]) : JSON.stringify([identityKey]);
21405
22769
  const cached2 = cache.get(cacheKey2);
21406
22770
  if (cached2) {
22771
+ const cachedVerdict = cached2.raw ? buildSignerVerdict(identity, cached2.raw) : void 0;
21407
22772
  if (cached2.allow) {
21408
22773
  const cachedRaw = cached2.raw;
21409
22774
  const cachedQuota = cachedRaw?.quota;
21410
22775
  return {
21411
22776
  kind: "allow",
21412
22777
  data: cachedRaw,
21413
- ...cachedQuota !== void 0 && { quota: cachedQuota }
22778
+ ...cachedQuota !== void 0 && { quota: cachedQuota },
22779
+ ...cachedVerdict !== void 0 && { signerVerdict: cachedVerdict }
21414
22780
  };
21415
22781
  }
21416
22782
  if (isFixableDenial(cached2.reasons)) {
21417
22783
  const sessionReason = await tryMintSessionDenial(ctx);
21418
- if (sessionReason) return { kind: "deny", reason: sessionReason };
22784
+ if (sessionReason) {
22785
+ return { kind: "deny", reason: sessionReason, ...cachedVerdict !== void 0 && { signerVerdict: cachedVerdict } };
22786
+ }
21419
22787
  }
21420
22788
  return {
21421
22789
  kind: "deny",
@@ -21425,7 +22793,8 @@ function createAgentScoreCore(options) {
21425
22793
  reasons: cached2.reasons,
21426
22794
  verify_url: cached2.raw?.verify_url,
21427
22795
  data: cached2.raw
21428
- }
22796
+ },
22797
+ ...cachedVerdict !== void 0 && { signerVerdict: cachedVerdict }
21429
22798
  };
21430
22799
  }
21431
22800
  const policy = {};
@@ -21446,7 +22815,10 @@ function createAgentScoreCore(options) {
21446
22815
  // regardless of policy.require_sanctions_clear (which gates the separate NAME screen).
21447
22816
  ...signer && { signer: { address: signer.address, network: signer.network } }
21448
22817
  };
21449
- const result = identity.aipToken ? await sdk.assess(null, { ...opts, aipToken: identity.aipToken }) : identity.address ? await sdk.assess(identity.address, { ...opts, operatorToken: identity.operatorToken }) : await sdk.assess(null, { ...opts, operatorToken: identity.operatorToken });
22818
+ if (identity.aipToken !== void 0 && identity.aipSignature === void 0) {
22819
+ throw new Error("AgentScoreCore.evaluate: aipToken requires aipSignature (RFC 9421 proof-of-possession material).");
22820
+ }
22821
+ const result = identity.aipToken !== void 0 && identity.aipSignature !== void 0 ? await sdk.assess(null, { ...opts, aipToken: identity.aipToken, aipSignature: identity.aipSignature }) : identity.address ? await sdk.assess(identity.address, { ...opts, operatorToken: identity.operatorToken }) : await sdk.assess(null, { ...opts, operatorToken: identity.operatorToken });
21450
22822
  data = result;
21451
22823
  } catch (err) {
21452
22824
  if (err instanceof import_sdk.PaymentRequiredError) {
@@ -21517,20 +22889,21 @@ function createAgentScoreCore(options) {
21517
22889
  const decisionReasons = data.decision_reasons ?? [];
21518
22890
  const allow = decision === "allow" || decision == null;
21519
22891
  cache.set(cacheKey2, { allow, decision: decision ?? void 0, reasons: decisionReasons, raw: data });
21520
- if (identity.address !== void 0 && identity.operatorToken === void 0 && identity.aipToken === void 0 && (data.signer_match !== void 0 || data.signer_sanctions !== void 0)) {
21521
- lastSignerRaw.set(normalizeAddress(identity.address), data);
21522
- }
22892
+ const signerVerdict = buildSignerVerdict(identity, data);
21523
22893
  if (allow) {
21524
22894
  const quota = data.quota;
21525
22895
  return {
21526
22896
  kind: "allow",
21527
22897
  data,
21528
- ...quota !== void 0 && { quota }
22898
+ ...quota !== void 0 && { quota },
22899
+ ...signerVerdict !== void 0 && { signerVerdict }
21529
22900
  };
21530
22901
  }
21531
22902
  if (isFixableDenial(decisionReasons)) {
21532
22903
  const sessionReason = await tryMintSessionDenial(ctx);
21533
- if (sessionReason) return { kind: "deny", reason: sessionReason };
22904
+ if (sessionReason) {
22905
+ return { kind: "deny", reason: sessionReason, ...signerVerdict !== void 0 && { signerVerdict } };
22906
+ }
21534
22907
  }
21535
22908
  return {
21536
22909
  kind: "deny",
@@ -21540,7 +22913,8 @@ function createAgentScoreCore(options) {
21540
22913
  reasons: decisionReasons,
21541
22914
  verify_url: data.verify_url,
21542
22915
  data
21543
- }
22916
+ },
22917
+ ...signerVerdict !== void 0 && { signerVerdict }
21544
22918
  };
21545
22919
  }
21546
22920
  async function captureWallet(options2) {
@@ -21582,20 +22956,21 @@ function createAgentScoreCore(options) {
21582
22956
  agentInstructions: sm.agent_instructions ?? WALLET_SIGNER_MISMATCH_INSTRUCTIONS
21583
22957
  };
21584
22958
  }
21585
- function getSignerVerdict(claimedAddress) {
21586
- const claimedNorm = normalizeAddress(claimedAddress);
21587
- const raw = lastSignerRaw.get(claimedNorm) ?? cache.get(claimedNorm)?.raw;
21588
- if (!raw) return void 0;
22959
+ function buildSignerVerdict(identity, raw) {
22960
+ if (identity.address === void 0 || identity.operatorToken !== void 0 || identity.aipToken !== void 0) {
22961
+ return void 0;
22962
+ }
21589
22963
  const rawMatch = raw.signer_match;
21590
22964
  const rawSanctions = raw.signer_sanctions;
21591
22965
  if (!rawMatch && !rawSanctions) return void 0;
22966
+ const claimedNorm = normalizeAddress(identity.address);
21592
22967
  const signerNorm = rawMatch?.actual_signer ?? claimedNorm;
21593
22968
  return {
21594
22969
  signer_match: rawMatch ? projectSignerMatch(rawMatch, claimedNorm, signerNorm) : null,
21595
22970
  signer_sanctions: rawSanctions ?? null
21596
22971
  };
21597
22972
  }
21598
- return { evaluate, captureWallet, getSignerVerdict };
22973
+ return { evaluate, captureWallet };
21599
22974
  }
21600
22975
 
21601
22976
  // src/_headers.ts
@@ -21707,6 +23082,7 @@ var DEFAULT_TRANSPORT = "JSONRPC";
21707
23082
  var DEFAULT_INPUT_MODE = "application/json";
21708
23083
  var DEFAULT_OUTPUT_MODE = "application/json";
21709
23084
  var UCP_A2A_EXTENSION_URI = "https://ucp.dev/2026-04-08/specification/reference";
23085
+ var AIP_A2A_EXTENSION_URI = "https://www.agentscore.com/.well-known/agent-identity";
21710
23086
  function ucpA2AExtension(capabilities = {}, options = {}) {
21711
23087
  return {
21712
23088
  uri: UCP_A2A_EXTENSION_URI,
@@ -21715,6 +23091,20 @@ function ucpA2AExtension(capabilities = {}, options = {}) {
21715
23091
  params: { capabilities }
21716
23092
  };
21717
23093
  }
23094
+ function aipA2AExtension(opts = {}) {
23095
+ return {
23096
+ uri: AIP_A2A_EXTENSION_URI,
23097
+ description: "AIP support: present an Agent Identity Token (JWT) in an Agent-Identity header plus an RFC 9421 HTTP Message Signature (over @method @authority @path agent-identity) proving possession of the token-bound cnf key. `agentscore-pay pay --identity aip` attaches it automatically.",
23098
+ required: opts.required ?? false,
23099
+ params: {
23100
+ header: "Agent-Identity",
23101
+ signature: "RFC 9421",
23102
+ ...opts.trustedIssuers !== void 0 && opts.trustedIssuers.length > 0 && { trusted_issuers: opts.trustedIssuers },
23103
+ ...opts.requiredTrustLevel !== void 0 && { required_trust_level: opts.requiredTrustLevel },
23104
+ ...opts.requiredAmr !== void 0 && opts.requiredAmr.length > 0 && { required_amr: opts.requiredAmr }
23105
+ }
23106
+ };
23107
+ }
21718
23108
  function buildA2AAgentCard(input) {
21719
23109
  if (!input.skills || input.skills.length === 0) {
21720
23110
  throw new Error(
@@ -21781,26 +23171,45 @@ var CheckoutValidationError = class extends Error {
21781
23171
  };
21782
23172
 
21783
23173
  // src/identity/policy.ts
21784
- function buildGateFromPolicy(policy, base) {
23174
+ function buildGateFromPolicy(policy, base3) {
21785
23175
  if (!policy || !policy.enforcement) return null;
21786
23176
  return {
21787
- apiKey: base.apiKey,
21788
- ...base.baseUrl !== void 0 && { baseUrl: base.baseUrl },
23177
+ apiKey: base3.apiKey,
23178
+ ...base3.baseUrl !== void 0 && { baseUrl: base3.baseUrl },
21789
23179
  ...policy.requireKyc !== void 0 && { requireKyc: policy.requireKyc },
21790
23180
  ...policy.requireSanctionsClear !== void 0 && {
21791
23181
  requireSanctionsClear: policy.requireSanctionsClear
21792
23182
  },
21793
23183
  ...policy.minAge !== void 0 && { minAge: policy.minAge },
23184
+ ...policy.blockedJurisdictions !== void 0 && {
23185
+ blockedJurisdictions: [...policy.blockedJurisdictions]
23186
+ },
21794
23187
  ...policy.allowedJurisdictions !== void 0 && {
21795
23188
  allowedJurisdictions: [...policy.allowedJurisdictions]
21796
23189
  }
21797
23190
  };
21798
23191
  }
23192
+ var SANCTIONS_DENIAL_REASONS = /* @__PURE__ */ new Set([
23193
+ "sanctions_flagged",
23194
+ "sanctions_check_unavailable"
23195
+ ]);
23196
+ function isSanctionsDenial(body) {
23197
+ if (!body || typeof body !== "object") return false;
23198
+ for (const key of ["reasons", "decision_reasons"]) {
23199
+ const raw = body[key];
23200
+ if (Array.isArray(raw) && raw.some((r) => typeof r === "string" && SANCTIONS_DENIAL_REASONS.has(r))) {
23201
+ return true;
23202
+ }
23203
+ }
23204
+ const error51 = body.error;
23205
+ const code = error51 && typeof error51 === "object" ? error51.code : void 0;
23206
+ return typeof code === "string" && SANCTIONS_DENIAL_REASONS.has(code);
23207
+ }
21799
23208
  async function runGateWithEnforcement(enforcement, runGate) {
21800
23209
  if (!runGate || !enforcement) return { status: "anonymous" };
21801
23210
  const outcome = await runGate();
21802
23211
  if (outcome.ok) return { status: "verified" };
21803
- if (enforcement === "hard") {
23212
+ if (enforcement === "hard" || isSanctionsDenial(outcome.body)) {
21804
23213
  return {
21805
23214
  status: "denied",
21806
23215
  denialStatus: outcome.status,
@@ -21890,7 +23299,7 @@ function extractOwnerScope(input) {
21890
23299
  const walletAddress = readHeader(headers, "x-wallet-address");
21891
23300
  const operatorToken = readHeader(headers, "x-operator-token");
21892
23301
  return {
21893
- ...walletAddress ? { walletAddress } : {},
23302
+ ...walletAddress ? { walletAddress: normalizeAddress(walletAddress) } : {},
21894
23303
  ...operatorToken ? { operatorTokenHash: hashOperatorToken(operatorToken) } : {}
21895
23304
  };
21896
23305
  }
@@ -21960,6 +23369,7 @@ var bytesToB64 = (bytes) => {
21960
23369
  var AIP_COVERED_COMPONENTS = ["@method", "@authority", "@path", "agent-identity"];
21961
23370
  var AIP_SIGNATURE_TAG = "agent-identity";
21962
23371
  var DEFAULT_MAX_SKEW_SECONDS = 60;
23372
+ var MAX_POP_WINDOW_SECONDS = 120;
21963
23373
  var normalizeAuthority = (authority) => {
21964
23374
  const lower = authority.trim().toLowerCase();
21965
23375
  const colon = lower.lastIndexOf(":");
@@ -22010,7 +23420,7 @@ var serializeParams = (p) => {
22010
23420
  }
22011
23421
  return parts.map((s) => `;${s}`).join("");
22012
23422
  };
22013
- var buildSignatureBase = (params, input) => {
23423
+ var buildSignatureBase = (params, input, rawSignatureParams) => {
22014
23424
  const lines = [];
22015
23425
  for (const name of params.components) {
22016
23426
  const value = componentValue(name, input);
@@ -22019,7 +23429,7 @@ var buildSignatureBase = (params, input) => {
22019
23429
  }
22020
23430
  lines.push(`"${name}": ${value}`);
22021
23431
  }
22022
- const paramsValue = serializeComponentList(params.components) + serializeParams(params);
23432
+ const paramsValue = rawSignatureParams ?? serializeComponentList(params.components) + serializeParams(params);
22023
23433
  lines.push(`"@signature-params": ${paramsValue}`);
22024
23434
  return lines.join("\n");
22025
23435
  };
@@ -22038,19 +23448,12 @@ var parseSignatureInput = (header, tag = AIP_SIGNATURE_TAG) => {
22038
23448
  }
22039
23449
  const parsed = members.map((m) => {
22040
23450
  const params = parseInnerListMember(m.value);
22041
- return params ? { label: m.label, params } : null;
23451
+ return params ? { label: m.label, params, rawParams: m.value } : null;
22042
23452
  }).filter((x) => x !== null);
22043
23453
  if (parsed.length === 0) {
22044
23454
  return null;
22045
23455
  }
22046
- const tagged = parsed.find((p) => p.params.tag === tag);
22047
- if (tagged) {
22048
- return tagged;
22049
- }
22050
- if (parsed.length === 1 && parsed[0].params.tag === void 0) {
22051
- return parsed[0];
22052
- }
22053
- return null;
23456
+ return parsed.find((p) => p.params.tag === tag) ?? null;
22054
23457
  };
22055
23458
  var parseSignatureValue = (header, label) => {
22056
23459
  const members = splitDictionary(header);
@@ -22164,7 +23567,7 @@ var verifyMessageSignature = async (input) => {
22164
23567
  if (!selected) {
22165
23568
  return { ok: false, reason: "no_aip_signature" };
22166
23569
  }
22167
- const { label, params } = selected;
23570
+ const { label, params, rawParams } = selected;
22168
23571
  if (params.alg !== void 0 && !["ed25519", "eddsa"].includes(params.alg.toLowerCase())) {
22169
23572
  return { ok: false, reason: "unsupported_alg" };
22170
23573
  }
@@ -22173,12 +23576,21 @@ var verifyMessageSignature = async (input) => {
22173
23576
  return { ok: false, reason: "missing_covered_component" };
22174
23577
  }
22175
23578
  }
23579
+ if (params.created === void 0) {
23580
+ return { ok: false, reason: "created_missing" };
23581
+ }
23582
+ if (params.expires === void 0) {
23583
+ return { ok: false, reason: "expires_missing" };
23584
+ }
23585
+ if (params.expires < params.created || params.expires - params.created > MAX_POP_WINDOW_SECONDS) {
23586
+ return { ok: false, reason: "pop_window_too_long" };
23587
+ }
22176
23588
  const now = input.now ?? Math.floor(Date.now() / 1e3);
22177
23589
  const skew = input.maxSkewSeconds ?? DEFAULT_MAX_SKEW_SECONDS;
22178
- if (params.created !== void 0 && params.created > now + skew) {
23590
+ if (params.created > now + skew) {
22179
23591
  return { ok: false, reason: "created_in_future" };
22180
23592
  }
22181
- if (params.expires !== void 0 && params.expires < now - skew) {
23593
+ if (params.expires < now - skew) {
22182
23594
  return { ok: false, reason: "expired" };
22183
23595
  }
22184
23596
  if (!params.keyid) {
@@ -22201,15 +23613,15 @@ var verifyMessageSignature = async (input) => {
22201
23613
  if (!sig) {
22202
23614
  return { ok: false, reason: "malformed_signature" };
22203
23615
  }
22204
- let base;
23616
+ let base3;
22205
23617
  try {
22206
- base = buildSignatureBase(params, {
23618
+ base3 = buildSignatureBase(params, {
22207
23619
  method: input.method,
22208
23620
  authority: input.authority,
22209
23621
  path: input.path,
22210
23622
  agentIdentity: input.agentIdentity,
22211
23623
  extra: input.extraComponents
22212
- });
23624
+ }, rawParams);
22213
23625
  } catch (err) {
22214
23626
  if (err instanceof MissingComponentError) {
22215
23627
  return { ok: false, reason: "missing_covered_component" };
@@ -22226,7 +23638,7 @@ var verifyMessageSignature = async (input) => {
22226
23638
  { name: "Ed25519" },
22227
23639
  key,
22228
23640
  sig,
22229
- new TextEncoder().encode(base)
23641
+ new TextEncoder().encode(base3)
22230
23642
  );
22231
23643
  } catch {
22232
23644
  return { ok: false, reason: "signature_invalid" };
@@ -22245,7 +23657,7 @@ var signMessage = async (input) => {
22245
23657
  keyid,
22246
23658
  tag: AIP_SIGNATURE_TAG
22247
23659
  };
22248
- const base = buildSignatureBase(params, {
23660
+ const base3 = buildSignatureBase(params, {
22249
23661
  method: input.method,
22250
23662
  authority: input.authority,
22251
23663
  path: input.path,
@@ -22259,7 +23671,7 @@ var signMessage = async (input) => {
22259
23671
  const sigBytes = await subtle.sign(
22260
23672
  "Ed25519",
22261
23673
  key,
22262
- new TextEncoder().encode(base)
23674
+ new TextEncoder().encode(base3)
22263
23675
  );
22264
23676
  const b64 = bytesToB64(new Uint8Array(sigBytes));
22265
23677
  const signatureInput = `${label}=${serializeComponentList(components)}${serializeParams(params)}`;
@@ -22315,6 +23727,8 @@ var verifyAit = async (ctx, opts) => {
22315
23727
  if (!ctx.signatureInput || !ctx.signature) {
22316
23728
  return { ok: false, reason: "pop_signature_missing" };
22317
23729
  }
23730
+ const signatureInput = ctx.signatureInput;
23731
+ const signature2 = ctx.signature;
22318
23732
  let lastFailure = "malformed_token";
22319
23733
  for (const raw of ctx.agentIdentityHeaders) {
22320
23734
  const token = stripBearer(raw);
@@ -22353,7 +23767,7 @@ var verifyAit = async (ctx, opts) => {
22353
23767
  // Pin the signature algorithm allowlist (RFC 8725 §3.1) — also rejects `alg:none`. Without
22354
23768
  // this, jose accepts whatever alg the resolved JWK supports, so a trusted IdP publishing a
22355
23769
  // non-Ed25519 (e.g. RSA/EC) `use:sig` key would let an attacker present an RS256/ES256
22356
- // token that verifies. Matches the server-side allowlist in core/api aip-verify.
23770
+ // token that verifies. Matches the server-side allowlist in the AgentScore API verifier.
22357
23771
  algorithms: AIT_SIGNING_ALGS,
22358
23772
  clockTolerance: jwtClockTolerance,
22359
23773
  currentDate: opts.now !== void 0 ? new Date(opts.now * 1e3) : void 0
@@ -22367,13 +23781,20 @@ var verifyAit = async (ctx, opts) => {
22367
23781
  lastFailure = "expired_token";
22368
23782
  continue;
22369
23783
  }
23784
+ if (claims.exp - claims.iat > (opts.maxLifetimeSeconds ?? 300)) {
23785
+ lastFailure = "expired_token";
23786
+ continue;
23787
+ }
22370
23788
  const popResult = await verifyMessageSignature({
22371
23789
  method: ctx.method,
22372
23790
  authority: ctx.authority,
22373
23791
  path: ctx.path,
22374
- agentIdentity: raw,
22375
- signatureInput: ctx.signatureInput,
22376
- signature: ctx.signature,
23792
+ // The agent-identity covered component is the BARE AIT (a Bearer prefix, if present, is
23793
+ // transport that `stripBearer` removed above). Verify over `token`, not `raw`, so the edge and
23794
+ // the API — which verifies over the forwarded bare aip_token — reconstruct the identical base.
23795
+ agentIdentity: token,
23796
+ signatureInput,
23797
+ signature: signature2,
22377
23798
  cnfJwk: claims.cnf.jwk,
22378
23799
  now: opts.now,
22379
23800
  maxSkewSeconds: opts.maxSkewSeconds
@@ -22382,7 +23803,22 @@ var verifyAit = async (ctx, opts) => {
22382
23803
  lastFailure = "pop_signature_invalid";
22383
23804
  continue;
22384
23805
  }
22385
- return { ok: true, ait: { payload: claims, iss: claims.iss, cnfJwk: claims.cnf.jwk, token } };
23806
+ return {
23807
+ ok: true,
23808
+ ait: {
23809
+ payload: claims,
23810
+ iss: claims.iss,
23811
+ cnfJwk: claims.cnf.jwk,
23812
+ token,
23813
+ signatureMaterial: {
23814
+ method: ctx.method,
23815
+ authority: ctx.authority,
23816
+ path: ctx.path,
23817
+ signature_input: signatureInput,
23818
+ signature: signature2
23819
+ }
23820
+ }
23821
+ };
22386
23822
  }
22387
23823
  return { ok: false, reason: lastFailure };
22388
23824
  };
@@ -22403,11 +23839,11 @@ var readAgentIdentityHeaders = (headers) => {
22403
23839
  return raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
22404
23840
  };
22405
23841
  var deriveAuthority = (req, url2) => req.headers.get("host") ?? url2.host;
22406
- var buildVerifyContextFromRequest = (req) => {
23842
+ var buildVerifyContextFromRequest = (req, authority) => {
22407
23843
  const url2 = new URL(req.url);
22408
23844
  return {
22409
23845
  method: req.method,
22410
- authority: deriveAuthority(req, url2),
23846
+ authority: authority ?? deriveAuthority(req, url2),
22411
23847
  path: url2.pathname,
22412
23848
  agentIdentityHeaders: readAgentIdentityHeaders(req.headers),
22413
23849
  signatureInput: req.headers.get("signature-input"),
@@ -22432,7 +23868,12 @@ var buildVerifyContextFromParts = (parts) => {
22432
23868
  const host = parts.authority ?? readNodeHeader(parts.headers, "host") ?? "";
22433
23869
  let path;
22434
23870
  try {
22435
- path = new URL(parts.url, host ? `http://${host}` : "http://localhost").pathname;
23871
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(parts.url)) {
23872
+ path = new URL(parts.url).pathname;
23873
+ } else {
23874
+ const target = parts.url.startsWith("/") ? parts.url : `/${parts.url}`;
23875
+ path = new URL(`http://${host || "localhost"}${target}`).pathname;
23876
+ }
22436
23877
  } catch {
22437
23878
  const q = parts.url.indexOf("?");
22438
23879
  path = q === -1 ? parts.url : parts.url.slice(0, q);
@@ -22452,8 +23893,12 @@ var verifyFromContext = async (ctx, opts) => {
22452
23893
  const result = await verifyAit(ctx, { jwks: opts.jwks, now: opts.now, maxSkewSeconds: opts.maxSkewSeconds });
22453
23894
  return result.ok ? { ok: true, ait: result.ait } : { ok: false, failure: result.reason };
22454
23895
  };
22455
- var verifyAitRequest = (req, opts) => verifyFromContext(buildVerifyContextFromRequest(req), opts);
22456
- var verifyAitParts = (parts, opts) => verifyFromContext(buildVerifyContextFromParts(parts), opts);
23896
+ var partsWithAuthority = (parts, opts) => {
23897
+ const authority = parts.authority ?? opts.authority;
23898
+ return authority !== void 0 ? { ...parts, authority } : parts;
23899
+ };
23900
+ var verifyAitRequest = (req, opts) => verifyFromContext(buildVerifyContextFromRequest(req, opts.authority), opts);
23901
+ var verifyAitParts = (parts, opts) => verifyFromContext(buildVerifyContextFromParts(partsWithAuthority(parts, opts)), opts);
22457
23902
  var aipErrorCode = (failure) => {
22458
23903
  switch (failure) {
22459
23904
  case "no_token":
@@ -22510,21 +23955,116 @@ var aipErrorDetail = (failure) => {
22510
23955
  return "Token verification failed.";
22511
23956
  }
22512
23957
  };
22513
- var buildAipErrorBody = (failure) => {
23958
+ var buildAipErrorBody = (failure, requirements) => {
22514
23959
  const code = aipErrorCode(failure);
22515
- return {
23960
+ const body = {
22516
23961
  type: `urn:aip:error:${code}`,
22517
23962
  title: code.replace(/_/g, " "),
22518
23963
  status: aipErrorStatus(failure),
22519
23964
  detail: aipErrorDetail(failure)
22520
23965
  };
23966
+ if (requirements) {
23967
+ if (code === "untrusted_issuer" && requirements.trustedIssuers?.length) {
23968
+ body.trusted_issuers = requirements.trustedIssuers;
23969
+ }
23970
+ if (code === "insufficient_claims") {
23971
+ if (requirements.requiredClaims?.length) body.required_claims = requirements.requiredClaims;
23972
+ if (requirements.requiredTrustLevel !== void 0) body.required_trust_level = requirements.requiredTrustLevel;
23973
+ if (requirements.requiredAmr?.length) body.required_amr = requirements.requiredAmr;
23974
+ }
23975
+ }
23976
+ return body;
23977
+ };
23978
+ var aipPolicyDenyCode = (code) => {
23979
+ switch (code) {
23980
+ case "token_expired":
23981
+ return { code: "expired_token", status: 401 };
23982
+ case "invalid_credential":
23983
+ return { code: "invalid_signature", status: 401 };
23984
+ case "api_error":
23985
+ return { code: "idp_unavailable", status: 503 };
23986
+ default:
23987
+ return { code: "insufficient_claims", status: 403 };
23988
+ }
23989
+ };
23990
+ var buildAipPolicyDenyBody = (code, reasons, body, requirements) => {
23991
+ const spec = aipPolicyDenyCode(code);
23992
+ const reasonList = reasons ?? [];
23993
+ const detail = spec.code === "insufficient_claims" ? reasonList.length > 0 ? `The Agent Identity Token did not attest a passing value for the required compliance claim(s). AgentScore decision: ${code} (${reasonList.join(", ")}).` : `The Agent Identity Token did not satisfy the merchant's compliance policy. AgentScore decision: ${code}.` : `AgentScore decision: ${code}.`;
23994
+ const superset = {
23995
+ type: `urn:aip:error:${spec.code}`,
23996
+ title: spec.code.replace(/_/g, " "),
23997
+ status: spec.status,
23998
+ detail
23999
+ };
24000
+ if (requirements && spec.code === "insufficient_claims") {
24001
+ if (requirements.requiredClaims?.length) superset.required_claims = requirements.requiredClaims;
24002
+ if (requirements.requiredTrustLevel !== void 0) superset.required_trust_level = requirements.requiredTrustLevel;
24003
+ if (requirements.requiredAmr?.length) superset.required_amr = requirements.requiredAmr;
24004
+ }
24005
+ const { type: _type, title: _title, status: _status, detail: _detail, ...rest } = body;
24006
+ return { ...superset, ...rest };
24007
+ };
24008
+ var TRUST_RANK = { autonomous: 0, human_present: 1, human_confirmed: 2 };
24009
+ var checkTrustRequirements = (payload, requiredTrustLevel, requiredAmr) => {
24010
+ if (requiredTrustLevel !== void 0) {
24011
+ const have = TRUST_RANK[payload.trust_level ?? "autonomous"] ?? 0;
24012
+ const need = TRUST_RANK[requiredTrustLevel] ?? 0;
24013
+ if (have < need) {
24014
+ return `This endpoint requires trust_level '${requiredTrustLevel}'; the token asserts '${payload.trust_level ?? "autonomous"}'. Re-mint an AIT at the required trust level (human confirmation).`;
24015
+ }
24016
+ }
24017
+ if (requiredAmr !== void 0 && requiredAmr.length > 0) {
24018
+ const amr = Array.isArray(payload.auth?.amr) ? payload.auth.amr : [];
24019
+ if (!amr.some((m) => requiredAmr.includes(m))) {
24020
+ return `This endpoint requires an authentication method in [${requiredAmr.join(", ")}]; the token carries [${amr.join(", ") || "none"}].`;
24021
+ }
24022
+ }
24023
+ return null;
24024
+ };
24025
+ var buildAipWeakAuthBody = (opts) => ({
24026
+ type: "urn:aip:error:weak_auth",
24027
+ title: "weak auth",
24028
+ status: 403,
24029
+ detail: opts.detail,
24030
+ ...opts.requiredTrustLevel !== void 0 && { required_trust_level: opts.requiredTrustLevel },
24031
+ ...opts.requiredAmr !== void 0 && opts.requiredAmr.length > 0 && { required_amr: opts.requiredAmr },
24032
+ ...opts.trustedIssuers !== void 0 && opts.trustedIssuers.length > 0 && { trusted_issuers: opts.trustedIssuers }
24033
+ });
24034
+ var requirementsFromOptions = (opts) => ({
24035
+ ...opts.trustedIssuers !== void 0 && { trustedIssuers: opts.trustedIssuers },
24036
+ ...opts.requiredClaims !== void 0 && { requiredClaims: opts.requiredClaims },
24037
+ ...opts.requireTrustLevel !== void 0 && { requiredTrustLevel: opts.requireTrustLevel },
24038
+ ...opts.requireAmr !== void 0 && { requiredAmr: opts.requireAmr }
24039
+ });
24040
+ var evaluateFromContext = async (ctx, opts) => {
24041
+ const result = await verifyAit(ctx, { jwks: opts.jwks, now: opts.now, maxSkewSeconds: opts.maxSkewSeconds });
24042
+ if (!result.ok) {
24043
+ return { ok: false, body: buildAipErrorBody(result.reason, requirementsFromOptions(opts)) };
24044
+ }
24045
+ const weak = checkTrustRequirements(result.ait.payload, opts.requireTrustLevel, opts.requireAmr);
24046
+ if (weak !== null) {
24047
+ return {
24048
+ ok: false,
24049
+ body: buildAipWeakAuthBody({
24050
+ detail: weak,
24051
+ ...opts.requireTrustLevel !== void 0 && { requiredTrustLevel: opts.requireTrustLevel },
24052
+ ...opts.requireAmr !== void 0 && { requiredAmr: opts.requireAmr },
24053
+ ...opts.trustedIssuers !== void 0 && { trustedIssuers: opts.trustedIssuers }
24054
+ })
24055
+ };
24056
+ }
24057
+ return { ok: true, ait: result.ait };
22521
24058
  };
24059
+ var evaluateAipRequest = (req, opts) => evaluateFromContext(buildVerifyContextFromRequest(req, opts.authority), opts);
24060
+ var evaluateAipParts = (parts, opts) => evaluateFromContext(buildVerifyContextFromParts(partsWithAuthority(parts, opts)), opts);
22522
24061
 
22523
24062
  // src/aip/jwks.ts
22524
24063
  var JWKS_WELL_KNOWN_PATH = "/.well-known/agent-identity/jwks.json";
22525
24064
  var HARD_MAX_CACHE_SECONDS = 86400;
22526
24065
  var DEFAULT_CACHE_SECONDS = 300;
22527
- var AGENTSCORE_CANONICAL_ISSUER = "https://agentscore.sh";
24066
+ var REFETCH_COOLDOWN_MS = 3e4;
24067
+ var AGENTSCORE_CANONICAL_ISSUER = "https://www.agentscore.com";
22528
24068
  var canonicalizeIssuer = (iss) => {
22529
24069
  let url2;
22530
24070
  try {
@@ -22563,6 +24103,12 @@ var JwksCache = class {
22563
24103
  now;
22564
24104
  userAgent;
22565
24105
  cache = /* @__PURE__ */ new Map();
24106
+ /** Per-issuer in-flight refresh promise — coalesces concurrent refreshes to ONE upstream fetch.
24107
+ * Without it, a concurrent burst of distinct-kid lookups on a cold/expired cache each call
24108
+ * `refresh()` before any has populated the cache → N parallel JWKS GETs (refetch amplification).
24109
+ * The cooldown only suppresses SEQUENTIAL refetches; single-flight suppresses CONCURRENT ones.
24110
+ * Entry is cleared in a `finally` once the fetch settles. */
24111
+ inflight = /* @__PURE__ */ new Map();
22566
24112
  constructor(opts) {
22567
24113
  this.trusted = new Set(
22568
24114
  [AGENTSCORE_CANONICAL_ISSUER, ...opts.trustedIssuers ?? []].map(canonicalizeIssuer).filter((s) => s !== null)
@@ -22594,13 +24140,21 @@ var JwksCache = class {
22594
24140
  if (hit2) {
22595
24141
  return { ok: true, key: hit2 };
22596
24142
  }
24143
+ if (this.now() < cached2.cooldownUntil) {
24144
+ return { ok: false, reason: "key_not_found" };
24145
+ }
24146
+ } else if (cached2 && this.now() < cached2.cooldownUntil) {
24147
+ return { ok: false, reason: cached2.lastFailure ?? "key_not_found" };
22597
24148
  }
22598
24149
  const refreshed = await this.refresh(canon);
22599
24150
  if (!refreshed.ok) {
22600
24151
  return refreshed;
22601
24152
  }
22602
24153
  const hit = this.select(refreshed.keys, kid);
22603
- return hit ? { ok: true, key: hit } : { ok: false, reason: "key_not_found" };
24154
+ if (hit) {
24155
+ return { ok: true, key: hit };
24156
+ }
24157
+ return { ok: false, reason: "key_not_found" };
22604
24158
  }
22605
24159
  select(keys, kid) {
22606
24160
  const candidates = signingKeys(keys);
@@ -22613,31 +24167,68 @@ var JwksCache = class {
22613
24167
  }
22614
24168
  return candidates.length === 1 ? candidates[0] : void 0;
22615
24169
  }
24170
+ /**
24171
+ * Refresh the cached key set for `canonIssuer`, coalescing concurrent callers onto a single
24172
+ * upstream fetch (single-flight). The first caller for an issuer with no in-flight refresh kicks
24173
+ * off the fetch and registers the promise; concurrent callers await that same promise instead of
24174
+ * issuing their own GET. The entry is cleared once the fetch settles so the NEXT cold/expired
24175
+ * lookup can refresh again.
24176
+ */
22616
24177
  async refresh(canonIssuer) {
24178
+ const existing = this.inflight.get(canonIssuer);
24179
+ if (existing !== void 0) {
24180
+ return existing;
24181
+ }
24182
+ const promise2 = this.fetchAndCache(canonIssuer).finally(() => {
24183
+ this.inflight.delete(canonIssuer);
24184
+ });
24185
+ this.inflight.set(canonIssuer, promise2);
24186
+ return promise2;
24187
+ }
24188
+ async fetchAndCache(canonIssuer) {
22617
24189
  const url2 = `${canonIssuer}${JWKS_WELL_KNOWN_PATH}`;
22618
24190
  let res;
22619
24191
  try {
22620
24192
  res = await this.fetchImpl(url2, { headers: { "User-Agent": this.userAgent, Accept: "application/jwk-set+json, application/json" } });
22621
24193
  } catch {
22622
- return { ok: false, reason: "fetch_failed" };
24194
+ return this.stampFailure(canonIssuer, "fetch_failed");
22623
24195
  }
22624
24196
  if (!res.ok) {
22625
- return { ok: false, reason: "fetch_failed" };
24197
+ return this.stampFailure(canonIssuer, "fetch_failed");
22626
24198
  }
22627
24199
  let body;
22628
24200
  try {
22629
24201
  body = await res.json();
22630
24202
  } catch {
22631
- return { ok: false, reason: "malformed_jwks" };
24203
+ return this.stampFailure(canonIssuer, "malformed_jwks");
22632
24204
  }
22633
24205
  if (typeof body !== "object" || body === null || !Array.isArray(body.keys)) {
22634
- return { ok: false, reason: "malformed_jwks" };
24206
+ return this.stampFailure(canonIssuer, "malformed_jwks");
22635
24207
  }
22636
24208
  const keys = body.keys;
22637
24209
  const ttlSeconds = resolveCacheSeconds(res.headers.get("cache-control"));
22638
- this.cache.set(canonIssuer, { keys, expiresAt: this.now() + ttlSeconds * 1e3 });
24210
+ const now = this.now();
24211
+ this.cache.set(canonIssuer, {
24212
+ keys,
24213
+ expiresAt: now + ttlSeconds * 1e3,
24214
+ cooldownUntil: now + REFETCH_COOLDOWN_MS
24215
+ });
22639
24216
  return { ok: true, keys };
22640
24217
  }
24218
+ /** Stamp the per-issuer refetch cooldown on a FAILED fetch attempt (the negative cache). Any
24219
+ * previously cached keys + expiry are preserved — a failed kid-miss refetch must not nuke a
24220
+ * still-fresh key set; only the cooldown and failure reason are updated. */
24221
+ stampFailure(canonIssuer, reason) {
24222
+ const now = this.now();
24223
+ const prev = this.cache.get(canonIssuer);
24224
+ this.cache.set(canonIssuer, {
24225
+ keys: prev?.keys ?? [],
24226
+ expiresAt: prev?.expiresAt ?? now,
24227
+ cooldownUntil: now + REFETCH_COOLDOWN_MS,
24228
+ lastFailure: reason
24229
+ });
24230
+ return { ok: false, reason };
24231
+ }
22641
24232
  };
22642
24233
 
22643
24234
  // src/payment/rail_spec.ts
@@ -22822,6 +24413,7 @@ function build402Body({
22822
24413
  if (x402) {
22823
24414
  body.x402Version = x402.version ?? 2;
22824
24415
  body.accepts = x402.accepts;
24416
+ if (x402.resource !== void 0) body.resource = x402.resource;
22825
24417
  if (x402.extensions !== void 0 && Object.keys(x402.extensions).length > 0) {
22826
24418
  body.extensions = x402.extensions;
22827
24419
  }
@@ -22997,7 +24589,7 @@ function respond402({
22997
24589
  const headers = normalizeHeadersToLowercase(mppxChallengeHeaders);
22998
24590
  headers["content-type"] = "application/json";
22999
24591
  if (x402) {
23000
- headers["payment-required"] = paymentRequiredHeader(x402);
24592
+ headers["payment-required"] = paymentRequiredHeader2(x402);
23001
24593
  }
23002
24594
  return { body, headers, status: 402 };
23003
24595
  }
@@ -23021,6 +24613,29 @@ function buildValidationError({
23021
24613
  return body;
23022
24614
  }
23023
24615
 
24616
+ // src/discovery/bazaar.ts
24617
+ async function enrichBazaarDiscoveryExtensions(extensions, request) {
24618
+ if (extensions === void 0) return extensions;
24619
+ const bazaar = await dynamicImport("@x402/extensions/bazaar");
24620
+ const ext = bazaar?.bazaarResourceServerExtension;
24621
+ if (!ext?.key || typeof ext.enrichDeclaration !== "function") return extensions;
24622
+ const declaration = extensions[ext.key];
24623
+ if (declaration === void 0) return extensions;
24624
+ const transportContext = {
24625
+ method: request.method,
24626
+ adapter: { getPath: () => request.path },
24627
+ routePattern: request.path
24628
+ };
24629
+ return { ...extensions, [ext.key]: ext.enrichDeclaration(declaration, transportContext) };
24630
+ }
24631
+ async function dynamicImport(moduleName) {
24632
+ try {
24633
+ return await import(moduleName);
24634
+ } catch {
24635
+ return null;
24636
+ }
24637
+ }
24638
+
23024
24639
  // src/payment/constants.ts
23025
24640
  var STRIPE_MIN_CHARGE_USD = 0.5;
23026
24641
 
@@ -23077,7 +24692,7 @@ async function createMppxServer({
23077
24692
  methods: extraMethods,
23078
24693
  secretKey
23079
24694
  }) {
23080
- const mppx = await dynamicImport("mppx/server");
24695
+ const mppx = await dynamicImport2("mppx/server");
23081
24696
  if (!mppx?.Mppx?.create) {
23082
24697
  throw new Error("mppx not installed \u2014 `npm install mppx` to use createMppxServer.");
23083
24698
  }
@@ -23132,7 +24747,7 @@ async function registerTempoSession(mppx, spec) {
23132
24747
  });
23133
24748
  }
23134
24749
  async function registerSolana(spec) {
23135
- const solanaMpp = await dynamicImport("@solana/mpp/server");
24750
+ const solanaMpp = await dynamicImport2("@solana/mpp/server");
23136
24751
  if (!solanaMpp?.charge) {
23137
24752
  throw new Error(
23138
24753
  "@solana/mpp not installed \u2014 `npm install @solana/mpp @solana/kit` to use the solana rail."
@@ -23171,7 +24786,7 @@ async function registerStripe(spec) {
23171
24786
  paymentMethodTypes: spec.paymentMethodTypes
23172
24787
  });
23173
24788
  }
23174
- async function dynamicImport(moduleName) {
24789
+ async function dynamicImport2(moduleName) {
23175
24790
  try {
23176
24791
  return await import(moduleName);
23177
24792
  } catch {
@@ -23248,7 +24863,7 @@ function registerX402SchemesV1V2(server, network, scheme) {
23248
24863
 
23249
24864
  // src/payment/x402_server.ts
23250
24865
  async function createX402Server(opts = {}) {
23251
- const x402Core = await dynamicImport2("@x402/core/server") ?? null;
24866
+ const x402Core = await dynamicImport3("@x402/core/server") ?? null;
23252
24867
  if (!x402Core) {
23253
24868
  throw new Error(
23254
24869
  "@x402/core not installed \u2014 `npm install @x402/core` to use createX402Server."
@@ -23257,7 +24872,7 @@ async function createX402Server(opts = {}) {
23257
24872
  let facilitator;
23258
24873
  const facilitatorChoice = opts.facilitator ?? (process.env.CDP_API_KEY_ID && process.env.CDP_API_KEY_SECRET ? "coinbase" : "http");
23259
24874
  if (facilitatorChoice === "coinbase") {
23260
- const cb = await dynamicImport2("@coinbase/x402");
24875
+ const cb = await dynamicImport3("@coinbase/x402");
23261
24876
  if (!cb?.facilitator) {
23262
24877
  throw new Error(
23263
24878
  '@coinbase/x402 not installed \u2014 `npm install @coinbase/x402` for facilitator: "coinbase".'
@@ -23278,13 +24893,13 @@ async function createX402Server(opts = {}) {
23278
24893
  const baseRail = isUpto ? rail.slice(0, -5) : rail;
23279
24894
  const network = baseRail === "x402-base-mainnet" ? networks.base.mainnet.caip2 : networks.base.sepolia.caip2;
23280
24895
  if (isUpto) {
23281
- evmUptoModule ??= await dynamicImport2("@x402/evm/upto/server");
24896
+ evmUptoModule ??= await dynamicImport3("@x402/evm/upto/server");
23282
24897
  if (!evmUptoModule?.UptoEvmScheme) {
23283
24898
  throw new Error("@x402/evm not installed \u2014 `npm install @x402/evm` for x402 base upto rails.");
23284
24899
  }
23285
24900
  registerX402SchemesV1V2(server, network, new evmUptoModule.UptoEvmScheme());
23286
24901
  } else {
23287
- evmExactModule ??= await dynamicImport2("@x402/evm/exact/server");
24902
+ evmExactModule ??= await dynamicImport3("@x402/evm/exact/server");
23288
24903
  if (!evmExactModule?.ExactEvmScheme) {
23289
24904
  throw new Error("@x402/evm not installed \u2014 `npm install @x402/evm` for x402 base rails.");
23290
24905
  }
@@ -23296,7 +24911,7 @@ async function createX402Server(opts = {}) {
23296
24911
  registerX402SchemesV1V2(server, network, scheme);
23297
24912
  }
23298
24913
  if (opts.bazaar) {
23299
- const bazaar = await dynamicImport2("@x402/extensions/bazaar");
24914
+ const bazaar = await dynamicImport3("@x402/extensions/bazaar");
23300
24915
  if (!bazaar?.bazaarResourceServerExtension) {
23301
24916
  throw new Error(
23302
24917
  "@x402/extensions not installed \u2014 `npm install @x402/extensions` for bazaar discovery."
@@ -23322,7 +24937,7 @@ async function buildX402AcceptsFor402(server, opts) {
23322
24937
  );
23323
24938
  return Array.isArray(requirements) ? requirements : [];
23324
24939
  }
23325
- async function dynamicImport2(moduleName) {
24940
+ async function dynamicImport3(moduleName) {
23326
24941
  try {
23327
24942
  return await import(moduleName);
23328
24943
  } catch {
@@ -23499,12 +25114,12 @@ async function processX402Settle({
23499
25114
  enrichedExt,
23500
25115
  resolvedTransportContext
23501
25116
  );
23502
- const paymentResponseHeader = settleResult ? Buffer.from(JSON.stringify(settleResult)).toString("base64") : void 0;
25117
+ const paymentResponseHeader2 = settleResult ? Buffer.from(JSON.stringify(settleResult)).toString("base64") : void 0;
23503
25118
  return {
23504
25119
  success: true,
23505
25120
  matchedRequirement,
23506
25121
  settleResult,
23507
- paymentResponseHeader,
25122
+ paymentResponseHeader: paymentResponseHeader2,
23508
25123
  verifyResult
23509
25124
  };
23510
25125
  } catch (err) {
@@ -23746,6 +25361,19 @@ function isStripeRailSpec2(s) {
23746
25361
  function isTempoSessionRailSpec3(s) {
23747
25362
  return "escrowContract" in s && "store" in s;
23748
25363
  }
25364
+ function staticRecipient2(r) {
25365
+ return typeof r === "string" && r.length > 0 ? r : null;
25366
+ }
25367
+ function collectStaticX402Recipients(rails2) {
25368
+ const out = /* @__PURE__ */ new Set();
25369
+ for (const spec of Object.values(rails2)) {
25370
+ if (isStripeRailSpec2(spec) || isTempoSessionRailSpec3(spec)) continue;
25371
+ if (!isEvmNetwork(spec)) continue;
25372
+ const recipient = staticRecipient2(spec.recipient);
25373
+ if (recipient !== null) out.add(recipient.toLowerCase());
25374
+ }
25375
+ return out;
25376
+ }
23749
25377
  function specRailKey(spec) {
23750
25378
  if (isStripeRailSpec2(spec)) return "stripe";
23751
25379
  if (isTempoSessionRailSpec3(spec)) return "tempo_mpp";
@@ -23844,6 +25472,16 @@ function buildAipTrustedIssuers(externalIssuers) {
23844
25472
  function aipTrustedIssuerSet(cfg) {
23845
25473
  return buildAipTrustedIssuers(cfg.trustedIssuers);
23846
25474
  }
25475
+ function aipRequiredClaims(policy) {
25476
+ const claims = [];
25477
+ if (policy.requireKyc) claims.push("id_verified");
25478
+ if (policy.requireSanctionsClear) claims.push("sanctions_clear");
25479
+ if (policy.minAge != null) claims.push(`age_over_${policy.minAge}`);
25480
+ if (policy.blockedJurisdictions !== void 0 || policy.allowedJurisdictions !== void 0) {
25481
+ claims.push("jurisdiction");
25482
+ }
25483
+ return claims;
25484
+ }
23847
25485
  function resolveIssuerPolicy(issuerPolicies, iss) {
23848
25486
  const target = canonicalizeIssuer(iss);
23849
25487
  if (target === null) return void 0;
@@ -23864,9 +25502,14 @@ var Checkout = class {
23864
25502
  mintReferenceId;
23865
25503
  onSettled;
23866
25504
  isCachedAddress;
25505
+ /** Lowercased static recipient addresses for the x402-base rail(s). When the merchant
25506
+ * configured a static recipient and supplied no `isCachedAddress`, the gate binds the
25507
+ * agent-supplied `payTo` to this set (anti funds-drain). Empty for pure per-order minting. */
25508
+ x402StaticRecipients;
23867
25509
  zeroSettleCarveOut;
23868
25510
  gate;
23869
25511
  discoveryExtensions;
25512
+ resourceInfo;
23870
25513
  discoveryProbe;
23871
25514
  _x402ServerGetter;
23872
25515
  /** Lazily-built JWKS cache for AIP verification, shared across requests so issuer keys
@@ -23943,9 +25586,11 @@ var Checkout = class {
23943
25586
  this.mintReferenceId = opts.mintReferenceId;
23944
25587
  this.onSettled = opts.onSettled;
23945
25588
  this.isCachedAddress = opts.isCachedAddress;
25589
+ this.x402StaticRecipients = collectStaticX402Recipients(opts.rails);
23946
25590
  this.zeroSettleCarveOut = opts.zeroSettleCarveOut ?? false;
23947
25591
  this.gate = opts.gate;
23948
25592
  this.discoveryExtensions = opts.discoveryExtensions;
25593
+ this.resourceInfo = opts.resourceInfo;
23949
25594
  this.discoveryProbe = opts.discoveryProbe;
23950
25595
  }
23951
25596
  /** Canonical `RailKey` list derived from the configured rails dict. Each
@@ -24170,6 +25815,7 @@ var Checkout = class {
24170
25815
  const operatorToken = headers["x-operator-token"];
24171
25816
  let aipToken;
24172
25817
  let aipIssuer;
25818
+ let aipSignature;
24173
25819
  if (gate.aip !== void 0 && hasAgentIdentityHeaderNode(headers)) {
24174
25820
  const aipResult = await verifyAitParts(
24175
25821
  {
@@ -24184,7 +25830,11 @@ var Checkout = class {
24184
25830
  }
24185
25831
  );
24186
25832
  if (!aipResult.ok) {
24187
- const body2 = buildAipErrorBody(aipResult.failure);
25833
+ const body2 = buildAipErrorBody(aipResult.failure, {
25834
+ trustedIssuers: aipTrustedIssuerSet(gate.aip),
25835
+ ...gate.aip.requireTrustLevel !== void 0 && { requiredTrustLevel: gate.aip.requireTrustLevel },
25836
+ ...gate.aip.requireAmr !== void 0 && { requiredAmr: gate.aip.requireAmr }
25837
+ });
24188
25838
  return {
24189
25839
  status: body2.status,
24190
25840
  body: body2,
@@ -24198,6 +25848,17 @@ var Checkout = class {
24198
25848
  }
24199
25849
  aipToken = aipResult.ait.token;
24200
25850
  aipIssuer = aipResult.ait.iss;
25851
+ aipSignature = aipResult.ait.signatureMaterial;
25852
+ const weakAuthDetail = checkTrustRequirements(aipResult.ait.payload, gate.aip.requireTrustLevel, gate.aip.requireAmr);
25853
+ if (weakAuthDetail) {
25854
+ const body2 = buildAipWeakAuthBody({
25855
+ detail: weakAuthDetail,
25856
+ ...gate.aip.requireTrustLevel !== void 0 && { requiredTrustLevel: gate.aip.requireTrustLevel },
25857
+ ...gate.aip.requireAmr !== void 0 && { requiredAmr: gate.aip.requireAmr },
25858
+ trustedIssuers: aipTrustedIssuerSet(gate.aip)
25859
+ });
25860
+ return { status: 403, body: body2, headers: { "content-type": "application/problem+json" } };
25861
+ }
24201
25862
  }
24202
25863
  const issuerPolicy = aipIssuer !== void 0 && gate.aip?.issuerPolicies !== void 0 ? resolveIssuerPolicy(gate.aip.issuerPolicies, aipIssuer) : void 0;
24203
25864
  const effPolicy = issuerPolicy ?? {
@@ -24228,7 +25889,7 @@ var Checkout = class {
24228
25889
  let policyOverride;
24229
25890
  if (gate.perRequestPolicy !== void 0) {
24230
25891
  policyOverride = await gate.perRequestPolicy(ctx);
24231
- if (policyOverride === null) return null;
25892
+ if (policyOverride === null) return this.runWalletSanctionsOnly(ctx);
24232
25893
  }
24233
25894
  const coreOpts = {
24234
25895
  apiKey: gate.apiKey,
@@ -24262,7 +25923,7 @@ var Checkout = class {
24262
25923
  ...policyOverride ?? {}
24263
25924
  };
24264
25925
  const core = createAgentScoreCore(coreOpts);
24265
- const identity = aipToken !== void 0 ? { aipToken } : walletAddress !== void 0 || operatorToken !== void 0 ? {
25926
+ const identity = aipToken !== void 0 ? { aipToken, ...aipSignature !== void 0 && { aipSignature } } : walletAddress !== void 0 || operatorToken !== void 0 ? {
24266
25927
  ...walletAddress !== void 0 && { address: walletAddress },
24267
25928
  ...operatorToken !== void 0 && { operatorToken }
24268
25929
  } : void 0;
@@ -24282,8 +25943,7 @@ var Checkout = class {
24282
25943
  };
24283
25944
  }
24284
25945
  if (aipToken === void 0 && walletAddress !== void 0) {
24285
- const verdict = core.getSignerVerdict(walletAddress);
24286
- const sm = verdict?.signer_match;
25946
+ const sm = outcome.signerVerdict?.signer_match;
24287
25947
  if (sm && sm.kind !== "pass") {
24288
25948
  const reason2 = sm.kind === "wallet_auth_requires_wallet_signing" ? {
24289
25949
  code: "wallet_auth_requires_wallet_signing",
@@ -24314,6 +25974,19 @@ var Checkout = class {
24314
25974
  if (custom2 !== null) return custom2;
24315
25975
  }
24316
25976
  const body = denialReasonToBody(reason);
25977
+ if (aipToken !== void 0) {
25978
+ const superset = buildAipPolicyDenyBody(reason.code, reason.reasons, body, {
25979
+ trustedIssuers: gate.aip !== void 0 ? aipTrustedIssuerSet(gate.aip) : void 0,
25980
+ requiredClaims: aipRequiredClaims(effPolicy),
25981
+ ...gate.aip?.requireTrustLevel !== void 0 && { requiredTrustLevel: gate.aip.requireTrustLevel },
25982
+ ...gate.aip?.requireAmr !== void 0 && { requiredAmr: gate.aip.requireAmr }
25983
+ });
25984
+ return {
25985
+ status: superset.status,
25986
+ body: superset,
25987
+ headers: { "content-type": "application/problem+json" }
25988
+ };
25989
+ }
24317
25990
  const status = reason.code === "token_expired" || reason.code === "invalid_credential" ? 401 : reason.code === "api_error" ? 503 : 403;
24318
25991
  return { status, body };
24319
25992
  }
@@ -24329,7 +26002,7 @@ var Checkout = class {
24329
26002
  * - `AGENTSCORE_API_KEY` — required. No key → one-time warning + skip
24330
26003
  * (dev/testnet pattern; production should always configure a key).
24331
26004
  * - `AGENTSCORE_BASE_URL` — optional override for staging/dev API
24332
- * (e.g. `https://api-dev.agentscore.sh` or `http://localhost:3002`).
26005
+ * (e.g. `https://api.staging.example` or `http://localhost:3002`).
24333
26006
  *
24334
26007
  * Stripe SPT (no extractable wallet signer) → skip silently; Stripe runs
24335
26008
  * its own OFAC screen on the buyer's Stripe account at customer creation.
@@ -24342,7 +26015,7 @@ var Checkout = class {
24342
26015
  * clean buyer is just bad UX).
24343
26016
  */
24344
26017
  async runWalletSanctionsOnly(ctx) {
24345
- const apiKey = process.env.AGENTSCORE_API_KEY;
26018
+ const apiKey = this.gate?.apiKey ?? process.env.AGENTSCORE_API_KEY;
24346
26019
  if (!apiKey) {
24347
26020
  warnMissingApiKeyOnce("checkout");
24348
26021
  return null;
@@ -24371,8 +26044,7 @@ var Checkout = class {
24371
26044
  }
24372
26045
  async handleZeroSettle(ctx, rail) {
24373
26046
  if (!this.zeroSettleCarveOut || ctx.pricing === null) return null;
24374
- const cents = Math.round(ctx.pricing.amountUsd * 100);
24375
- if (cents !== 0) return null;
26047
+ if (ctx.pricing.amountUsd !== 0) return null;
24376
26048
  const headers = normalizeHeadersToLowercase(ctx.request.headers);
24377
26049
  let zero;
24378
26050
  if (rail === "x402-base") {
@@ -24413,9 +26085,16 @@ var Checkout = class {
24413
26085
  ctx.recipients = { ...await this.mintRecipients(ctx) };
24414
26086
  return ctx.recipients;
24415
26087
  }
24416
- async asyncIsCachedAddress(address2) {
24417
- if (this.isCachedAddress === void 0) return true;
24418
- return Promise.resolve(this.isCachedAddress(address2));
26088
+ async asyncIsCachedAddress(address3, ctx) {
26089
+ if (this.isCachedAddress !== void 0) return Promise.resolve(this.isCachedAddress(address3));
26090
+ const minted = ctx?.recipients["x402_base"];
26091
+ if (minted !== void 0 && minted.length > 0) {
26092
+ return address3.toLowerCase() === minted.toLowerCase();
26093
+ }
26094
+ if (this.x402StaticRecipients.size > 0) {
26095
+ return this.x402StaticRecipients.has(address3.toLowerCase());
26096
+ }
26097
+ return true;
24419
26098
  }
24420
26099
  async handleX402(ctx) {
24421
26100
  const x402Server = await this.getX402Server();
@@ -24428,7 +26107,7 @@ var Checkout = class {
24428
26107
  });
24429
26108
  const verified = await verifyX402Request({
24430
26109
  request: fakeRequest,
24431
- isCachedAddress: this.asyncIsCachedAddress.bind(this),
26110
+ isCachedAddress: (addr) => this.asyncIsCachedAddress(addr, ctx),
24432
26111
  acceptedNetwork: this.x402BaseNetwork
24433
26112
  });
24434
26113
  if (!verified.ok) {
@@ -24452,7 +26131,7 @@ var Checkout = class {
24452
26131
  maxTimeoutSeconds: 300
24453
26132
  },
24454
26133
  resourceMeta: {
24455
- url: ctx.request.url,
26134
+ url: resolveResourceUrl(ctx.request),
24456
26135
  description: "Agent purchase via x402",
24457
26136
  mimeType: "application/json"
24458
26137
  }
@@ -24610,13 +26289,29 @@ var Checkout = class {
24610
26289
  payTo: recipient,
24611
26290
  maxTimeoutSeconds: 300
24612
26291
  });
24613
- x402Resource = { url: ctx.request.url, mimeType: "application/json" };
26292
+ x402Resource = {
26293
+ url: resolveResourceUrl(ctx.request),
26294
+ mimeType: "application/json",
26295
+ ...this.resourceInfo?.description !== void 0 && { description: this.resourceInfo.description },
26296
+ ...this.resourceInfo?.serviceName !== void 0 && { serviceName: this.resourceInfo.serviceName },
26297
+ ...this.resourceInfo?.tags !== void 0 && { tags: this.resourceInfo.tags },
26298
+ ...this.resourceInfo?.iconUrl !== void 0 && { iconUrl: this.resourceInfo.iconUrl }
26299
+ };
24614
26300
  } catch {
24615
26301
  x402Accepts = [];
24616
26302
  }
24617
26303
  }
24618
26304
  }
24619
26305
  const identityMetadata = resolveIdentityMetadata(ctx);
26306
+ let requestPath = ctx.request.url;
26307
+ try {
26308
+ requestPath = new URL(resolveResourceUrl(ctx.request)).pathname;
26309
+ } catch {
26310
+ }
26311
+ const enrichedExtensions = await enrichBazaarDiscoveryExtensions(this.discoveryExtensions, {
26312
+ method: ctx.request.method,
26313
+ path: requestPath
26314
+ });
24620
26315
  const body = build402Body({
24621
26316
  acceptedMethods: accepted,
24622
26317
  agentInstructions: buildAgentInstructions({ howToPay }),
@@ -24638,7 +26333,8 @@ var Checkout = class {
24638
26333
  ...x402Accepts.length > 0 ? {
24639
26334
  x402: {
24640
26335
  accepts: x402Accepts,
24641
- ...this.discoveryExtensions !== void 0 && Object.keys(this.discoveryExtensions).length > 0 ? { extensions: this.discoveryExtensions } : {}
26336
+ ...x402Resource ? { resource: x402Resource } : {},
26337
+ ...enrichedExtensions !== void 0 && Object.keys(enrichedExtensions).length > 0 ? { extensions: enrichedExtensions } : {}
24642
26338
  }
24643
26339
  } : {}
24644
26340
  });
@@ -24647,7 +26343,8 @@ var Checkout = class {
24647
26343
  x402Block = {
24648
26344
  x402Version: 2,
24649
26345
  accepts: x402Accepts,
24650
- ...x402Resource ? { resource: x402Resource } : {}
26346
+ ...x402Resource ? { resource: x402Resource } : {},
26347
+ ...enrichedExtensions !== void 0 && Object.keys(enrichedExtensions).length > 0 ? { extensions: enrichedExtensions } : {}
24651
26348
  };
24652
26349
  }
24653
26350
  const respond = respond402({
@@ -24725,11 +26422,18 @@ function validationResponseNextjs(input) {
24725
26422
  function validationResponseWeb(input) {
24726
26423
  return validationResponseHono(input);
24727
26424
  }
24728
- function invalidBodyEnvelope() {
24729
- return validationEnvelope({
24730
- code: "invalid_body",
24731
- message: "Request body must be valid JSON."
24732
- });
26425
+ function resolveResourceUrl(request) {
26426
+ const fwd = request.headers["x-forwarded-proto"] ?? request.headers["X-Forwarded-Proto"];
26427
+ const proto = typeof fwd === "string" ? fwd.split(",")[0]?.trim() : void 0;
26428
+ if (proto) {
26429
+ try {
26430
+ const u = new URL(request.url);
26431
+ u.protocol = `${proto}:`;
26432
+ return u.toString();
26433
+ } catch {
26434
+ }
26435
+ }
26436
+ return request.url;
24733
26437
  }
24734
26438
  function stripContentType(headers) {
24735
26439
  const out = {};
@@ -24738,6 +26442,12 @@ function stripContentType(headers) {
24738
26442
  }
24739
26443
  return out;
24740
26444
  }
26445
+ function explicitContentType(headers) {
26446
+ for (const [k, v] of Object.entries(headers)) {
26447
+ if (k.toLowerCase() === "content-type") return v;
26448
+ }
26449
+ return void 0;
26450
+ }
24741
26451
  function headersToRecord(h) {
24742
26452
  if (h === void 0) return {};
24743
26453
  if (h instanceof Headers) {
@@ -24757,10 +26467,7 @@ Checkout.prototype.handleHono = async function(c, body) {
24757
26467
  try {
24758
26468
  parsedBody = await c.req.json();
24759
26469
  } catch {
24760
- return new Response(JSON.stringify(invalidBodyEnvelope()), {
24761
- status: 400,
24762
- headers: { "Content-Type": "application/json" }
24763
- });
26470
+ parsedBody = {};
24764
26471
  }
24765
26472
  }
24766
26473
  const rawHeaders = c.req.header();
@@ -24775,16 +26482,11 @@ Checkout.prototype.handleHono = async function(c, body) {
24775
26482
  });
24776
26483
  return new Response(JSON.stringify(result.body), {
24777
26484
  status: result.status,
24778
- headers: { "Content-Type": "application/json", ...stripContentType(result.headers) }
26485
+ headers: { "Content-Type": explicitContentType(result.headers) ?? "application/json", ...stripContentType(result.headers) }
24779
26486
  });
24780
26487
  };
24781
26488
  Checkout.prototype.handleExpress = async function(req, res, body) {
24782
- const parsedBody = body ?? (typeof req.body === "object" && req.body !== null ? req.body : null);
24783
- if (parsedBody === null) {
24784
- res.status(400);
24785
- res.json(invalidBodyEnvelope());
24786
- return;
24787
- }
26489
+ const parsedBody = body ?? (typeof req.body === "object" && req.body !== null ? req.body : {});
24788
26490
  const headers = {};
24789
26491
  for (const [k, v] of Object.entries(req.headers)) {
24790
26492
  if (typeof v === "string") headers[k] = v;
@@ -24800,15 +26502,13 @@ Checkout.prototype.handleExpress = async function(req, res, body) {
24800
26502
  raw: req
24801
26503
  });
24802
26504
  for (const [k, v] of Object.entries(stripContentType(result.headers))) res.setHeader(k, v);
26505
+ const ct = explicitContentType(result.headers);
26506
+ if (ct !== void 0) res.setHeader("Content-Type", ct);
24803
26507
  res.status(result.status);
24804
26508
  res.json(result.body);
24805
26509
  };
24806
26510
  Checkout.prototype.handleFastify = async function(request, reply, body) {
24807
- const parsedBody = body ?? (typeof request.body === "object" && request.body !== null ? request.body : null);
24808
- if (parsedBody === null) {
24809
- reply.code(400);
24810
- return reply.send(invalidBodyEnvelope());
24811
- }
26511
+ const parsedBody = body ?? (typeof request.body === "object" && request.body !== null ? request.body : {});
24812
26512
  const headers = {};
24813
26513
  for (const [k, v] of Object.entries(request.headers)) {
24814
26514
  if (typeof v === "string") headers[k] = v;
@@ -24824,6 +26524,11 @@ Checkout.prototype.handleFastify = async function(request, reply, body) {
24824
26524
  });
24825
26525
  for (const [k, v] of Object.entries(stripContentType(result.headers))) reply.header(k, v);
24826
26526
  reply.code(result.status);
26527
+ const ct = explicitContentType(result.headers);
26528
+ if (ct !== void 0) {
26529
+ reply.header("content-type", ct);
26530
+ return reply.send(JSON.stringify(result.body));
26531
+ }
24827
26532
  return reply.send(result.body);
24828
26533
  };
24829
26534
  Checkout.prototype.handleNextjs = async function(request, body) {
@@ -24834,10 +26539,7 @@ Checkout.prototype.handleNextjs = async function(request, body) {
24834
26539
  try {
24835
26540
  parsedBody = await request.json();
24836
26541
  } catch {
24837
- return new Response(JSON.stringify(invalidBodyEnvelope()), {
24838
- status: 400,
24839
- headers: { "Content-Type": "application/json" }
24840
- });
26542
+ parsedBody = {};
24841
26543
  }
24842
26544
  }
24843
26545
  const headers = {};
@@ -24854,7 +26556,7 @@ Checkout.prototype.handleNextjs = async function(request, body) {
24854
26556
  });
24855
26557
  return new Response(JSON.stringify(result.body), {
24856
26558
  status: result.status,
24857
- headers: { "Content-Type": "application/json", ...stripContentType(result.headers) }
26559
+ headers: { "Content-Type": explicitContentType(result.headers) ?? "application/json", ...stripContentType(result.headers) }
24858
26560
  });
24859
26561
  };
24860
26562
  Checkout.prototype.handleWeb = Checkout.prototype.handleNextjs;
@@ -25327,7 +27029,7 @@ function computeFirstCheckout(opts) {
25327
27029
  for (const [k, v] of Object.entries(mppChallengeHeaders)) headers.set(k, v);
25328
27030
  headers.set(
25329
27031
  "PAYMENT-REQUIRED",
25330
- paymentRequiredHeader({ x402Version: 2, accepts: accepted, resource: { url: opts.url } })
27032
+ paymentRequiredHeader2({ x402Version: 2, accepts: accepted, resource: { url: opts.url } })
25331
27033
  );
25332
27034
  return new Response(JSON.stringify(body402), { status: 402, headers });
25333
27035
  }
@@ -25362,9 +27064,10 @@ function computeFirstCheckout(opts) {
25362
27064
  );
25363
27065
  }
25364
27066
  async function handleX402Settle(req, referenceId, cachedBody, priceCents, recipients) {
27067
+ const expectedPayTo = recipients.x402_base?.toLowerCase();
25365
27068
  const verified = await verifyX402Request({
25366
27069
  request: req,
25367
- isCachedAddress: async () => true,
27070
+ isCachedAddress: async (addr) => expectedPayTo === void 0 || addr.toLowerCase() === expectedPayTo,
25368
27071
  acceptedNetwork: opts.rails.x402_base?.network ?? "eip155:8453"
25369
27072
  });
25370
27073
  if (!verified.ok) {
@@ -25697,6 +27400,7 @@ function defaultReadOnlyOnDenied(reason) {
25697
27400
  AGENTSCORE_CANONICAL_ISSUER,
25698
27401
  AGENTSCORE_UCP_CAPABILITY,
25699
27402
  AGENT_IDENTITY_HEADER,
27403
+ AIP_A2A_EXTENSION_URI,
25700
27404
  AIP_COVERED_COMPONENTS,
25701
27405
  AIP_SIGNATURE_TAG,
25702
27406
  Checkout,
@@ -25705,15 +27409,18 @@ function defaultReadOnlyOnDenied(reason) {
25705
27409
  HARD_MAX_CACHE_SECONDS,
25706
27410
  JWKS_WELL_KNOWN_PATH,
25707
27411
  JwksCache,
27412
+ MAX_POP_WINDOW_SECONDS,
25708
27413
  UCPSigningKey,
25709
27414
  UCPVerificationError,
25710
27415
  UCP_A2A_EXTENSION_URI,
27416
+ aipA2AExtension,
25711
27417
  aipErrorCode,
25712
27418
  aipErrorStatus,
25713
27419
  buildA2AAgentCard,
25714
27420
  buildAgentMemoryHint,
25715
27421
  buildAipErrorBody,
25716
27422
  buildAipTrustedIssuers,
27423
+ buildAipWeakAuthBody,
25717
27424
  buildContactSupportNextSteps,
25718
27425
  buildDefaultCheckoutRails,
25719
27426
  buildGateFromPolicy,
@@ -25724,12 +27431,15 @@ function defaultReadOnlyOnDenied(reason) {
25724
27431
  buildVerificationRequiredBody,
25725
27432
  buildVerifyContextFromRequest,
25726
27433
  canonicalizeIssuer,
27434
+ checkTrustRequirements,
25727
27435
  computeFirstCheckout,
25728
27436
  createDefaultOnDenied,
25729
27437
  createQuoteCache,
25730
27438
  defaultReadOnlyOnDenied,
25731
27439
  denialReasonStatus,
25732
27440
  denialReasonToBody,
27441
+ evaluateAipParts,
27442
+ evaluateAipRequest,
25733
27443
  extractOwnerScope,
25734
27444
  extractPaymentSigner,
25735
27445
  extractPaymentSignerFromAuth,
@@ -25750,6 +27460,7 @@ function defaultReadOnlyOnDenied(reason) {
25750
27460
  loadUCPSigningKeyFromEnv,
25751
27461
  makeMppxComposeHook,
25752
27462
  mppPaymentHandler,
27463
+ normalizeAddress,
25753
27464
  pricingResult,
25754
27465
  readX402PaymentHeader,
25755
27466
  runGateWithEnforcement,