x402-express-mantle 1.0.0 → 1.0.3

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 (125) hide show
  1. package/README.md +52 -30
  2. package/lib/cjs/index.d.ts +119 -81
  3. package/lib/cjs/index.js +3 -3
  4. package/lib/esm/index.d.mts +5 -5
  5. package/lib/esm/index.mjs +3 -3
  6. package/package.json +17 -5
  7. package/lib/cjs/client/index.d.ts +0 -243
  8. package/lib/cjs/client/index.js +0 -413
  9. package/lib/cjs/client/index.js.map +0 -1
  10. package/lib/cjs/exact/client/index.d.ts +0 -37
  11. package/lib/cjs/exact/client/index.js +0 -281
  12. package/lib/cjs/exact/client/index.js.map +0 -1
  13. package/lib/cjs/exact/facilitator/index.d.ts +0 -110
  14. package/lib/cjs/exact/facilitator/index.js +0 -714
  15. package/lib/cjs/exact/facilitator/index.js.map +0 -1
  16. package/lib/cjs/exact/server/index.d.ts +0 -87
  17. package/lib/cjs/exact/server/index.js +0 -209
  18. package/lib/cjs/exact/server/index.js.map +0 -1
  19. package/lib/cjs/exact/v1/client/index.d.ts +0 -33
  20. package/lib/cjs/exact/v1/client/index.js +0 -169
  21. package/lib/cjs/exact/v1/client/index.js.map +0 -1
  22. package/lib/cjs/exact/v1/facilitator/index.d.ts +0 -71
  23. package/lib/cjs/exact/v1/facilitator/index.js +0 -384
  24. package/lib/cjs/exact/v1/facilitator/index.js.map +0 -1
  25. package/lib/cjs/facilitator/index.d.ts +0 -192
  26. package/lib/cjs/facilitator/index.js +0 -398
  27. package/lib/cjs/facilitator/index.js.map +0 -1
  28. package/lib/cjs/http/index.d.ts +0 -52
  29. package/lib/cjs/http/index.js +0 -827
  30. package/lib/cjs/http/index.js.map +0 -1
  31. package/lib/cjs/mechanisms-CzuGzYsS.d.ts +0 -270
  32. package/lib/cjs/scheme-MoBRXFM8.d.ts +0 -29
  33. package/lib/cjs/server/index.d.ts +0 -2
  34. package/lib/cjs/server/index.js +0 -1305
  35. package/lib/cjs/server/index.js.map +0 -1
  36. package/lib/cjs/signer-5OVDxViv.d.ts +0 -79
  37. package/lib/cjs/signer-BMkbhFYE.d.ts +0 -123
  38. package/lib/cjs/types/index.d.ts +0 -1
  39. package/lib/cjs/types/index.js +0 -66
  40. package/lib/cjs/types/index.js.map +0 -1
  41. package/lib/cjs/types/v1/index.d.ts +0 -1
  42. package/lib/cjs/types/v1/index.js +0 -19
  43. package/lib/cjs/types/v1/index.js.map +0 -1
  44. package/lib/cjs/utils/index.d.ts +0 -48
  45. package/lib/cjs/utils/index.js +0 -116
  46. package/lib/cjs/utils/index.js.map +0 -1
  47. package/lib/cjs/v1/index.d.ts +0 -12
  48. package/lib/cjs/v1/index.js +0 -180
  49. package/lib/cjs/v1/index.js.map +0 -1
  50. package/lib/cjs/x402HTTPResourceServer-D1YtlH_r.d.ts +0 -719
  51. package/lib/esm/chunk-3CEIVWNN.mjs +0 -339
  52. package/lib/esm/chunk-3CEIVWNN.mjs.map +0 -1
  53. package/lib/esm/chunk-BJTO5JO5.mjs +0 -11
  54. package/lib/esm/chunk-BJTO5JO5.mjs.map +0 -1
  55. package/lib/esm/chunk-EEA7DKZI.mjs +0 -111
  56. package/lib/esm/chunk-EEA7DKZI.mjs.map +0 -1
  57. package/lib/esm/chunk-FOUXRQAV.mjs +0 -88
  58. package/lib/esm/chunk-FOUXRQAV.mjs.map +0 -1
  59. package/lib/esm/chunk-IKSTWKEM.mjs +0 -157
  60. package/lib/esm/chunk-IKSTWKEM.mjs.map +0 -1
  61. package/lib/esm/chunk-JYZWCLMP.mjs +0 -305
  62. package/lib/esm/chunk-JYZWCLMP.mjs.map +0 -1
  63. package/lib/esm/chunk-PNSAJQCF.mjs +0 -108
  64. package/lib/esm/chunk-PNSAJQCF.mjs.map +0 -1
  65. package/lib/esm/chunk-PSA4YVU2.mjs +0 -92
  66. package/lib/esm/chunk-PSA4YVU2.mjs.map +0 -1
  67. package/lib/esm/chunk-QLXM7BIB.mjs +0 -23
  68. package/lib/esm/chunk-QLXM7BIB.mjs.map +0 -1
  69. package/lib/esm/chunk-TDLQZ6MP.mjs +0 -86
  70. package/lib/esm/chunk-TDLQZ6MP.mjs.map +0 -1
  71. package/lib/esm/chunk-VE37GDG2.mjs +0 -7
  72. package/lib/esm/chunk-VE37GDG2.mjs.map +0 -1
  73. package/lib/esm/chunk-WWACQNRQ.mjs +0 -7
  74. package/lib/esm/chunk-WWACQNRQ.mjs.map +0 -1
  75. package/lib/esm/chunk-X4W4S5RB.mjs +0 -39
  76. package/lib/esm/chunk-X4W4S5RB.mjs.map +0 -1
  77. package/lib/esm/chunk-Z4QX3O5V.mjs +0 -748
  78. package/lib/esm/chunk-Z4QX3O5V.mjs.map +0 -1
  79. package/lib/esm/chunk-ZYXTTU74.mjs +0 -88
  80. package/lib/esm/chunk-ZYXTTU74.mjs.map +0 -1
  81. package/lib/esm/client/index.d.mts +0 -243
  82. package/lib/esm/client/index.mjs +0 -260
  83. package/lib/esm/client/index.mjs.map +0 -1
  84. package/lib/esm/exact/client/index.d.mts +0 -37
  85. package/lib/esm/exact/client/index.mjs +0 -36
  86. package/lib/esm/exact/client/index.mjs.map +0 -1
  87. package/lib/esm/exact/facilitator/index.d.mts +0 -110
  88. package/lib/esm/exact/facilitator/index.mjs +0 -350
  89. package/lib/esm/exact/facilitator/index.mjs.map +0 -1
  90. package/lib/esm/exact/server/index.d.mts +0 -87
  91. package/lib/esm/exact/server/index.mjs +0 -129
  92. package/lib/esm/exact/server/index.mjs.map +0 -1
  93. package/lib/esm/exact/v1/client/index.d.mts +0 -33
  94. package/lib/esm/exact/v1/client/index.mjs +0 -8
  95. package/lib/esm/exact/v1/client/index.mjs.map +0 -1
  96. package/lib/esm/exact/v1/facilitator/index.d.mts +0 -71
  97. package/lib/esm/exact/v1/facilitator/index.mjs +0 -8
  98. package/lib/esm/exact/v1/facilitator/index.mjs.map +0 -1
  99. package/lib/esm/facilitator/index.d.mts +0 -192
  100. package/lib/esm/facilitator/index.mjs +0 -373
  101. package/lib/esm/facilitator/index.mjs.map +0 -1
  102. package/lib/esm/http/index.d.mts +0 -52
  103. package/lib/esm/http/index.mjs +0 -29
  104. package/lib/esm/http/index.mjs.map +0 -1
  105. package/lib/esm/mechanisms-CzuGzYsS.d.mts +0 -270
  106. package/lib/esm/scheme-fjF-9LhT.d.mts +0 -29
  107. package/lib/esm/server/index.d.mts +0 -2
  108. package/lib/esm/server/index.mjs +0 -563
  109. package/lib/esm/server/index.mjs.map +0 -1
  110. package/lib/esm/signer-5OVDxViv.d.mts +0 -79
  111. package/lib/esm/signer-BMkbhFYE.d.mts +0 -123
  112. package/lib/esm/types/index.d.mts +0 -1
  113. package/lib/esm/types/index.mjs +0 -10
  114. package/lib/esm/types/index.mjs.map +0 -1
  115. package/lib/esm/types/v1/index.d.mts +0 -1
  116. package/lib/esm/types/v1/index.mjs +0 -1
  117. package/lib/esm/types/v1/index.mjs.map +0 -1
  118. package/lib/esm/utils/index.d.mts +0 -48
  119. package/lib/esm/utils/index.mjs +0 -20
  120. package/lib/esm/utils/index.mjs.map +0 -1
  121. package/lib/esm/v1/index.d.mts +0 -12
  122. package/lib/esm/v1/index.mjs +0 -13
  123. package/lib/esm/v1/index.mjs.map +0 -1
  124. package/lib/esm/x402HTTPResourceServer-BIfIK5HS.d.mts +0 -719
  125. package/src/index.js +0 -4
@@ -1,243 +0,0 @@
1
- import { c as PaymentRequired, a as PaymentRequirements, P as PaymentPayload, N as Network, d as SchemeNetworkClient, S as SettleResponse } from '../mechanisms-CzuGzYsS.js';
2
-
3
- /**
4
- * Client Hook Context Interfaces
5
- */
6
- interface PaymentCreationContext {
7
- paymentRequired: PaymentRequired;
8
- selectedRequirements: PaymentRequirements;
9
- }
10
- interface PaymentCreatedContext extends PaymentCreationContext {
11
- paymentPayload: PaymentPayload;
12
- }
13
- interface PaymentCreationFailureContext extends PaymentCreationContext {
14
- error: Error;
15
- }
16
- /**
17
- * Client Hook Type Definitions
18
- */
19
- type BeforePaymentCreationHook = (context: PaymentCreationContext) => Promise<void | {
20
- abort: true;
21
- reason: string;
22
- }>;
23
- type AfterPaymentCreationHook = (context: PaymentCreatedContext) => Promise<void>;
24
- type OnPaymentCreationFailureHook = (context: PaymentCreationFailureContext) => Promise<void | {
25
- recovered: true;
26
- payload: PaymentPayload;
27
- }>;
28
- type SelectPaymentRequirements = (x402Version: number, paymentRequirements: PaymentRequirements[]) => PaymentRequirements;
29
- /**
30
- * A policy function that filters or transforms payment requirements.
31
- * Policies are applied in order before the selector chooses the final option.
32
- *
33
- * @param x402Version - The x402 protocol version
34
- * @param paymentRequirements - Array of payment requirements to filter/transform
35
- * @returns Filtered array of payment requirements
36
- */
37
- type PaymentPolicy = (x402Version: number, paymentRequirements: PaymentRequirements[]) => PaymentRequirements[];
38
- /**
39
- * Configuration for registering a payment scheme with a specific network
40
- */
41
- interface SchemeRegistration {
42
- /**
43
- * The network identifier (e.g., 'eip155:8453', 'solana:mainnet')
44
- */
45
- network: Network;
46
- /**
47
- * The scheme client implementation for this network
48
- */
49
- client: SchemeNetworkClient;
50
- /**
51
- * The x402 protocol version to use for this scheme
52
- *
53
- * @default 2
54
- */
55
- x402Version?: number;
56
- }
57
- /**
58
- * Configuration options for the fetch wrapper
59
- */
60
- interface x402ClientConfig {
61
- /**
62
- * Array of scheme registrations defining which payment methods are supported
63
- */
64
- schemes: SchemeRegistration[];
65
- /**
66
- * Policies to apply to the client
67
- */
68
- policies?: PaymentPolicy[];
69
- /**
70
- * Custom payment requirements selector function
71
- * If not provided, uses the default selector (first available option)
72
- */
73
- paymentRequirementsSelector?: SelectPaymentRequirements;
74
- }
75
- /**
76
- * Core client for managing x402 payment schemes and creating payment payloads.
77
- *
78
- * Handles registration of payment schemes, policy-based filtering of payment requirements,
79
- * and creation of payment payloads based on server requirements.
80
- */
81
- declare class x402Client {
82
- private readonly paymentRequirementsSelector;
83
- private readonly registeredClientSchemes;
84
- private readonly policies;
85
- private beforePaymentCreationHooks;
86
- private afterPaymentCreationHooks;
87
- private onPaymentCreationFailureHooks;
88
- /**
89
- * Creates a new x402Client instance.
90
- *
91
- * @param paymentRequirementsSelector - Function to select payment requirements from available options
92
- */
93
- constructor(paymentRequirementsSelector?: SelectPaymentRequirements);
94
- /**
95
- * Creates a new x402Client instance from a configuration object.
96
- *
97
- * @param config - The client configuration including schemes, policies, and payment requirements selector
98
- * @returns A configured x402Client instance
99
- */
100
- static fromConfig(config: x402ClientConfig): x402Client;
101
- /**
102
- * Registers a scheme client for the current x402 version.
103
- *
104
- * @param network - The network to register the client for
105
- * @param client - The scheme network client to register
106
- * @returns The x402Client instance for chaining
107
- */
108
- register(network: Network, client: SchemeNetworkClient): x402Client;
109
- /**
110
- * Registers a scheme client for x402 version 1.
111
- *
112
- * @param network - The v1 network identifier (e.g., 'base-sepolia', 'solana-devnet')
113
- * @param client - The scheme network client to register
114
- * @returns The x402Client instance for chaining
115
- */
116
- registerV1(network: string, client: SchemeNetworkClient): x402Client;
117
- /**
118
- * Registers a policy to filter or transform payment requirements.
119
- *
120
- * Policies are applied in order after filtering by registered schemes
121
- * and before the selector chooses the final payment requirement.
122
- *
123
- * @param policy - Function to filter/transform payment requirements
124
- * @returns The x402Client instance for chaining
125
- *
126
- * @example
127
- * ```typescript
128
- * // Prefer cheaper options
129
- * client.registerPolicy((version, reqs) =>
130
- * reqs.filter(r => BigInt(r.value) < BigInt('1000000'))
131
- * );
132
- *
133
- * // Prefer specific networks
134
- * client.registerPolicy((version, reqs) =>
135
- * reqs.filter(r => r.network.startsWith('eip155:'))
136
- * );
137
- * ```
138
- */
139
- registerPolicy(policy: PaymentPolicy): x402Client;
140
- /**
141
- * Register a hook to execute before payment payload creation.
142
- * Can abort creation by returning { abort: true, reason: string }
143
- *
144
- * @param hook - The hook function to register
145
- * @returns The x402Client instance for chaining
146
- */
147
- onBeforePaymentCreation(hook: BeforePaymentCreationHook): x402Client;
148
- /**
149
- * Register a hook to execute after successful payment payload creation.
150
- *
151
- * @param hook - The hook function to register
152
- * @returns The x402Client instance for chaining
153
- */
154
- onAfterPaymentCreation(hook: AfterPaymentCreationHook): x402Client;
155
- /**
156
- * Register a hook to execute when payment payload creation fails.
157
- * Can recover from failure by returning { recovered: true, payload: PaymentPayload }
158
- *
159
- * @param hook - The hook function to register
160
- * @returns The x402Client instance for chaining
161
- */
162
- onPaymentCreationFailure(hook: OnPaymentCreationFailureHook): x402Client;
163
- /**
164
- * Creates a payment payload based on a PaymentRequired response.
165
- *
166
- * Automatically extracts x402Version, resource, and extensions from the PaymentRequired
167
- * response and constructs a complete PaymentPayload with the accepted requirements.
168
- *
169
- * @param paymentRequired - The PaymentRequired response from the server
170
- * @returns Promise resolving to the complete payment payload
171
- */
172
- createPaymentPayload(paymentRequired: PaymentRequired): Promise<PaymentPayload>;
173
- /**
174
- * Selects appropriate payment requirements based on registered clients and policies.
175
- *
176
- * Selection process:
177
- * 1. Filter by registered schemes (network + scheme support)
178
- * 2. Apply all registered policies in order
179
- * 3. Use selector to choose final requirement
180
- *
181
- * @param x402Version - The x402 protocol version
182
- * @param paymentRequirements - Array of available payment requirements
183
- * @returns The selected payment requirements
184
- */
185
- private selectPaymentRequirements;
186
- /**
187
- * Internal method to register a scheme client.
188
- *
189
- * @param x402Version - The x402 protocol version
190
- * @param network - The network to register the client for
191
- * @param client - The scheme network client to register
192
- * @returns The x402Client instance for chaining
193
- */
194
- private _registerScheme;
195
- }
196
-
197
- /**
198
- * HTTP-specific client for handling x402 payment protocol over HTTP.
199
- *
200
- * Wraps a x402Client to provide HTTP-specific encoding/decoding functionality
201
- * for payment headers and responses while maintaining the builder pattern.
202
- */
203
- declare class x402HTTPClient {
204
- private readonly client;
205
- /**
206
- * Creates a new x402HTTPClient instance.
207
- *
208
- * @param client - The underlying x402Client for payment logic
209
- */
210
- constructor(client: x402Client);
211
- /**
212
- * Encodes a payment payload into appropriate HTTP headers based on version.
213
- *
214
- * @param paymentPayload - The payment payload to encode
215
- * @returns HTTP headers containing the encoded payment signature
216
- */
217
- encodePaymentSignatureHeader(paymentPayload: PaymentPayload): Record<string, string>;
218
- /**
219
- * Extracts payment required information from HTTP response.
220
- *
221
- * @param getHeader - Function to retrieve header value by name (case-insensitive)
222
- * @param body - Optional response body for v1 compatibility
223
- * @returns The payment required object
224
- */
225
- getPaymentRequiredResponse(getHeader: (name: string) => string | null | undefined, body?: unknown): PaymentRequired;
226
- /**
227
- * Extracts payment settlement response from HTTP headers.
228
- *
229
- * @param getHeader - Function to retrieve header value by name (case-insensitive)
230
- * @returns The settlement response object
231
- */
232
- getPaymentSettleResponse(getHeader: (name: string) => string | null | undefined): SettleResponse;
233
- /**
234
- * Creates a payment payload for the given payment requirements.
235
- * Delegates to the underlying x402Client.
236
- *
237
- * @param paymentRequired - The payment required response from the server
238
- * @returns Promise resolving to the payment payload
239
- */
240
- createPaymentPayload(paymentRequired: PaymentRequired): Promise<PaymentPayload>;
241
- }
242
-
243
- export { type AfterPaymentCreationHook, type BeforePaymentCreationHook, type OnPaymentCreationFailureHook, type PaymentCreatedContext, type PaymentCreationContext, type PaymentCreationFailureContext, type PaymentPolicy, type SchemeRegistration, type SelectPaymentRequirements, x402Client, type x402ClientConfig, x402HTTPClient };
@@ -1,413 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/client/index.ts
21
- var client_exports = {};
22
- __export(client_exports, {
23
- x402Client: () => x402Client,
24
- x402HTTPClient: () => x402HTTPClient
25
- });
26
- module.exports = __toCommonJS(client_exports);
27
-
28
- // src/index.ts
29
- var x402Version = 2;
30
-
31
- // src/utils/index.ts
32
- var findSchemesByNetwork = (map, network) => {
33
- let implementationsByScheme = map.get(network);
34
- if (!implementationsByScheme) {
35
- for (const [registeredNetworkPattern, implementations] of map.entries()) {
36
- const pattern = registeredNetworkPattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\*/g, ".*");
37
- const regex = new RegExp(`^${pattern}$`);
38
- if (regex.test(network)) {
39
- implementationsByScheme = implementations;
40
- break;
41
- }
42
- }
43
- }
44
- return implementationsByScheme;
45
- };
46
- var findByNetworkAndScheme = (map, scheme, network) => {
47
- return findSchemesByNetwork(map, network)?.get(scheme);
48
- };
49
- var Base64EncodedRegex = /^[A-Za-z0-9+/]*={0,2}$/;
50
- function safeBase64Encode(data) {
51
- if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") {
52
- const bytes = new TextEncoder().encode(data);
53
- const binaryString = Array.from(bytes, (byte) => String.fromCharCode(byte)).join("");
54
- return globalThis.btoa(binaryString);
55
- }
56
- return Buffer.from(data, "utf8").toString("base64");
57
- }
58
- function safeBase64Decode(data) {
59
- if (typeof globalThis !== "undefined" && typeof globalThis.atob === "function") {
60
- const binaryString = globalThis.atob(data);
61
- const bytes = new Uint8Array(binaryString.length);
62
- for (let i = 0; i < binaryString.length; i++) {
63
- bytes[i] = binaryString.charCodeAt(i);
64
- }
65
- const decoder = new TextDecoder("utf-8");
66
- return decoder.decode(bytes);
67
- }
68
- return Buffer.from(data, "base64").toString("utf-8");
69
- }
70
-
71
- // src/client/x402Client.ts
72
- var x402Client = class _x402Client {
73
- /**
74
- * Creates a new x402Client instance.
75
- *
76
- * @param paymentRequirementsSelector - Function to select payment requirements from available options
77
- */
78
- constructor(paymentRequirementsSelector) {
79
- this.registeredClientSchemes = /* @__PURE__ */ new Map();
80
- this.policies = [];
81
- this.beforePaymentCreationHooks = [];
82
- this.afterPaymentCreationHooks = [];
83
- this.onPaymentCreationFailureHooks = [];
84
- this.paymentRequirementsSelector = paymentRequirementsSelector || ((x402Version2, accepts) => accepts[0]);
85
- }
86
- /**
87
- * Creates a new x402Client instance from a configuration object.
88
- *
89
- * @param config - The client configuration including schemes, policies, and payment requirements selector
90
- * @returns A configured x402Client instance
91
- */
92
- static fromConfig(config) {
93
- const client = new _x402Client(config.paymentRequirementsSelector);
94
- config.schemes.forEach((scheme) => {
95
- if (scheme.x402Version === 1) {
96
- client.registerV1(scheme.network, scheme.client);
97
- } else {
98
- client.register(scheme.network, scheme.client);
99
- }
100
- });
101
- config.policies?.forEach((policy) => {
102
- client.registerPolicy(policy);
103
- });
104
- return client;
105
- }
106
- /**
107
- * Registers a scheme client for the current x402 version.
108
- *
109
- * @param network - The network to register the client for
110
- * @param client - The scheme network client to register
111
- * @returns The x402Client instance for chaining
112
- */
113
- register(network, client) {
114
- return this._registerScheme(x402Version, network, client);
115
- }
116
- /**
117
- * Registers a scheme client for x402 version 1.
118
- *
119
- * @param network - The v1 network identifier (e.g., 'base-sepolia', 'solana-devnet')
120
- * @param client - The scheme network client to register
121
- * @returns The x402Client instance for chaining
122
- */
123
- registerV1(network, client) {
124
- return this._registerScheme(1, network, client);
125
- }
126
- /**
127
- * Registers a policy to filter or transform payment requirements.
128
- *
129
- * Policies are applied in order after filtering by registered schemes
130
- * and before the selector chooses the final payment requirement.
131
- *
132
- * @param policy - Function to filter/transform payment requirements
133
- * @returns The x402Client instance for chaining
134
- *
135
- * @example
136
- * ```typescript
137
- * // Prefer cheaper options
138
- * client.registerPolicy((version, reqs) =>
139
- * reqs.filter(r => BigInt(r.value) < BigInt('1000000'))
140
- * );
141
- *
142
- * // Prefer specific networks
143
- * client.registerPolicy((version, reqs) =>
144
- * reqs.filter(r => r.network.startsWith('eip155:'))
145
- * );
146
- * ```
147
- */
148
- registerPolicy(policy) {
149
- this.policies.push(policy);
150
- return this;
151
- }
152
- /**
153
- * Register a hook to execute before payment payload creation.
154
- * Can abort creation by returning { abort: true, reason: string }
155
- *
156
- * @param hook - The hook function to register
157
- * @returns The x402Client instance for chaining
158
- */
159
- onBeforePaymentCreation(hook) {
160
- this.beforePaymentCreationHooks.push(hook);
161
- return this;
162
- }
163
- /**
164
- * Register a hook to execute after successful payment payload creation.
165
- *
166
- * @param hook - The hook function to register
167
- * @returns The x402Client instance for chaining
168
- */
169
- onAfterPaymentCreation(hook) {
170
- this.afterPaymentCreationHooks.push(hook);
171
- return this;
172
- }
173
- /**
174
- * Register a hook to execute when payment payload creation fails.
175
- * Can recover from failure by returning { recovered: true, payload: PaymentPayload }
176
- *
177
- * @param hook - The hook function to register
178
- * @returns The x402Client instance for chaining
179
- */
180
- onPaymentCreationFailure(hook) {
181
- this.onPaymentCreationFailureHooks.push(hook);
182
- return this;
183
- }
184
- /**
185
- * Creates a payment payload based on a PaymentRequired response.
186
- *
187
- * Automatically extracts x402Version, resource, and extensions from the PaymentRequired
188
- * response and constructs a complete PaymentPayload with the accepted requirements.
189
- *
190
- * @param paymentRequired - The PaymentRequired response from the server
191
- * @returns Promise resolving to the complete payment payload
192
- */
193
- async createPaymentPayload(paymentRequired) {
194
- const clientSchemesByNetwork = this.registeredClientSchemes.get(paymentRequired.x402Version);
195
- if (!clientSchemesByNetwork) {
196
- throw new Error(`No client registered for x402 version: ${paymentRequired.x402Version}`);
197
- }
198
- const requirements = this.selectPaymentRequirements(paymentRequired.x402Version, paymentRequired.accepts);
199
- const context = {
200
- paymentRequired,
201
- selectedRequirements: requirements
202
- };
203
- for (const hook of this.beforePaymentCreationHooks) {
204
- const result = await hook(context);
205
- if (result && "abort" in result && result.abort) {
206
- throw new Error(`Payment creation aborted: ${result.reason}`);
207
- }
208
- }
209
- try {
210
- const schemeNetworkClient = findByNetworkAndScheme(clientSchemesByNetwork, requirements.scheme, requirements.network);
211
- if (!schemeNetworkClient) {
212
- throw new Error(`No client registered for scheme: ${requirements.scheme} and network: ${requirements.network}`);
213
- }
214
- const partialPayload = await schemeNetworkClient.createPaymentPayload(paymentRequired.x402Version, requirements);
215
- let paymentPayload;
216
- if (partialPayload.x402Version == 1) {
217
- paymentPayload = partialPayload;
218
- } else {
219
- paymentPayload = {
220
- ...partialPayload,
221
- extensions: paymentRequired.extensions,
222
- resource: paymentRequired.resource,
223
- accepted: requirements
224
- };
225
- }
226
- const createdContext = {
227
- ...context,
228
- paymentPayload
229
- };
230
- for (const hook of this.afterPaymentCreationHooks) {
231
- await hook(createdContext);
232
- }
233
- return paymentPayload;
234
- } catch (error) {
235
- const failureContext = {
236
- ...context,
237
- error
238
- };
239
- for (const hook of this.onPaymentCreationFailureHooks) {
240
- const result = await hook(failureContext);
241
- if (result && "recovered" in result && result.recovered) {
242
- return result.payload;
243
- }
244
- }
245
- throw error;
246
- }
247
- }
248
- /**
249
- * Selects appropriate payment requirements based on registered clients and policies.
250
- *
251
- * Selection process:
252
- * 1. Filter by registered schemes (network + scheme support)
253
- * 2. Apply all registered policies in order
254
- * 3. Use selector to choose final requirement
255
- *
256
- * @param x402Version - The x402 protocol version
257
- * @param paymentRequirements - Array of available payment requirements
258
- * @returns The selected payment requirements
259
- */
260
- selectPaymentRequirements(x402Version2, paymentRequirements) {
261
- const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version2);
262
- if (!clientSchemesByNetwork) {
263
- throw new Error(`No client registered for x402 version: ${x402Version2}`);
264
- }
265
- const supportedPaymentRequirements = paymentRequirements.filter((requirement) => {
266
- let clientSchemes = findSchemesByNetwork(clientSchemesByNetwork, requirement.network);
267
- if (!clientSchemes) {
268
- return false;
269
- }
270
- return clientSchemes.has(requirement.scheme);
271
- });
272
- if (supportedPaymentRequirements.length === 0) {
273
- throw new Error(`No network/scheme registered for x402 version: ${x402Version2} which comply with the payment requirements. ${JSON.stringify({
274
- x402Version: x402Version2,
275
- paymentRequirements,
276
- x402Versions: Array.from(this.registeredClientSchemes.keys()),
277
- networks: Array.from(clientSchemesByNetwork.keys()),
278
- schemes: Array.from(clientSchemesByNetwork.values()).map((schemes) => Array.from(schemes.keys())).flat()
279
- })}`);
280
- }
281
- let filteredRequirements = supportedPaymentRequirements;
282
- for (const policy of this.policies) {
283
- filteredRequirements = policy(x402Version2, filteredRequirements);
284
- if (filteredRequirements.length === 0) {
285
- throw new Error(`All payment requirements were filtered out by policies for x402 version: ${x402Version2}`);
286
- }
287
- }
288
- return this.paymentRequirementsSelector(x402Version2, filteredRequirements);
289
- }
290
- /**
291
- * Internal method to register a scheme client.
292
- *
293
- * @param x402Version - The x402 protocol version
294
- * @param network - The network to register the client for
295
- * @param client - The scheme network client to register
296
- * @returns The x402Client instance for chaining
297
- */
298
- _registerScheme(x402Version2, network, client) {
299
- if (!this.registeredClientSchemes.has(x402Version2)) {
300
- this.registeredClientSchemes.set(x402Version2, /* @__PURE__ */ new Map());
301
- }
302
- const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version2);
303
- if (!clientSchemesByNetwork.has(network)) {
304
- clientSchemesByNetwork.set(network, /* @__PURE__ */ new Map());
305
- }
306
- const clientByScheme = clientSchemesByNetwork.get(network);
307
- if (!clientByScheme.has(client.scheme)) {
308
- clientByScheme.set(client.scheme, client);
309
- }
310
- return this;
311
- }
312
- };
313
-
314
- // src/http/index.ts
315
- function encodePaymentSignatureHeader(paymentPayload) {
316
- return safeBase64Encode(JSON.stringify(paymentPayload));
317
- }
318
- function decodePaymentRequiredHeader(paymentRequiredHeader) {
319
- if (!Base64EncodedRegex.test(paymentRequiredHeader)) {
320
- throw new Error("Invalid payment required header");
321
- }
322
- return JSON.parse(safeBase64Decode(paymentRequiredHeader));
323
- }
324
- function decodePaymentResponseHeader(paymentResponseHeader) {
325
- if (!Base64EncodedRegex.test(paymentResponseHeader)) {
326
- throw new Error("Invalid payment response header");
327
- }
328
- return JSON.parse(safeBase64Decode(paymentResponseHeader));
329
- }
330
-
331
- // src/http/x402HTTPClient.ts
332
- var x402HTTPClient = class {
333
- /**
334
- * Creates a new x402HTTPClient instance.
335
- *
336
- * @param client - The underlying x402Client for payment logic
337
- */
338
- constructor(client) {
339
- this.client = client;
340
- }
341
- /**
342
- * Encodes a payment payload into appropriate HTTP headers based on version.
343
- *
344
- * @param paymentPayload - The payment payload to encode
345
- * @returns HTTP headers containing the encoded payment signature
346
- */
347
- encodePaymentSignatureHeader(paymentPayload) {
348
- switch (paymentPayload.x402Version) {
349
- case 2:
350
- return {
351
- "PAYMENT-SIGNATURE": encodePaymentSignatureHeader(paymentPayload)
352
- };
353
- case 1:
354
- return {
355
- "X-PAYMENT": encodePaymentSignatureHeader(paymentPayload)
356
- };
357
- default:
358
- throw new Error(
359
- `Unsupported x402 version: ${paymentPayload.x402Version}`
360
- );
361
- }
362
- }
363
- /**
364
- * Extracts payment required information from HTTP response.
365
- *
366
- * @param getHeader - Function to retrieve header value by name (case-insensitive)
367
- * @param body - Optional response body for v1 compatibility
368
- * @returns The payment required object
369
- */
370
- getPaymentRequiredResponse(getHeader, body) {
371
- const paymentRequired = getHeader("PAYMENT-REQUIRED");
372
- if (paymentRequired) {
373
- return decodePaymentRequiredHeader(paymentRequired);
374
- }
375
- if (body && body instanceof Object && "x402Version" in body && body.x402Version === 1) {
376
- return body;
377
- }
378
- throw new Error("Invalid payment required response");
379
- }
380
- /**
381
- * Extracts payment settlement response from HTTP headers.
382
- *
383
- * @param getHeader - Function to retrieve header value by name (case-insensitive)
384
- * @returns The settlement response object
385
- */
386
- getPaymentSettleResponse(getHeader) {
387
- const paymentResponse = getHeader("PAYMENT-RESPONSE");
388
- if (paymentResponse) {
389
- return decodePaymentResponseHeader(paymentResponse);
390
- }
391
- const xPaymentResponse = getHeader("X-PAYMENT-RESPONSE");
392
- if (xPaymentResponse) {
393
- return decodePaymentResponseHeader(xPaymentResponse);
394
- }
395
- throw new Error("Payment response header not found");
396
- }
397
- /**
398
- * Creates a payment payload for the given payment requirements.
399
- * Delegates to the underlying x402Client.
400
- *
401
- * @param paymentRequired - The payment required response from the server
402
- * @returns Promise resolving to the payment payload
403
- */
404
- async createPaymentPayload(paymentRequired) {
405
- return this.client.createPaymentPayload(paymentRequired);
406
- }
407
- };
408
- // Annotate the CommonJS export names for ESM import in node:
409
- 0 && (module.exports = {
410
- x402Client,
411
- x402HTTPClient
412
- });
413
- //# sourceMappingURL=index.js.map