x402-express-mantle 1.0.0 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -1
- package/lib/cjs/index.d.ts +119 -81
- package/lib/cjs/index.js +3 -3
- package/lib/esm/index.d.mts +5 -5
- package/lib/esm/index.mjs +3 -3
- package/package.json +4 -3
- package/lib/cjs/client/index.d.ts +0 -243
- package/lib/cjs/client/index.js +0 -413
- package/lib/cjs/client/index.js.map +0 -1
- package/lib/cjs/exact/client/index.d.ts +0 -37
- package/lib/cjs/exact/client/index.js +0 -281
- package/lib/cjs/exact/client/index.js.map +0 -1
- package/lib/cjs/exact/facilitator/index.d.ts +0 -110
- package/lib/cjs/exact/facilitator/index.js +0 -714
- package/lib/cjs/exact/facilitator/index.js.map +0 -1
- package/lib/cjs/exact/server/index.d.ts +0 -87
- package/lib/cjs/exact/server/index.js +0 -209
- package/lib/cjs/exact/server/index.js.map +0 -1
- package/lib/cjs/exact/v1/client/index.d.ts +0 -33
- package/lib/cjs/exact/v1/client/index.js +0 -169
- package/lib/cjs/exact/v1/client/index.js.map +0 -1
- package/lib/cjs/exact/v1/facilitator/index.d.ts +0 -71
- package/lib/cjs/exact/v1/facilitator/index.js +0 -384
- package/lib/cjs/exact/v1/facilitator/index.js.map +0 -1
- package/lib/cjs/facilitator/index.d.ts +0 -192
- package/lib/cjs/facilitator/index.js +0 -398
- package/lib/cjs/facilitator/index.js.map +0 -1
- package/lib/cjs/http/index.d.ts +0 -52
- package/lib/cjs/http/index.js +0 -827
- package/lib/cjs/http/index.js.map +0 -1
- package/lib/cjs/mechanisms-CzuGzYsS.d.ts +0 -270
- package/lib/cjs/scheme-MoBRXFM8.d.ts +0 -29
- package/lib/cjs/server/index.d.ts +0 -2
- package/lib/cjs/server/index.js +0 -1305
- package/lib/cjs/server/index.js.map +0 -1
- package/lib/cjs/signer-5OVDxViv.d.ts +0 -79
- package/lib/cjs/signer-BMkbhFYE.d.ts +0 -123
- package/lib/cjs/types/index.d.ts +0 -1
- package/lib/cjs/types/index.js +0 -66
- package/lib/cjs/types/index.js.map +0 -1
- package/lib/cjs/types/v1/index.d.ts +0 -1
- package/lib/cjs/types/v1/index.js +0 -19
- package/lib/cjs/types/v1/index.js.map +0 -1
- package/lib/cjs/utils/index.d.ts +0 -48
- package/lib/cjs/utils/index.js +0 -116
- package/lib/cjs/utils/index.js.map +0 -1
- package/lib/cjs/v1/index.d.ts +0 -12
- package/lib/cjs/v1/index.js +0 -180
- package/lib/cjs/v1/index.js.map +0 -1
- package/lib/cjs/x402HTTPResourceServer-D1YtlH_r.d.ts +0 -719
- package/lib/esm/chunk-3CEIVWNN.mjs +0 -339
- package/lib/esm/chunk-3CEIVWNN.mjs.map +0 -1
- package/lib/esm/chunk-BJTO5JO5.mjs +0 -11
- package/lib/esm/chunk-BJTO5JO5.mjs.map +0 -1
- package/lib/esm/chunk-EEA7DKZI.mjs +0 -111
- package/lib/esm/chunk-EEA7DKZI.mjs.map +0 -1
- package/lib/esm/chunk-FOUXRQAV.mjs +0 -88
- package/lib/esm/chunk-FOUXRQAV.mjs.map +0 -1
- package/lib/esm/chunk-IKSTWKEM.mjs +0 -157
- package/lib/esm/chunk-IKSTWKEM.mjs.map +0 -1
- package/lib/esm/chunk-JYZWCLMP.mjs +0 -305
- package/lib/esm/chunk-JYZWCLMP.mjs.map +0 -1
- package/lib/esm/chunk-PNSAJQCF.mjs +0 -108
- package/lib/esm/chunk-PNSAJQCF.mjs.map +0 -1
- package/lib/esm/chunk-PSA4YVU2.mjs +0 -92
- package/lib/esm/chunk-PSA4YVU2.mjs.map +0 -1
- package/lib/esm/chunk-QLXM7BIB.mjs +0 -23
- package/lib/esm/chunk-QLXM7BIB.mjs.map +0 -1
- package/lib/esm/chunk-TDLQZ6MP.mjs +0 -86
- package/lib/esm/chunk-TDLQZ6MP.mjs.map +0 -1
- package/lib/esm/chunk-VE37GDG2.mjs +0 -7
- package/lib/esm/chunk-VE37GDG2.mjs.map +0 -1
- package/lib/esm/chunk-WWACQNRQ.mjs +0 -7
- package/lib/esm/chunk-WWACQNRQ.mjs.map +0 -1
- package/lib/esm/chunk-X4W4S5RB.mjs +0 -39
- package/lib/esm/chunk-X4W4S5RB.mjs.map +0 -1
- package/lib/esm/chunk-Z4QX3O5V.mjs +0 -748
- package/lib/esm/chunk-Z4QX3O5V.mjs.map +0 -1
- package/lib/esm/chunk-ZYXTTU74.mjs +0 -88
- package/lib/esm/chunk-ZYXTTU74.mjs.map +0 -1
- package/lib/esm/client/index.d.mts +0 -243
- package/lib/esm/client/index.mjs +0 -260
- package/lib/esm/client/index.mjs.map +0 -1
- package/lib/esm/exact/client/index.d.mts +0 -37
- package/lib/esm/exact/client/index.mjs +0 -36
- package/lib/esm/exact/client/index.mjs.map +0 -1
- package/lib/esm/exact/facilitator/index.d.mts +0 -110
- package/lib/esm/exact/facilitator/index.mjs +0 -350
- package/lib/esm/exact/facilitator/index.mjs.map +0 -1
- package/lib/esm/exact/server/index.d.mts +0 -87
- package/lib/esm/exact/server/index.mjs +0 -129
- package/lib/esm/exact/server/index.mjs.map +0 -1
- package/lib/esm/exact/v1/client/index.d.mts +0 -33
- package/lib/esm/exact/v1/client/index.mjs +0 -8
- package/lib/esm/exact/v1/client/index.mjs.map +0 -1
- package/lib/esm/exact/v1/facilitator/index.d.mts +0 -71
- package/lib/esm/exact/v1/facilitator/index.mjs +0 -8
- package/lib/esm/exact/v1/facilitator/index.mjs.map +0 -1
- package/lib/esm/facilitator/index.d.mts +0 -192
- package/lib/esm/facilitator/index.mjs +0 -373
- package/lib/esm/facilitator/index.mjs.map +0 -1
- package/lib/esm/http/index.d.mts +0 -52
- package/lib/esm/http/index.mjs +0 -29
- package/lib/esm/http/index.mjs.map +0 -1
- package/lib/esm/mechanisms-CzuGzYsS.d.mts +0 -270
- package/lib/esm/scheme-fjF-9LhT.d.mts +0 -29
- package/lib/esm/server/index.d.mts +0 -2
- package/lib/esm/server/index.mjs +0 -563
- package/lib/esm/server/index.mjs.map +0 -1
- package/lib/esm/signer-5OVDxViv.d.mts +0 -79
- package/lib/esm/signer-BMkbhFYE.d.mts +0 -123
- package/lib/esm/types/index.d.mts +0 -1
- package/lib/esm/types/index.mjs +0 -10
- package/lib/esm/types/index.mjs.map +0 -1
- package/lib/esm/types/v1/index.d.mts +0 -1
- package/lib/esm/types/v1/index.mjs +0 -1
- package/lib/esm/types/v1/index.mjs.map +0 -1
- package/lib/esm/utils/index.d.mts +0 -48
- package/lib/esm/utils/index.mjs +0 -20
- package/lib/esm/utils/index.mjs.map +0 -1
- package/lib/esm/v1/index.d.mts +0 -12
- package/lib/esm/v1/index.mjs +0 -13
- package/lib/esm/v1/index.mjs.map +0 -1
- package/lib/esm/x402HTTPResourceServer-BIfIK5HS.d.mts +0 -719
- package/src/index.js +0 -4
package/lib/cjs/client/index.js
DELETED
|
@@ -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
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/client/index.ts","../../../src/index.ts","../../../src/utils/index.ts","../../../src/client/x402Client.ts","../../../src/http/index.ts","../../../src/http/x402HTTPClient.ts"],"sourcesContent":["export * from \"./x402Client\";\nexport * from \"../http/x402HTTPClient\";","export const x402Version = 2;\n","import { Network } from \"../types\";\n\n/**\n * Scheme data structure for facilitator storage\n */\nexport interface SchemeData<T> {\n facilitator: T;\n networks: Set<Network>;\n pattern: Network;\n}\n\nexport const findSchemesByNetwork = <T>(\n map: Map<string, Map<string, T>>,\n network: Network,\n): Map<string, T> | undefined => {\n // Direct match first\n let implementationsByScheme = map.get(network);\n\n if (!implementationsByScheme) {\n // Try pattern matching for registered network patterns\n for (const [registeredNetworkPattern, implementations] of map.entries()) {\n // Convert the registered network pattern to a regex\n // e.g., \"eip155:*\" becomes /^eip155:.*$/\n const pattern = registeredNetworkPattern\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\") // Escape special regex chars except *\n .replace(/\\\\\\*/g, \".*\"); // Replace escaped * with .*\n\n const regex = new RegExp(`^${pattern}$`);\n\n if (regex.test(network)) {\n implementationsByScheme = implementations;\n break;\n }\n }\n }\n\n return implementationsByScheme;\n};\n\nexport const findByNetworkAndScheme = <T>(\n map: Map<string, Map<string, T>>,\n scheme: string,\n network: Network,\n): T | undefined => {\n return findSchemesByNetwork(map, network)?.get(scheme);\n};\n\n/**\n * Finds a facilitator by scheme and network using pattern matching.\n * Works with new SchemeData storage structure.\n *\n * @param schemeMap - Map of scheme names to SchemeData\n * @param scheme - The scheme to find\n * @param network - The network to match against\n * @returns The facilitator if found, undefined otherwise\n */\nexport const findFacilitatorBySchemeAndNetwork = <T>(\n schemeMap: Map<string, SchemeData<T>>,\n scheme: string,\n network: Network,\n): T | undefined => {\n const schemeData = schemeMap.get(scheme);\n if (!schemeData) return undefined;\n\n // Check if network is in the stored networks set\n if (schemeData.networks.has(network)) {\n return schemeData.facilitator;\n }\n\n // Try pattern matching\n const patternRegex = new RegExp(\"^\" + schemeData.pattern.replace(\"*\", \".*\") + \"$\");\n if (patternRegex.test(network)) {\n return schemeData.facilitator;\n }\n\n return undefined;\n};\n\nexport const Base64EncodedRegex = /^[A-Za-z0-9+/]*={0,2}$/;\n\n/**\n * Encodes a string to base64 format\n *\n * @param data - The string to be encoded to base64\n * @returns The base64 encoded string\n */\nexport function safeBase64Encode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.btoa === \"function\") {\n const bytes = new TextEncoder().encode(data);\n const binaryString = Array.from(bytes, byte => String.fromCharCode(byte)).join(\"\");\n return globalThis.btoa(binaryString);\n }\n return Buffer.from(data, \"utf8\").toString(\"base64\");\n}\n\n/**\n * Decodes a base64 string back to its original format\n *\n * @param data - The base64 encoded string to be decoded\n * @returns The decoded string in UTF-8 format\n */\nexport function safeBase64Decode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.atob === \"function\") {\n const binaryString = globalThis.atob(data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n const decoder = new TextDecoder(\"utf-8\");\n return decoder.decode(bytes);\n }\n return Buffer.from(data, \"base64\").toString(\"utf-8\");\n}\n\n/**\n * Deep equality comparison for payment requirements\n * Uses a normalized JSON.stringify for consistent comparison\n *\n * @param obj1 - First object to compare\n * @param obj2 - Second object to compare\n * @returns True if objects are deeply equal\n */\nexport function deepEqual(obj1: unknown, obj2: unknown): boolean {\n // Normalize and stringify both objects for comparison\n // This handles nested objects, arrays, and different property orders\n const normalize = (obj: unknown): string => {\n // Handle primitives and null/undefined\n if (obj === null || obj === undefined) return JSON.stringify(obj);\n if (typeof obj !== \"object\") return JSON.stringify(obj);\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return JSON.stringify(\n obj.map(item =>\n typeof item === \"object\" && item !== null ? JSON.parse(normalize(item)) : item,\n ),\n );\n }\n\n // Handle objects - sort keys and recursively normalize values\n const sorted: Record<string, unknown> = {};\n Object.keys(obj as Record<string, unknown>)\n .sort()\n .forEach(key => {\n const value = (obj as Record<string, unknown>)[key];\n sorted[key] =\n typeof value === \"object\" && value !== null ? JSON.parse(normalize(value)) : value;\n });\n return JSON.stringify(sorted);\n };\n\n try {\n return normalize(obj1) === normalize(obj2);\n } catch {\n // Fallback to simple comparison if normalization fails\n return JSON.stringify(obj1) === JSON.stringify(obj2);\n }\n}\n","import { x402Version } from \"..\";\nimport { SchemeNetworkClient } from \"../types/mechanisms\";\nimport { PaymentPayload, PaymentRequirements } from \"../types/payments\";\nimport { Network, PaymentRequired } from \"../types\";\nimport { findByNetworkAndScheme, findSchemesByNetwork } from \"../utils\";\n\n/**\n * Client Hook Context Interfaces\n */\n\nexport interface PaymentCreationContext {\n paymentRequired: PaymentRequired;\n selectedRequirements: PaymentRequirements;\n}\n\nexport interface PaymentCreatedContext extends PaymentCreationContext {\n paymentPayload: PaymentPayload;\n}\n\nexport interface PaymentCreationFailureContext extends PaymentCreationContext {\n error: Error;\n}\n\n/**\n * Client Hook Type Definitions\n */\n\nexport type BeforePaymentCreationHook = (\n context: PaymentCreationContext,\n) => Promise<void | { abort: true; reason: string }>;\n\nexport type AfterPaymentCreationHook = (context: PaymentCreatedContext) => Promise<void>;\n\nexport type OnPaymentCreationFailureHook = (\n context: PaymentCreationFailureContext,\n) => Promise<void | { recovered: true; payload: PaymentPayload }>;\n\nexport type SelectPaymentRequirements = (x402Version: number, paymentRequirements: PaymentRequirements[]) => PaymentRequirements;\n\n/**\n * A policy function that filters or transforms payment requirements.\n * Policies are applied in order before the selector chooses the final option.\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - Array of payment requirements to filter/transform\n * @returns Filtered array of payment requirements\n */\nexport type PaymentPolicy = (x402Version: number, paymentRequirements: PaymentRequirements[]) => PaymentRequirements[];\n\n\n/**\n * Configuration for registering a payment scheme with a specific network\n */\nexport interface SchemeRegistration {\n /**\n * The network identifier (e.g., 'eip155:8453', 'solana:mainnet')\n */\n network: Network;\n\n /**\n * The scheme client implementation for this network\n */\n client: SchemeNetworkClient;\n\n /**\n * The x402 protocol version to use for this scheme\n *\n * @default 2\n */\n x402Version?: number;\n}\n\n/**\n * Configuration options for the fetch wrapper\n */\nexport interface x402ClientConfig {\n /**\n * Array of scheme registrations defining which payment methods are supported\n */\n schemes: SchemeRegistration[];\n\n /**\n * Policies to apply to the client\n */\n policies?: PaymentPolicy[];\n\n /**\n * Custom payment requirements selector function\n * If not provided, uses the default selector (first available option)\n */\n paymentRequirementsSelector?: SelectPaymentRequirements;\n}\n\n/**\n * Core client for managing x402 payment schemes and creating payment payloads.\n *\n * Handles registration of payment schemes, policy-based filtering of payment requirements,\n * and creation of payment payloads based on server requirements.\n */\nexport class x402Client {\n private readonly paymentRequirementsSelector: SelectPaymentRequirements;\n private readonly registeredClientSchemes: Map<number, Map<string, Map<string, SchemeNetworkClient>>> = new Map();\n private readonly policies: PaymentPolicy[] = [];\n\n private beforePaymentCreationHooks: BeforePaymentCreationHook[] = [];\n private afterPaymentCreationHooks: AfterPaymentCreationHook[] = [];\n private onPaymentCreationFailureHooks: OnPaymentCreationFailureHook[] = [];\n\n /**\n * Creates a new x402Client instance.\n *\n * @param paymentRequirementsSelector - Function to select payment requirements from available options\n */\n constructor(paymentRequirementsSelector?: SelectPaymentRequirements) {\n this.paymentRequirementsSelector = paymentRequirementsSelector || ((x402Version, accepts) => accepts[0]);\n }\n\n /**\n * Creates a new x402Client instance from a configuration object.\n *\n * @param config - The client configuration including schemes, policies, and payment requirements selector\n * @returns A configured x402Client instance\n */\n static fromConfig(config: x402ClientConfig): x402Client {\n const client = new x402Client(config.paymentRequirementsSelector);\n config.schemes.forEach(scheme => {\n if (scheme.x402Version === 1) {\n client.registerV1(scheme.network, scheme.client);\n } else {\n client.register(scheme.network, scheme.client);\n }\n });\n config.policies?.forEach(policy => {\n client.registerPolicy(policy);\n });\n return client;\n }\n\n /**\n * Registers a scheme client for the current x402 version.\n *\n * @param network - The network to register the client for\n * @param client - The scheme network client to register\n * @returns The x402Client instance for chaining\n */\n register(network: Network, client: SchemeNetworkClient): x402Client {\n return this._registerScheme(x402Version, network, client);\n }\n\n /**\n * Registers a scheme client for x402 version 1.\n *\n * @param network - The v1 network identifier (e.g., 'base-sepolia', 'solana-devnet')\n * @param client - The scheme network client to register\n * @returns The x402Client instance for chaining\n */\n registerV1(network: string, client: SchemeNetworkClient): x402Client {\n return this._registerScheme(1, network as Network, client);\n }\n\n /**\n * Registers a policy to filter or transform payment requirements.\n *\n * Policies are applied in order after filtering by registered schemes\n * and before the selector chooses the final payment requirement.\n *\n * @param policy - Function to filter/transform payment requirements\n * @returns The x402Client instance for chaining\n *\n * @example\n * ```typescript\n * // Prefer cheaper options\n * client.registerPolicy((version, reqs) =>\n * reqs.filter(r => BigInt(r.value) < BigInt('1000000'))\n * );\n *\n * // Prefer specific networks\n * client.registerPolicy((version, reqs) =>\n * reqs.filter(r => r.network.startsWith('eip155:'))\n * );\n * ```\n */\n registerPolicy(policy: PaymentPolicy): x402Client {\n this.policies.push(policy);\n return this;\n }\n\n /**\n * Register a hook to execute before payment payload creation.\n * Can abort creation by returning { abort: true, reason: string }\n *\n * @param hook - The hook function to register\n * @returns The x402Client instance for chaining\n */\n onBeforePaymentCreation(hook: BeforePaymentCreationHook): x402Client {\n this.beforePaymentCreationHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute after successful payment payload creation.\n *\n * @param hook - The hook function to register\n * @returns The x402Client instance for chaining\n */\n onAfterPaymentCreation(hook: AfterPaymentCreationHook): x402Client {\n this.afterPaymentCreationHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute when payment payload creation fails.\n * Can recover from failure by returning { recovered: true, payload: PaymentPayload }\n *\n * @param hook - The hook function to register\n * @returns The x402Client instance for chaining\n */\n onPaymentCreationFailure(hook: OnPaymentCreationFailureHook): x402Client {\n this.onPaymentCreationFailureHooks.push(hook);\n return this;\n }\n\n /**\n * Creates a payment payload based on a PaymentRequired response.\n *\n * Automatically extracts x402Version, resource, and extensions from the PaymentRequired\n * response and constructs a complete PaymentPayload with the accepted requirements.\n *\n * @param paymentRequired - The PaymentRequired response from the server\n * @returns Promise resolving to the complete payment payload\n */\n async createPaymentPayload(\n paymentRequired: PaymentRequired,\n ): Promise<PaymentPayload> {\n const clientSchemesByNetwork = this.registeredClientSchemes.get(paymentRequired.x402Version);\n if (!clientSchemesByNetwork) {\n throw new Error(`No client registered for x402 version: ${paymentRequired.x402Version}`);\n }\n\n const requirements = this.selectPaymentRequirements(paymentRequired.x402Version, paymentRequired.accepts);\n\n const context: PaymentCreationContext = {\n paymentRequired,\n selectedRequirements: requirements,\n };\n\n // Execute beforePaymentCreation hooks\n for (const hook of this.beforePaymentCreationHooks) {\n const result = await hook(context);\n if (result && \"abort\" in result && result.abort) {\n throw new Error(`Payment creation aborted: ${result.reason}`);\n }\n }\n\n try {\n const schemeNetworkClient = findByNetworkAndScheme(clientSchemesByNetwork, requirements.scheme, requirements.network);\n if (!schemeNetworkClient) {\n throw new Error(`No client registered for scheme: ${requirements.scheme} and network: ${requirements.network}`);\n }\n\n const partialPayload = await schemeNetworkClient.createPaymentPayload(paymentRequired.x402Version, requirements);\n\n let paymentPayload: PaymentPayload;\n if (partialPayload.x402Version == 1) {\n paymentPayload = partialPayload as PaymentPayload;\n } else {\n paymentPayload = {\n ...partialPayload,\n extensions: paymentRequired.extensions,\n resource: paymentRequired.resource,\n accepted: requirements,\n };\n }\n\n // Execute afterPaymentCreation hooks\n const createdContext: PaymentCreatedContext = {\n ...context,\n paymentPayload,\n };\n\n for (const hook of this.afterPaymentCreationHooks) {\n await hook(createdContext);\n }\n\n return paymentPayload;\n } catch (error) {\n const failureContext: PaymentCreationFailureContext = {\n ...context,\n error: error as Error,\n };\n\n // Execute onPaymentCreationFailure hooks\n for (const hook of this.onPaymentCreationFailureHooks) {\n const result = await hook(failureContext);\n if (result && \"recovered\" in result && result.recovered) {\n return result.payload;\n }\n }\n\n throw error;\n }\n }\n\n\n\n /**\n * Selects appropriate payment requirements based on registered clients and policies.\n *\n * Selection process:\n * 1. Filter by registered schemes (network + scheme support)\n * 2. Apply all registered policies in order\n * 3. Use selector to choose final requirement\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - Array of available payment requirements\n * @returns The selected payment requirements\n */\n private selectPaymentRequirements(x402Version: number, paymentRequirements: PaymentRequirements[]): PaymentRequirements {\n const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version);\n if (!clientSchemesByNetwork) {\n throw new Error(`No client registered for x402 version: ${x402Version}`);\n }\n\n // Step 1: Filter by registered schemes\n const supportedPaymentRequirements = paymentRequirements.filter(requirement => {\n let clientSchemes = findSchemesByNetwork(clientSchemesByNetwork, requirement.network);\n if (!clientSchemes) {\n return false;\n }\n\n return clientSchemes.has(requirement.scheme);\n })\n\n if (supportedPaymentRequirements.length === 0) {\n throw new Error(`No network/scheme registered for x402 version: ${x402Version} which comply with the payment requirements. ${JSON.stringify({\n x402Version,\n paymentRequirements,\n x402Versions: Array.from(this.registeredClientSchemes.keys()),\n networks: Array.from(clientSchemesByNetwork.keys()),\n schemes: Array.from(clientSchemesByNetwork.values()).map(schemes => Array.from(schemes.keys())).flat(),\n })}`);\n }\n\n // Step 2: Apply all policies in order\n let filteredRequirements = supportedPaymentRequirements;\n for (const policy of this.policies) {\n filteredRequirements = policy(x402Version, filteredRequirements);\n\n if (filteredRequirements.length === 0) {\n throw new Error(`All payment requirements were filtered out by policies for x402 version: ${x402Version}`);\n }\n }\n\n // Step 3: Use selector to choose final requirement\n return this.paymentRequirementsSelector(x402Version, filteredRequirements);\n }\n\n /**\n * Internal method to register a scheme client.\n *\n * @param x402Version - The x402 protocol version\n * @param network - The network to register the client for\n * @param client - The scheme network client to register\n * @returns The x402Client instance for chaining\n */\n private _registerScheme(x402Version: number, network: Network, client: SchemeNetworkClient): x402Client {\n if (!this.registeredClientSchemes.has(x402Version)) {\n this.registeredClientSchemes.set(x402Version, new Map());\n }\n const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version)!;\n if (!clientSchemesByNetwork.has(network)) {\n clientSchemesByNetwork.set(network, new Map());\n }\n\n const clientByScheme = clientSchemesByNetwork.get(network)!;\n if (!clientByScheme.has(client.scheme)) {\n clientByScheme.set(client.scheme, client);\n }\n\n return this;\n }\n}\n","import { SettleResponse } from \"../types\";\nimport { PaymentPayload, PaymentRequired, PaymentRequirements } from \"../types/payments\";\nimport { Base64EncodedRegex, safeBase64Decode, safeBase64Encode } from \"../utils\";\n\n// HTTP Methods that typically use query parameters\nexport type QueryParamMethods = \"GET\" | \"HEAD\" | \"DELETE\";\n\n// HTTP Methods that typically use request body\nexport type BodyMethods = \"POST\" | \"PUT\" | \"PATCH\";\n\n/**\n * Encodes a payment payload as a base64 header value.\n *\n * @param paymentPayload - The payment payload to encode\n * @returns Base64 encoded string representation of the payment payload\n */\nexport function encodePaymentSignatureHeader(paymentPayload: PaymentPayload): string {\n return safeBase64Encode(JSON.stringify(paymentPayload));\n}\n\n/**\n * Decodes a base64 payment signature header into a payment payload.\n *\n * @param paymentSignatureHeader - The base64 encoded payment signature header\n * @returns The decoded payment payload\n */\nexport function decodePaymentSignatureHeader(paymentSignatureHeader: string): PaymentPayload {\n if (!Base64EncodedRegex.test(paymentSignatureHeader)) {\n throw new Error(\"Invalid payment signature header\");\n }\n return JSON.parse(safeBase64Decode(paymentSignatureHeader)) as PaymentPayload;\n}\n\n/**\n * Encodes a payment required object as a base64 header value.\n *\n * @param paymentRequired - The payment required object to encode\n * @returns Base64 encoded string representation of the payment required object\n */\nexport function encodePaymentRequiredHeader(paymentRequired: PaymentRequired): string {\n return safeBase64Encode(JSON.stringify(paymentRequired));\n}\n\n/**\n * Decodes a base64 payment required header into a payment required object.\n *\n * @param paymentRequiredHeader - The base64 encoded payment required header\n * @returns The decoded payment required object\n */\nexport function decodePaymentRequiredHeader(paymentRequiredHeader: string): PaymentRequired {\n if (!Base64EncodedRegex.test(paymentRequiredHeader)) {\n throw new Error(\"Invalid payment required header\");\n }\n return JSON.parse(safeBase64Decode(paymentRequiredHeader)) as PaymentRequired;\n}\n\n/**\n * Encodes a payment response as a base64 header value.\n *\n * @param paymentResponse - The payment response to encode\n * @returns Base64 encoded string representation of the payment response\n */\nexport function encodePaymentResponseHeader(\n paymentResponse: SettleResponse & { requirements: PaymentRequirements },\n): string {\n return safeBase64Encode(JSON.stringify(paymentResponse));\n}\n\n/**\n * Decodes a base64 payment response header into a settle response.\n *\n * @param paymentResponseHeader - The base64 encoded payment response header\n * @returns The decoded settle response\n */\nexport function decodePaymentResponseHeader(paymentResponseHeader: string): SettleResponse {\n if (!Base64EncodedRegex.test(paymentResponseHeader)) {\n throw new Error(\"Invalid payment response header\");\n }\n return JSON.parse(safeBase64Decode(paymentResponseHeader)) as SettleResponse;\n}\n\n// Export HTTP service and types\nexport {\n x402HTTPResourceServer,\n HTTPAdapter,\n HTTPRequestContext,\n HTTPResponseInstructions,\n HTTPProcessResult,\n PaywallConfig,\n PaywallProvider,\n PaymentOption,\n RouteConfig,\n RoutesConfig,\n CompiledRoute,\n DynamicPayTo,\n DynamicPrice,\n UnpaidResponseBody,\n UnpaidResponseResult,\n ProcessSettleResultResponse,\n ProcessSettleSuccessResponse,\n ProcessSettleFailureResponse,\n RouteValidationError,\n RouteConfigurationError,\n} from \"./x402HTTPResourceServer\";\nexport {\n HTTPFacilitatorClient,\n FacilitatorClient,\n FacilitatorConfig,\n} from \"./httpFacilitatorClient\";\nexport { x402HTTPClient } from \"./x402HTTPClient\";\n","import {\n decodePaymentRequiredHeader,\n decodePaymentResponseHeader,\n encodePaymentSignatureHeader,\n} from \".\";\nimport { SettleResponse } from \"../types\";\nimport { PaymentPayload, PaymentRequired } from \"../types/payments\";\nimport { x402Client } from \"../client/x402Client\";\n\n/**\n * HTTP-specific client for handling x402 payment protocol over HTTP.\n *\n * Wraps a x402Client to provide HTTP-specific encoding/decoding functionality\n * for payment headers and responses while maintaining the builder pattern.\n */\nexport class x402HTTPClient {\n /**\n * Creates a new x402HTTPClient instance.\n *\n * @param client - The underlying x402Client for payment logic\n */\n constructor(private readonly client: x402Client) {}\n\n /**\n * Encodes a payment payload into appropriate HTTP headers based on version.\n *\n * @param paymentPayload - The payment payload to encode\n * @returns HTTP headers containing the encoded payment signature\n */\n encodePaymentSignatureHeader(paymentPayload: PaymentPayload): Record<string, string> {\n switch (paymentPayload.x402Version) {\n case 2:\n return {\n \"PAYMENT-SIGNATURE\": encodePaymentSignatureHeader(paymentPayload),\n };\n case 1:\n return {\n \"X-PAYMENT\": encodePaymentSignatureHeader(paymentPayload),\n };\n default:\n throw new Error(\n `Unsupported x402 version: ${(paymentPayload as PaymentPayload).x402Version}`,\n );\n }\n }\n\n /**\n * Extracts payment required information from HTTP response.\n *\n * @param getHeader - Function to retrieve header value by name (case-insensitive)\n * @param body - Optional response body for v1 compatibility\n * @returns The payment required object\n */\n getPaymentRequiredResponse(\n getHeader: (name: string) => string | null | undefined,\n body?: unknown,\n ): PaymentRequired {\n // v2\n const paymentRequired = getHeader(\"PAYMENT-REQUIRED\");\n if (paymentRequired) {\n return decodePaymentRequiredHeader(paymentRequired);\n }\n\n // v1\n if (\n body &&\n body instanceof Object &&\n \"x402Version\" in body &&\n (body as PaymentRequired).x402Version === 1\n ) {\n return body as PaymentRequired;\n }\n\n throw new Error(\"Invalid payment required response\");\n }\n\n /**\n * Extracts payment settlement response from HTTP headers.\n *\n * @param getHeader - Function to retrieve header value by name (case-insensitive)\n * @returns The settlement response object\n */\n getPaymentSettleResponse(getHeader: (name: string) => string | null | undefined): SettleResponse {\n // v2\n const paymentResponse = getHeader(\"PAYMENT-RESPONSE\");\n if (paymentResponse) {\n return decodePaymentResponseHeader(paymentResponse);\n }\n\n // v1\n const xPaymentResponse = getHeader(\"X-PAYMENT-RESPONSE\");\n if (xPaymentResponse) {\n return decodePaymentResponseHeader(xPaymentResponse);\n }\n\n throw new Error(\"Payment response header not found\");\n }\n\n /**\n * Creates a payment payload for the given payment requirements.\n * Delegates to the underlying x402Client.\n *\n * @param paymentRequired - The payment required response from the server\n * @returns Promise resolving to the payment payload\n */\n async createPaymentPayload(paymentRequired: PaymentRequ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ACrD;AAEA,UAAM,IAAI,MAAM,mCAAmC;AAAA,EACrD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,qBAAqB,iBAA2D;AACpF,WAAO,KAAK,OAAO,qBAAqB,eAAe;AAAA,EACzD;AACF;","names":["x402Version"]}
|
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
export { E as ExactSvmScheme } from '../../scheme-MoBRXFM8.js';
|
|
2
|
-
import { x402Client, SelectPaymentRequirements, PaymentPolicy } from '@x402/core/client';
|
|
3
|
-
import { Network } from '@x402/core/types';
|
|
4
|
-
import { C as ClientSvmSigner } from '../../signer-BMkbhFYE.js';
|
|
5
|
-
import '@solana/kit';
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Configuration options for registering SVM schemes to an x402Client
|
|
9
|
-
*/
|
|
10
|
-
interface SvmClientConfig {
|
|
11
|
-
/**
|
|
12
|
-
* The SVM signer to use for creating payment payloads
|
|
13
|
-
*/
|
|
14
|
-
signer: ClientSvmSigner;
|
|
15
|
-
/**
|
|
16
|
-
* Optional payment requirements selector function
|
|
17
|
-
*/
|
|
18
|
-
paymentRequirementsSelector?: SelectPaymentRequirements;
|
|
19
|
-
/**
|
|
20
|
-
* Optional policies to apply to the client
|
|
21
|
-
*/
|
|
22
|
-
policies?: PaymentPolicy[];
|
|
23
|
-
/**
|
|
24
|
-
* Optional specific networks to register
|
|
25
|
-
*/
|
|
26
|
-
networks?: Network[];
|
|
27
|
-
}
|
|
28
|
-
/**
|
|
29
|
-
* Registers SVM payment schemes to an existing x402Client instance.
|
|
30
|
-
*
|
|
31
|
-
* @param client - The x402Client instance to register schemes to
|
|
32
|
-
* @param config - Configuration for SVM client registration
|
|
33
|
-
* @returns The client instance for chaining
|
|
34
|
-
*/
|
|
35
|
-
declare function registerExactSvmScheme(client: x402Client, config: SvmClientConfig): x402Client;
|
|
36
|
-
|
|
37
|
-
export { type SvmClientConfig, registerExactSvmScheme };
|