@bankofai/x402-core 1.0.0-beta.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.
- package/README.md +294 -0
- package/dist/cjs/client/index.d.ts +149 -0
- package/dist/cjs/client/index.js +909 -0
- package/dist/cjs/client/index.js.map +1 -0
- package/dist/cjs/facilitator/index.d.ts +206 -0
- package/dist/cjs/facilitator/index.js +431 -0
- package/dist/cjs/facilitator/index.js.map +1 -0
- package/dist/cjs/http/index.d.ts +50 -0
- package/dist/cjs/http/index.js +1452 -0
- package/dist/cjs/http/index.js.map +1 -0
- package/dist/cjs/index.d.ts +3 -0
- package/dist/cjs/index.js +31 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/schemas/index.d.ts +891 -0
- package/dist/cjs/schemas/index.js +216 -0
- package/dist/cjs/schemas/index.js.map +1 -0
- package/dist/cjs/server/index.d.ts +79 -0
- package/dist/cjs/server/index.js +2568 -0
- package/dist/cjs/server/index.js.map +1 -0
- package/dist/cjs/types/index.d.ts +1 -0
- package/dist/cjs/types/index.js +97 -0
- package/dist/cjs/types/index.js.map +1 -0
- package/dist/cjs/types/v1/index.d.ts +1 -0
- package/dist/cjs/types/v1/index.js +19 -0
- package/dist/cjs/types/v1/index.js.map +1 -0
- package/dist/cjs/utils/index.d.ts +77 -0
- package/dist/cjs/utils/index.js +179 -0
- package/dist/cjs/utils/index.js.map +1 -0
- package/dist/cjs/x402Client-BgegfQgE.d.ts +1807 -0
- package/dist/cjs/x402Client-TQHctrG7.d.ts +1807 -0
- package/dist/esm/chunk-ABS7D6VX.mjs +145 -0
- package/dist/esm/chunk-ABS7D6VX.mjs.map +1 -0
- package/dist/esm/chunk-AGOUMC4P.mjs +68 -0
- package/dist/esm/chunk-AGOUMC4P.mjs.map +1 -0
- package/dist/esm/chunk-BJTO5JO5.mjs +11 -0
- package/dist/esm/chunk-BJTO5JO5.mjs.map +1 -0
- package/dist/esm/chunk-FPXAE3OS.mjs +161 -0
- package/dist/esm/chunk-FPXAE3OS.mjs.map +1 -0
- package/dist/esm/chunk-IL77TMJL.mjs +1275 -0
- package/dist/esm/chunk-IL77TMJL.mjs.map +1 -0
- package/dist/esm/chunk-VE37GDG2.mjs +7 -0
- package/dist/esm/chunk-VE37GDG2.mjs.map +1 -0
- package/dist/esm/client/index.d.mts +149 -0
- package/dist/esm/client/index.mjs +504 -0
- package/dist/esm/client/index.mjs.map +1 -0
- package/dist/esm/facilitator/index.d.mts +206 -0
- package/dist/esm/facilitator/index.mjs +399 -0
- package/dist/esm/facilitator/index.mjs.map +1 -0
- package/dist/esm/http/index.d.mts +50 -0
- package/dist/esm/http/index.mjs +35 -0
- package/dist/esm/http/index.mjs.map +1 -0
- package/dist/esm/index.d.mts +3 -0
- package/dist/esm/index.mjs +8 -0
- package/dist/esm/index.mjs.map +1 -0
- package/dist/esm/schemas/index.d.mts +891 -0
- package/dist/esm/schemas/index.mjs +70 -0
- package/dist/esm/schemas/index.mjs.map +1 -0
- package/dist/esm/server/index.d.mts +79 -0
- package/dist/esm/server/index.mjs +1318 -0
- package/dist/esm/server/index.mjs.map +1 -0
- package/dist/esm/types/index.d.mts +1 -0
- package/dist/esm/types/index.mjs +14 -0
- package/dist/esm/types/index.mjs.map +1 -0
- package/dist/esm/types/v1/index.d.mts +1 -0
- package/dist/esm/types/v1/index.mjs +1 -0
- package/dist/esm/types/v1/index.mjs.map +1 -0
- package/dist/esm/utils/index.d.mts +77 -0
- package/dist/esm/utils/index.mjs +28 -0
- package/dist/esm/utils/index.mjs.map +1 -0
- package/dist/esm/x402Client-BgegfQgE.d.mts +1807 -0
- package/dist/esm/x402Client-TQHctrG7.d.mts +1807 -0
- package/package.json +142 -0
|
@@ -0,0 +1,909 @@
|
|
|
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 escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
33
|
+
var networkPatternToRegExp = (pattern) => {
|
|
34
|
+
const source = escapeRegExp(pattern).replace(/\\\*/g, ".*");
|
|
35
|
+
return new RegExp(`^${source}$`);
|
|
36
|
+
};
|
|
37
|
+
var networkMatchesPattern = (pattern, network) => {
|
|
38
|
+
return networkPatternToRegExp(pattern).test(network);
|
|
39
|
+
};
|
|
40
|
+
var findSchemesByNetwork = (map, network) => {
|
|
41
|
+
let implementationsByScheme = map.get(network);
|
|
42
|
+
if (!implementationsByScheme) {
|
|
43
|
+
for (const [registeredNetworkPattern, implementations] of map.entries()) {
|
|
44
|
+
if (networkMatchesPattern(registeredNetworkPattern, network)) {
|
|
45
|
+
implementationsByScheme = implementations;
|
|
46
|
+
break;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return implementationsByScheme;
|
|
51
|
+
};
|
|
52
|
+
var findByNetworkAndScheme = (map, scheme, network) => {
|
|
53
|
+
return findSchemesByNetwork(map, network)?.get(scheme);
|
|
54
|
+
};
|
|
55
|
+
var Base64EncodedRegex = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
56
|
+
function safeBase64Encode(data) {
|
|
57
|
+
if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") {
|
|
58
|
+
const bytes = new TextEncoder().encode(data);
|
|
59
|
+
const binaryString = Array.from(bytes, (byte) => String.fromCharCode(byte)).join("");
|
|
60
|
+
return globalThis.btoa(binaryString);
|
|
61
|
+
}
|
|
62
|
+
return Buffer.from(data, "utf8").toString("base64");
|
|
63
|
+
}
|
|
64
|
+
function safeBase64Decode(data) {
|
|
65
|
+
if (typeof globalThis !== "undefined" && typeof globalThis.atob === "function") {
|
|
66
|
+
const binaryString = globalThis.atob(data);
|
|
67
|
+
const bytes = new Uint8Array(binaryString.length);
|
|
68
|
+
for (let i = 0; i < binaryString.length; i++) {
|
|
69
|
+
bytes[i] = binaryString.charCodeAt(i);
|
|
70
|
+
}
|
|
71
|
+
const decoder = new TextDecoder("utf-8");
|
|
72
|
+
return decoder.decode(bytes);
|
|
73
|
+
}
|
|
74
|
+
return Buffer.from(data, "base64").toString("utf-8");
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// src/client/x402Client.ts
|
|
78
|
+
var x402Client = class _x402Client {
|
|
79
|
+
/**
|
|
80
|
+
* Creates a new x402Client instance.
|
|
81
|
+
*
|
|
82
|
+
* @param paymentRequirementsSelector - Function to select payment requirements from available options
|
|
83
|
+
*/
|
|
84
|
+
constructor(paymentRequirementsSelector) {
|
|
85
|
+
this.registeredClientSchemes = /* @__PURE__ */ new Map();
|
|
86
|
+
this.schemeClientHookAdapters = /* @__PURE__ */ new Map();
|
|
87
|
+
this.policies = [];
|
|
88
|
+
this.registeredExtensions = /* @__PURE__ */ new Map();
|
|
89
|
+
this.beforePaymentCreationHooks = [];
|
|
90
|
+
this.afterPaymentCreationHooks = [];
|
|
91
|
+
this.onPaymentCreationFailureHooks = [];
|
|
92
|
+
this.paymentResponseHooks = [];
|
|
93
|
+
this.paymentRequirementsSelector = paymentRequirementsSelector || ((x402Version2, accepts) => accepts[0]);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Creates a new x402Client instance from a configuration object.
|
|
97
|
+
*
|
|
98
|
+
* @param config - The client configuration including schemes, policies, and payment requirements selector
|
|
99
|
+
* @returns A configured x402Client instance
|
|
100
|
+
*/
|
|
101
|
+
static fromConfig(config) {
|
|
102
|
+
const client = new _x402Client(config.paymentRequirementsSelector);
|
|
103
|
+
config.schemes.forEach((scheme) => {
|
|
104
|
+
if (scheme.x402Version === 1) {
|
|
105
|
+
client.registerV1(scheme.network, scheme.client);
|
|
106
|
+
} else {
|
|
107
|
+
client.register(scheme.network, scheme.client);
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
config.policies?.forEach((policy) => {
|
|
111
|
+
client.registerPolicy(policy);
|
|
112
|
+
});
|
|
113
|
+
return client;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Registers a scheme client for the current x402 version.
|
|
117
|
+
*
|
|
118
|
+
* @param network - The network to register the client for
|
|
119
|
+
* @param client - The scheme network client to register
|
|
120
|
+
* @returns The x402Client instance for chaining
|
|
121
|
+
*/
|
|
122
|
+
register(network, client) {
|
|
123
|
+
return this._registerScheme(x402Version, network, client);
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Registers a scheme client for x402 version 1.
|
|
127
|
+
*
|
|
128
|
+
* @param network - The v1 network identifier (e.g., 'base-sepolia', 'solana-devnet')
|
|
129
|
+
* @param client - The scheme network client to register
|
|
130
|
+
* @returns The x402Client instance for chaining
|
|
131
|
+
*/
|
|
132
|
+
registerV1(network, client) {
|
|
133
|
+
return this._registerScheme(1, network, client);
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Registers a policy to filter or transform payment requirements.
|
|
137
|
+
*
|
|
138
|
+
* Policies are applied in order after filtering by registered schemes
|
|
139
|
+
* and before the selector chooses the final payment requirement.
|
|
140
|
+
*
|
|
141
|
+
* @param policy - Function to filter/transform payment requirements
|
|
142
|
+
* @returns The x402Client instance for chaining
|
|
143
|
+
*
|
|
144
|
+
* @example
|
|
145
|
+
* ```typescript
|
|
146
|
+
* // Prefer cheaper options
|
|
147
|
+
* client.registerPolicy((version, reqs) =>
|
|
148
|
+
* reqs.filter(r => BigInt(r.value) < BigInt('1000000'))
|
|
149
|
+
* );
|
|
150
|
+
*
|
|
151
|
+
* // Prefer specific networks
|
|
152
|
+
* client.registerPolicy((version, reqs) =>
|
|
153
|
+
* reqs.filter(r => r.network.startsWith('eip155:'))
|
|
154
|
+
* );
|
|
155
|
+
* ```
|
|
156
|
+
*/
|
|
157
|
+
registerPolicy(policy) {
|
|
158
|
+
this.policies.push(policy);
|
|
159
|
+
return this;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Registers a client extension that can enrich payment payloads.
|
|
163
|
+
*
|
|
164
|
+
* Extensions are invoked after the scheme creates the base payload and the
|
|
165
|
+
* payload is wrapped with extensions/resource/accepted data. If the extension's
|
|
166
|
+
* key is present in `paymentRequired.extensions`, the extension's
|
|
167
|
+
* `enrichPaymentPayload` hook is called to modify the payload.
|
|
168
|
+
*
|
|
169
|
+
* @param extension - The client extension to register
|
|
170
|
+
* @returns The x402Client instance for chaining
|
|
171
|
+
*/
|
|
172
|
+
registerExtension(extension) {
|
|
173
|
+
this.registeredExtensions.set(extension.key, extension);
|
|
174
|
+
return this;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Get all registered client extensions.
|
|
178
|
+
*
|
|
179
|
+
* @returns Array of registered extensions
|
|
180
|
+
*/
|
|
181
|
+
getExtensions() {
|
|
182
|
+
return Array.from(this.registeredExtensions.values());
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Register a hook to execute before payment payload creation.
|
|
186
|
+
* Can abort creation by returning { abort: true, reason: string }
|
|
187
|
+
*
|
|
188
|
+
* @param hook - The hook function to register
|
|
189
|
+
* @returns The x402Client instance for chaining
|
|
190
|
+
*/
|
|
191
|
+
onBeforePaymentCreation(hook) {
|
|
192
|
+
this.beforePaymentCreationHooks.push(hook);
|
|
193
|
+
return this;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Register a hook to execute after successful payment payload creation.
|
|
197
|
+
*
|
|
198
|
+
* @param hook - The hook function to register
|
|
199
|
+
* @returns The x402Client instance for chaining
|
|
200
|
+
*/
|
|
201
|
+
onAfterPaymentCreation(hook) {
|
|
202
|
+
this.afterPaymentCreationHooks.push(hook);
|
|
203
|
+
return this;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Register a hook to execute when payment payload creation fails.
|
|
207
|
+
* Can recover from failure by returning { recovered: true, payload: PaymentPayload }
|
|
208
|
+
*
|
|
209
|
+
* @param hook - The hook function to register
|
|
210
|
+
* @returns The x402Client instance for chaining
|
|
211
|
+
*/
|
|
212
|
+
onPaymentCreationFailure(hook) {
|
|
213
|
+
this.onPaymentCreationFailureHooks.push(hook);
|
|
214
|
+
return this;
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Register a hook to execute after a paid request completes.
|
|
218
|
+
* Can signal recovery by returning { recovered: true }, causing the transport to retry.
|
|
219
|
+
*
|
|
220
|
+
* @param hook - The hook function to register
|
|
221
|
+
* @returns The x402Client instance for chaining
|
|
222
|
+
*/
|
|
223
|
+
onPaymentResponse(hook) {
|
|
224
|
+
this.paymentResponseHooks.push(hook);
|
|
225
|
+
return this;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Fires all registered payment response hooks in order.
|
|
229
|
+
* Returns `{ recovered: true }` if any hook signals recovery (first wins).
|
|
230
|
+
*
|
|
231
|
+
* @param ctx - The payment response context
|
|
232
|
+
* @returns Recovery signal or undefined
|
|
233
|
+
*/
|
|
234
|
+
async handlePaymentResponse(ctx) {
|
|
235
|
+
for (const hook of this.getLabeledHooks(
|
|
236
|
+
"onPaymentResponse",
|
|
237
|
+
ctx.paymentPayload.x402Version,
|
|
238
|
+
ctx.requirements,
|
|
239
|
+
ctx.paymentRequired?.extensions ?? ctx.paymentPayload.extensions
|
|
240
|
+
)) {
|
|
241
|
+
const result = await hook(ctx);
|
|
242
|
+
if (result && "recovered" in result && result.recovered) {
|
|
243
|
+
return { recovered: true };
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return void 0;
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Creates a payment payload based on a PaymentRequired response.
|
|
250
|
+
*
|
|
251
|
+
* Automatically extracts x402Version, resource, and extensions from the PaymentRequired
|
|
252
|
+
* response and constructs a complete PaymentPayload with the accepted requirements.
|
|
253
|
+
*
|
|
254
|
+
* @param paymentRequired - The PaymentRequired response from the server
|
|
255
|
+
* @returns Promise resolving to the complete payment payload
|
|
256
|
+
*/
|
|
257
|
+
async createPaymentPayload(paymentRequired) {
|
|
258
|
+
const clientSchemesByNetwork = this.registeredClientSchemes.get(paymentRequired.x402Version);
|
|
259
|
+
if (!clientSchemesByNetwork) {
|
|
260
|
+
throw new Error(`No client registered for x402 version: ${paymentRequired.x402Version}`);
|
|
261
|
+
}
|
|
262
|
+
const requirements = this.selectPaymentRequirements(paymentRequired.x402Version, paymentRequired.accepts);
|
|
263
|
+
const context = {
|
|
264
|
+
paymentRequired,
|
|
265
|
+
selectedRequirements: requirements
|
|
266
|
+
};
|
|
267
|
+
for (const hook of this.getLabeledHooks(
|
|
268
|
+
"beforePaymentCreation",
|
|
269
|
+
paymentRequired.x402Version,
|
|
270
|
+
requirements,
|
|
271
|
+
paymentRequired.extensions
|
|
272
|
+
)) {
|
|
273
|
+
const result = await hook(context);
|
|
274
|
+
if (result && "abort" in result && result.abort) {
|
|
275
|
+
throw new Error(`Payment creation aborted: ${result.reason}`);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
try {
|
|
279
|
+
const schemeNetworkClient = findByNetworkAndScheme(clientSchemesByNetwork, requirements.scheme, requirements.network);
|
|
280
|
+
if (!schemeNetworkClient) {
|
|
281
|
+
throw new Error(`No client registered for scheme: ${requirements.scheme} and network: ${requirements.network}`);
|
|
282
|
+
}
|
|
283
|
+
const partialPayload = await schemeNetworkClient.createPaymentPayload(
|
|
284
|
+
paymentRequired.x402Version,
|
|
285
|
+
requirements,
|
|
286
|
+
{ extensions: paymentRequired.extensions }
|
|
287
|
+
);
|
|
288
|
+
let paymentPayload;
|
|
289
|
+
if (partialPayload.x402Version == 1) {
|
|
290
|
+
paymentPayload = partialPayload;
|
|
291
|
+
} else {
|
|
292
|
+
const mergedExtensions = this.mergeExtensions(
|
|
293
|
+
paymentRequired.extensions,
|
|
294
|
+
partialPayload.extensions
|
|
295
|
+
);
|
|
296
|
+
paymentPayload = {
|
|
297
|
+
x402Version: partialPayload.x402Version,
|
|
298
|
+
payload: partialPayload.payload,
|
|
299
|
+
extensions: mergedExtensions,
|
|
300
|
+
resource: paymentRequired.resource,
|
|
301
|
+
accepted: requirements
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
paymentPayload = await this.enrichPaymentPayloadWithExtensions(paymentPayload, paymentRequired);
|
|
305
|
+
const createdContext = {
|
|
306
|
+
...context,
|
|
307
|
+
paymentPayload
|
|
308
|
+
};
|
|
309
|
+
for (const hook of this.getLabeledHooks(
|
|
310
|
+
"afterPaymentCreation",
|
|
311
|
+
paymentRequired.x402Version,
|
|
312
|
+
requirements,
|
|
313
|
+
paymentRequired.extensions
|
|
314
|
+
)) {
|
|
315
|
+
await hook(createdContext);
|
|
316
|
+
}
|
|
317
|
+
return paymentPayload;
|
|
318
|
+
} catch (error) {
|
|
319
|
+
const failureContext = {
|
|
320
|
+
...context,
|
|
321
|
+
error
|
|
322
|
+
};
|
|
323
|
+
for (const hook of this.getLabeledHooks(
|
|
324
|
+
"onPaymentCreationFailure",
|
|
325
|
+
paymentRequired.x402Version,
|
|
326
|
+
requirements,
|
|
327
|
+
paymentRequired.extensions
|
|
328
|
+
)) {
|
|
329
|
+
const result = await hook(failureContext);
|
|
330
|
+
if (result && "recovered" in result && result.recovered) {
|
|
331
|
+
return result.payload;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
throw error;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Merges server-declared extensions with client extension echoes.
|
|
339
|
+
* Client extension data may add fields, but server-declared fields remain intact.
|
|
340
|
+
*
|
|
341
|
+
* @param serverExtensions - Extensions declared by the server in the 402 response
|
|
342
|
+
* @param clientExtensions - Extensions provided by the client or scheme
|
|
343
|
+
* @returns The merged extensions object, or undefined if both inputs are undefined
|
|
344
|
+
*/
|
|
345
|
+
mergeExtensions(serverExtensions, clientExtensions) {
|
|
346
|
+
if (!clientExtensions) return serverExtensions;
|
|
347
|
+
if (!serverExtensions) return clientExtensions;
|
|
348
|
+
const merged = { ...serverExtensions };
|
|
349
|
+
for (const [key, clientValue] of Object.entries(clientExtensions)) {
|
|
350
|
+
const serverValue = merged[key];
|
|
351
|
+
if (serverValue === null || typeof serverValue !== "object" || Array.isArray(serverValue) || clientValue === null || typeof clientValue !== "object" || Array.isArray(clientValue)) {
|
|
352
|
+
merged[key] = clientValue;
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
const serverRecord = serverValue;
|
|
356
|
+
const clientRecord = clientValue;
|
|
357
|
+
const extensionValue = { ...serverRecord };
|
|
358
|
+
const pending = [{ target: extensionValue, source: clientRecord }];
|
|
359
|
+
for (const item of pending) {
|
|
360
|
+
for (const [fieldKey, clientFieldValue] of Object.entries(item.source)) {
|
|
361
|
+
const serverFieldValue = item.target[fieldKey];
|
|
362
|
+
if (serverFieldValue !== null && typeof serverFieldValue === "object" && !Array.isArray(serverFieldValue) && clientFieldValue !== null && typeof clientFieldValue === "object" && !Array.isArray(clientFieldValue)) {
|
|
363
|
+
const nestedValue = { ...serverFieldValue };
|
|
364
|
+
item.target[fieldKey] = nestedValue;
|
|
365
|
+
pending.push({
|
|
366
|
+
target: nestedValue,
|
|
367
|
+
source: clientFieldValue
|
|
368
|
+
});
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
if (!Object.prototype.hasOwnProperty.call(item.target, fieldKey)) {
|
|
372
|
+
item.target[fieldKey] = clientFieldValue;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
merged[key] = extensionValue;
|
|
377
|
+
}
|
|
378
|
+
return merged;
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Enriches a payment payload by calling registered extension hooks.
|
|
382
|
+
* For each extension key present in the PaymentRequired response,
|
|
383
|
+
* invokes the corresponding extension's enrichPaymentPayload callback.
|
|
384
|
+
*
|
|
385
|
+
* @param paymentPayload - The payment payload to enrich with extension data
|
|
386
|
+
* @param paymentRequired - The PaymentRequired response containing extension declarations
|
|
387
|
+
* @returns The enriched payment payload with extension data applied
|
|
388
|
+
*/
|
|
389
|
+
async enrichPaymentPayloadWithExtensions(paymentPayload, paymentRequired) {
|
|
390
|
+
if (!paymentRequired.extensions || this.registeredExtensions.size === 0) {
|
|
391
|
+
return paymentPayload;
|
|
392
|
+
}
|
|
393
|
+
let enriched = paymentPayload;
|
|
394
|
+
for (const [key, extension] of this.registeredExtensions) {
|
|
395
|
+
if (key in paymentRequired.extensions && extension.enrichPaymentPayload) {
|
|
396
|
+
enriched = await extension.enrichPaymentPayload(enriched, paymentRequired);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
return {
|
|
400
|
+
...enriched,
|
|
401
|
+
extensions: this.mergeExtensions(paymentRequired.extensions, enriched.extensions)
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Selects appropriate payment requirements based on registered clients and policies.
|
|
406
|
+
*
|
|
407
|
+
* Selection process:
|
|
408
|
+
* 1. Filter by registered schemes (network + scheme support)
|
|
409
|
+
* 2. Apply all registered policies in order
|
|
410
|
+
* 3. Use selector to choose final requirement
|
|
411
|
+
*
|
|
412
|
+
* @param x402Version - The x402 protocol version
|
|
413
|
+
* @param paymentRequirements - Array of available payment requirements
|
|
414
|
+
* @returns The selected payment requirements
|
|
415
|
+
*/
|
|
416
|
+
selectPaymentRequirements(x402Version2, paymentRequirements) {
|
|
417
|
+
const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version2);
|
|
418
|
+
if (!clientSchemesByNetwork) {
|
|
419
|
+
throw new Error(`No client registered for x402 version: ${x402Version2}`);
|
|
420
|
+
}
|
|
421
|
+
const supportedPaymentRequirements = paymentRequirements.filter((requirement) => {
|
|
422
|
+
let clientSchemes = findSchemesByNetwork(clientSchemesByNetwork, requirement.network);
|
|
423
|
+
if (!clientSchemes) {
|
|
424
|
+
return false;
|
|
425
|
+
}
|
|
426
|
+
return clientSchemes.has(requirement.scheme);
|
|
427
|
+
});
|
|
428
|
+
if (supportedPaymentRequirements.length === 0) {
|
|
429
|
+
throw new Error(`No network/scheme registered for x402 version: ${x402Version2} which comply with the payment requirements. ${JSON.stringify({
|
|
430
|
+
x402Version: x402Version2,
|
|
431
|
+
paymentRequirements,
|
|
432
|
+
x402Versions: Array.from(this.registeredClientSchemes.keys()),
|
|
433
|
+
networks: Array.from(clientSchemesByNetwork.keys()),
|
|
434
|
+
schemes: Array.from(clientSchemesByNetwork.values()).map((schemes) => Array.from(schemes.keys())).flat()
|
|
435
|
+
})}`);
|
|
436
|
+
}
|
|
437
|
+
let filteredRequirements = supportedPaymentRequirements;
|
|
438
|
+
for (const policy of this.policies) {
|
|
439
|
+
filteredRequirements = policy(x402Version2, filteredRequirements);
|
|
440
|
+
if (filteredRequirements.length === 0) {
|
|
441
|
+
throw new Error(`All payment requirements were filtered out by policies for x402 version: ${x402Version2}`);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
return this.paymentRequirementsSelector(x402Version2, filteredRequirements);
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Internal method to register a scheme client.
|
|
448
|
+
*
|
|
449
|
+
* @param x402Version - The x402 protocol version
|
|
450
|
+
* @param network - The network to register the client for
|
|
451
|
+
* @param client - The scheme network client to register
|
|
452
|
+
* @returns The x402Client instance for chaining
|
|
453
|
+
*/
|
|
454
|
+
_registerScheme(x402Version2, network, client) {
|
|
455
|
+
if (!this.registeredClientSchemes.has(x402Version2)) {
|
|
456
|
+
this.registeredClientSchemes.set(x402Version2, /* @__PURE__ */ new Map());
|
|
457
|
+
}
|
|
458
|
+
const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version2);
|
|
459
|
+
if (!clientSchemesByNetwork.has(network)) {
|
|
460
|
+
clientSchemesByNetwork.set(network, /* @__PURE__ */ new Map());
|
|
461
|
+
}
|
|
462
|
+
const clientByScheme = clientSchemesByNetwork.get(network);
|
|
463
|
+
clientByScheme.set(client.scheme, client);
|
|
464
|
+
if (!this.schemeClientHookAdapters.has(x402Version2)) {
|
|
465
|
+
this.schemeClientHookAdapters.set(x402Version2, /* @__PURE__ */ new Map());
|
|
466
|
+
}
|
|
467
|
+
const adaptersByNetwork = this.schemeClientHookAdapters.get(x402Version2);
|
|
468
|
+
if (!adaptersByNetwork.has(network)) {
|
|
469
|
+
adaptersByNetwork.set(network, /* @__PURE__ */ new Map());
|
|
470
|
+
}
|
|
471
|
+
const adaptersByScheme = adaptersByNetwork.get(network);
|
|
472
|
+
const hooks = client.schemeHooks;
|
|
473
|
+
if (!hooks) {
|
|
474
|
+
adaptersByScheme.delete(client.scheme);
|
|
475
|
+
return this;
|
|
476
|
+
}
|
|
477
|
+
const handles = {};
|
|
478
|
+
if (hooks.onBeforePaymentCreation) {
|
|
479
|
+
handles.beforePaymentCreation = hooks.onBeforePaymentCreation;
|
|
480
|
+
}
|
|
481
|
+
if (hooks.onAfterPaymentCreation) {
|
|
482
|
+
handles.afterPaymentCreation = hooks.onAfterPaymentCreation;
|
|
483
|
+
}
|
|
484
|
+
if (hooks.onPaymentCreationFailure) {
|
|
485
|
+
handles.onPaymentCreationFailure = hooks.onPaymentCreationFailure;
|
|
486
|
+
}
|
|
487
|
+
if (hooks.onPaymentResponse) {
|
|
488
|
+
handles.onPaymentResponse = hooks.onPaymentResponse;
|
|
489
|
+
}
|
|
490
|
+
if (Object.keys(handles).length > 0) {
|
|
491
|
+
adaptersByScheme.set(client.scheme, handles);
|
|
492
|
+
} else {
|
|
493
|
+
adaptersByScheme.delete(client.scheme);
|
|
494
|
+
}
|
|
495
|
+
return this;
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* Returns manual hooks followed by the selected scheme hook and declared extension hooks.
|
|
499
|
+
*
|
|
500
|
+
* @param phase - Hook slot to collect
|
|
501
|
+
* @param x402Version - Protocol version for the selected requirement
|
|
502
|
+
* @param requirements - Selected payment requirement
|
|
503
|
+
* @param declaredExtensions - Extension declarations that scope extension hooks
|
|
504
|
+
* @returns Hooks in invocation order
|
|
505
|
+
*/
|
|
506
|
+
getLabeledHooks(phase, x402Version2, requirements, declaredExtensions) {
|
|
507
|
+
let manual;
|
|
508
|
+
switch (phase) {
|
|
509
|
+
case "beforePaymentCreation":
|
|
510
|
+
manual = this.beforePaymentCreationHooks;
|
|
511
|
+
break;
|
|
512
|
+
case "afterPaymentCreation":
|
|
513
|
+
manual = this.afterPaymentCreationHooks;
|
|
514
|
+
break;
|
|
515
|
+
case "onPaymentCreationFailure":
|
|
516
|
+
manual = this.onPaymentCreationFailureHooks;
|
|
517
|
+
break;
|
|
518
|
+
case "onPaymentResponse":
|
|
519
|
+
manual = this.paymentResponseHooks;
|
|
520
|
+
break;
|
|
521
|
+
}
|
|
522
|
+
const out = [...manual];
|
|
523
|
+
const adaptersByNetwork = this.schemeClientHookAdapters.get(x402Version2);
|
|
524
|
+
const schemeAdapter = adaptersByNetwork ? findByNetworkAndScheme(adaptersByNetwork, requirements.scheme, requirements.network) : void 0;
|
|
525
|
+
const hook = schemeAdapter?.[phase];
|
|
526
|
+
if (hook !== void 0) {
|
|
527
|
+
out.push(hook);
|
|
528
|
+
}
|
|
529
|
+
if (!declaredExtensions) {
|
|
530
|
+
return out;
|
|
531
|
+
}
|
|
532
|
+
const extensionHookKey = this.getClientExtensionHookKey(phase);
|
|
533
|
+
for (const [extensionKey, extension] of this.registeredExtensions) {
|
|
534
|
+
if (!(extensionKey in declaredExtensions)) continue;
|
|
535
|
+
const extensionHook = extension.hooks?.[extensionHookKey];
|
|
536
|
+
if (!extensionHook) continue;
|
|
537
|
+
out.push((async (ctx) => {
|
|
538
|
+
return extensionHook(declaredExtensions[extensionKey], ctx);
|
|
539
|
+
}));
|
|
540
|
+
}
|
|
541
|
+
return out;
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* Maps internal hook phases to extension hook names.
|
|
545
|
+
*
|
|
546
|
+
* @param phase - Internal hook phase
|
|
547
|
+
* @returns Extension hook key for the phase
|
|
548
|
+
*/
|
|
549
|
+
getClientExtensionHookKey(phase) {
|
|
550
|
+
switch (phase) {
|
|
551
|
+
case "beforePaymentCreation":
|
|
552
|
+
return "onBeforePaymentCreation";
|
|
553
|
+
case "afterPaymentCreation":
|
|
554
|
+
return "onAfterPaymentCreation";
|
|
555
|
+
case "onPaymentCreationFailure":
|
|
556
|
+
return "onPaymentCreationFailure";
|
|
557
|
+
case "onPaymentResponse":
|
|
558
|
+
return "onPaymentResponse";
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
};
|
|
562
|
+
|
|
563
|
+
// src/schemas/index.ts
|
|
564
|
+
var import_zod = require("zod");
|
|
565
|
+
var import_zod2 = require("zod");
|
|
566
|
+
var NonEmptyString = import_zod.z.string().min(1);
|
|
567
|
+
var Any = import_zod.z.record(import_zod.z.unknown());
|
|
568
|
+
var OptionalAny = import_zod.z.record(import_zod.z.unknown()).optional().nullable();
|
|
569
|
+
var NetworkSchemaV1 = NonEmptyString;
|
|
570
|
+
var NetworkSchemaV2 = import_zod.z.string().min(3).refine((val) => val.includes(":"), {
|
|
571
|
+
message: "Network must be in CAIP-2 format (e.g., 'eip155:84532')"
|
|
572
|
+
});
|
|
573
|
+
var NetworkSchema = import_zod.z.union([NetworkSchemaV1, NetworkSchemaV2]);
|
|
574
|
+
var PRINTABLE_ASCII_REGEX = /^[\x20-\x7e]+$/;
|
|
575
|
+
var ResourceInfoSchema = import_zod.z.object({
|
|
576
|
+
url: NonEmptyString,
|
|
577
|
+
description: import_zod.z.string().optional(),
|
|
578
|
+
mimeType: import_zod.z.string().optional(),
|
|
579
|
+
serviceName: import_zod.z.string().min(1).max(32).regex(PRINTABLE_ASCII_REGEX).optional(),
|
|
580
|
+
tags: import_zod.z.array(import_zod.z.string().min(1).max(32).regex(PRINTABLE_ASCII_REGEX)).max(5).optional(),
|
|
581
|
+
iconUrl: import_zod.z.string().max(2048).optional()
|
|
582
|
+
});
|
|
583
|
+
var PaymentRequirementsV1Schema = import_zod.z.object({
|
|
584
|
+
scheme: NonEmptyString,
|
|
585
|
+
network: NetworkSchemaV1,
|
|
586
|
+
maxAmountRequired: NonEmptyString,
|
|
587
|
+
resource: NonEmptyString,
|
|
588
|
+
// URL string in V1
|
|
589
|
+
description: import_zod.z.string(),
|
|
590
|
+
mimeType: import_zod.z.string().optional(),
|
|
591
|
+
outputSchema: Any.optional().nullable(),
|
|
592
|
+
payTo: NonEmptyString,
|
|
593
|
+
maxTimeoutSeconds: import_zod.z.number().positive(),
|
|
594
|
+
asset: NonEmptyString,
|
|
595
|
+
extra: OptionalAny
|
|
596
|
+
});
|
|
597
|
+
var PaymentRequiredV1Schema = import_zod.z.object({
|
|
598
|
+
x402Version: import_zod.z.literal(1),
|
|
599
|
+
error: import_zod.z.string().optional(),
|
|
600
|
+
accepts: import_zod.z.array(PaymentRequirementsV1Schema).min(1)
|
|
601
|
+
});
|
|
602
|
+
var PaymentPayloadV1Schema = import_zod.z.object({
|
|
603
|
+
x402Version: import_zod.z.literal(1),
|
|
604
|
+
scheme: NonEmptyString,
|
|
605
|
+
network: NetworkSchemaV1,
|
|
606
|
+
payload: Any
|
|
607
|
+
});
|
|
608
|
+
var PaymentRequirementsV2Schema = import_zod.z.object({
|
|
609
|
+
scheme: NonEmptyString,
|
|
610
|
+
network: NetworkSchemaV2,
|
|
611
|
+
amount: NonEmptyString,
|
|
612
|
+
asset: NonEmptyString,
|
|
613
|
+
payTo: NonEmptyString,
|
|
614
|
+
maxTimeoutSeconds: import_zod.z.number().positive(),
|
|
615
|
+
extra: OptionalAny
|
|
616
|
+
});
|
|
617
|
+
var PaymentRequiredV2Schema = import_zod.z.object({
|
|
618
|
+
x402Version: import_zod.z.literal(2),
|
|
619
|
+
error: import_zod.z.string().optional(),
|
|
620
|
+
resource: ResourceInfoSchema,
|
|
621
|
+
accepts: import_zod.z.array(PaymentRequirementsV2Schema).min(1),
|
|
622
|
+
extensions: OptionalAny
|
|
623
|
+
});
|
|
624
|
+
var PaymentPayloadV2Schema = import_zod.z.object({
|
|
625
|
+
x402Version: import_zod.z.literal(2),
|
|
626
|
+
resource: ResourceInfoSchema.optional(),
|
|
627
|
+
accepted: PaymentRequirementsV2Schema,
|
|
628
|
+
payload: Any,
|
|
629
|
+
extensions: OptionalAny
|
|
630
|
+
});
|
|
631
|
+
var PaymentRequirementsSchema = import_zod.z.union([
|
|
632
|
+
PaymentRequirementsV1Schema,
|
|
633
|
+
PaymentRequirementsV2Schema
|
|
634
|
+
]);
|
|
635
|
+
var PaymentRequiredSchema = import_zod.z.discriminatedUnion("x402Version", [
|
|
636
|
+
PaymentRequiredV1Schema,
|
|
637
|
+
PaymentRequiredV2Schema
|
|
638
|
+
]);
|
|
639
|
+
var PaymentPayloadSchema = import_zod.z.discriminatedUnion("x402Version", [
|
|
640
|
+
PaymentPayloadV1Schema,
|
|
641
|
+
PaymentPayloadV2Schema
|
|
642
|
+
]);
|
|
643
|
+
|
|
644
|
+
// src/http/httpFacilitatorClient.ts
|
|
645
|
+
var verifyResponseSchema = import_zod2.z.object({
|
|
646
|
+
isValid: import_zod2.z.boolean(),
|
|
647
|
+
invalidReason: import_zod2.z.string().nullish().transform((v) => v ?? void 0),
|
|
648
|
+
invalidMessage: import_zod2.z.string().nullish().transform((v) => v ?? void 0),
|
|
649
|
+
payer: import_zod2.z.string().nullish().transform((v) => v ?? void 0),
|
|
650
|
+
extensions: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()).nullish().transform((v) => v ?? void 0),
|
|
651
|
+
extra: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()).nullish().transform((v) => v ?? void 0)
|
|
652
|
+
});
|
|
653
|
+
var settleResponseSchema = import_zod2.z.object({
|
|
654
|
+
success: import_zod2.z.boolean(),
|
|
655
|
+
errorReason: import_zod2.z.string().nullish().transform((v) => v ?? void 0),
|
|
656
|
+
errorMessage: import_zod2.z.string().nullish().transform((v) => v ?? void 0),
|
|
657
|
+
payer: import_zod2.z.string().nullish().transform((v) => v ?? void 0),
|
|
658
|
+
transaction: import_zod2.z.string(),
|
|
659
|
+
network: import_zod2.z.custom((value) => typeof value === "string"),
|
|
660
|
+
amount: import_zod2.z.string().nullish().transform((v) => v ?? void 0),
|
|
661
|
+
extensions: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()).nullish().transform((v) => v ?? void 0),
|
|
662
|
+
extra: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()).nullish().transform((v) => v ?? void 0)
|
|
663
|
+
});
|
|
664
|
+
var supportedKindSchema = import_zod2.z.object({
|
|
665
|
+
x402Version: import_zod2.z.number(),
|
|
666
|
+
scheme: import_zod2.z.string(),
|
|
667
|
+
network: import_zod2.z.custom(
|
|
668
|
+
(value) => typeof value === "string"
|
|
669
|
+
),
|
|
670
|
+
extra: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()).nullish().transform((v) => v ?? void 0)
|
|
671
|
+
});
|
|
672
|
+
var supportedResponseSchema = import_zod2.z.object({
|
|
673
|
+
kinds: import_zod2.z.array(supportedKindSchema),
|
|
674
|
+
extensions: import_zod2.z.array(import_zod2.z.string()).default([]),
|
|
675
|
+
signers: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.array(import_zod2.z.string())).default({})
|
|
676
|
+
});
|
|
677
|
+
|
|
678
|
+
// src/http/index.ts
|
|
679
|
+
function encodePaymentSignatureHeader(paymentPayload) {
|
|
680
|
+
return safeBase64Encode(JSON.stringify(paymentPayload));
|
|
681
|
+
}
|
|
682
|
+
function decodePaymentRequiredHeader(paymentRequiredHeader) {
|
|
683
|
+
if (!Base64EncodedRegex.test(paymentRequiredHeader)) {
|
|
684
|
+
throw new Error("Invalid payment required header");
|
|
685
|
+
}
|
|
686
|
+
return JSON.parse(safeBase64Decode(paymentRequiredHeader));
|
|
687
|
+
}
|
|
688
|
+
function decodePaymentResponseHeader(paymentResponseHeader) {
|
|
689
|
+
if (!Base64EncodedRegex.test(paymentResponseHeader)) {
|
|
690
|
+
throw new Error("Invalid payment response header");
|
|
691
|
+
}
|
|
692
|
+
return JSON.parse(safeBase64Decode(paymentResponseHeader));
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
// src/http/x402HTTPClient.ts
|
|
696
|
+
var x402HTTPClient = class {
|
|
697
|
+
/**
|
|
698
|
+
* Creates a new x402HTTPClient instance.
|
|
699
|
+
*
|
|
700
|
+
* @param client - The underlying x402Client for payment logic
|
|
701
|
+
*/
|
|
702
|
+
constructor(client) {
|
|
703
|
+
this.client = client;
|
|
704
|
+
this.paymentRequiredHooks = [];
|
|
705
|
+
}
|
|
706
|
+
/**
|
|
707
|
+
* Register a hook to handle 402 responses before payment.
|
|
708
|
+
* Hooks run in order; first to return headers wins.
|
|
709
|
+
*
|
|
710
|
+
* @param hook - The hook function to register
|
|
711
|
+
* @returns This instance for chaining
|
|
712
|
+
*/
|
|
713
|
+
onPaymentRequired(hook) {
|
|
714
|
+
this.paymentRequiredHooks.push(hook);
|
|
715
|
+
return this;
|
|
716
|
+
}
|
|
717
|
+
/**
|
|
718
|
+
* Run hooks and return headers if any hook provides them.
|
|
719
|
+
*
|
|
720
|
+
* @param paymentRequired - The payment required response from the server
|
|
721
|
+
* @returns Headers to use for retry, or null to proceed to payment
|
|
722
|
+
*/
|
|
723
|
+
async handlePaymentRequired(paymentRequired) {
|
|
724
|
+
for (const hook of this.getPaymentRequiredHooks(paymentRequired)) {
|
|
725
|
+
const result = await hook({ paymentRequired });
|
|
726
|
+
if (result?.headers) {
|
|
727
|
+
return result.headers;
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
return null;
|
|
731
|
+
}
|
|
732
|
+
/**
|
|
733
|
+
* Encodes a payment payload into appropriate HTTP headers based on version.
|
|
734
|
+
*
|
|
735
|
+
* @param paymentPayload - The payment payload to encode
|
|
736
|
+
* @returns HTTP headers containing the encoded payment signature
|
|
737
|
+
*/
|
|
738
|
+
encodePaymentSignatureHeader(paymentPayload) {
|
|
739
|
+
switch (paymentPayload.x402Version) {
|
|
740
|
+
case 2:
|
|
741
|
+
return {
|
|
742
|
+
"PAYMENT-SIGNATURE": encodePaymentSignatureHeader(paymentPayload)
|
|
743
|
+
};
|
|
744
|
+
case 1:
|
|
745
|
+
return {
|
|
746
|
+
"X-PAYMENT": encodePaymentSignatureHeader(paymentPayload)
|
|
747
|
+
};
|
|
748
|
+
default:
|
|
749
|
+
throw new Error(
|
|
750
|
+
`Unsupported x402 version: ${paymentPayload.x402Version}`
|
|
751
|
+
);
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* Extracts payment required information from HTTP response.
|
|
756
|
+
*
|
|
757
|
+
* @param getHeader - Function to retrieve header value by name (case-insensitive)
|
|
758
|
+
* @param body - Optional response body for v1 compatibility
|
|
759
|
+
* @returns The payment required object
|
|
760
|
+
*/
|
|
761
|
+
getPaymentRequiredResponse(getHeader, body) {
|
|
762
|
+
const paymentRequired = getHeader("PAYMENT-REQUIRED");
|
|
763
|
+
if (paymentRequired) {
|
|
764
|
+
return decodePaymentRequiredHeader(paymentRequired);
|
|
765
|
+
}
|
|
766
|
+
if (body && body instanceof Object && "x402Version" in body && body.x402Version === 1) {
|
|
767
|
+
return body;
|
|
768
|
+
}
|
|
769
|
+
throw new Error("Invalid payment required response");
|
|
770
|
+
}
|
|
771
|
+
/**
|
|
772
|
+
* Extracts payment settlement response from HTTP headers.
|
|
773
|
+
*
|
|
774
|
+
* @param getHeader - Function to retrieve header value by name (case-insensitive)
|
|
775
|
+
* @returns The settlement response object
|
|
776
|
+
*/
|
|
777
|
+
getPaymentSettleResponse(getHeader) {
|
|
778
|
+
const paymentResponse = getHeader("PAYMENT-RESPONSE");
|
|
779
|
+
if (paymentResponse) {
|
|
780
|
+
return decodePaymentResponseHeader(paymentResponse);
|
|
781
|
+
}
|
|
782
|
+
const xPaymentResponse = getHeader("X-PAYMENT-RESPONSE");
|
|
783
|
+
if (xPaymentResponse) {
|
|
784
|
+
return decodePaymentResponseHeader(xPaymentResponse);
|
|
785
|
+
}
|
|
786
|
+
throw new Error("Payment response header not found");
|
|
787
|
+
}
|
|
788
|
+
/**
|
|
789
|
+
* Creates a payment payload for the given payment requirements.
|
|
790
|
+
* Delegates to the underlying x402Client.
|
|
791
|
+
*
|
|
792
|
+
* @param paymentRequired - The payment required response from the server
|
|
793
|
+
* @returns Promise resolving to the payment payload
|
|
794
|
+
*/
|
|
795
|
+
async createPaymentPayload(paymentRequired) {
|
|
796
|
+
return this.client.createPaymentPayload(paymentRequired);
|
|
797
|
+
}
|
|
798
|
+
/**
|
|
799
|
+
* Parses response headers into protocol types, fires payment response hooks (v2 only),
|
|
800
|
+
* and returns whether a hook signaled recovery.
|
|
801
|
+
*
|
|
802
|
+
* Called by transport wrappers (fetch, axios) after the paid request completes.
|
|
803
|
+
*
|
|
804
|
+
* @param paymentPayload - The payload that was sent with the request
|
|
805
|
+
* @param getHeader - Function to retrieve a response header by name
|
|
806
|
+
* @param status - The HTTP status code of the response
|
|
807
|
+
* @returns Whether a hook recovered and the parsed settle response (if any)
|
|
808
|
+
*/
|
|
809
|
+
async processPaymentResult(paymentPayload, getHeader, status) {
|
|
810
|
+
let settleResponse;
|
|
811
|
+
try {
|
|
812
|
+
settleResponse = this.getPaymentSettleResponse(getHeader);
|
|
813
|
+
} catch {
|
|
814
|
+
}
|
|
815
|
+
if (paymentPayload.x402Version === 1) {
|
|
816
|
+
return { recovered: false, settleResponse };
|
|
817
|
+
}
|
|
818
|
+
let paymentRequired;
|
|
819
|
+
if (!settleResponse && status === 402) {
|
|
820
|
+
try {
|
|
821
|
+
paymentRequired = this.getPaymentRequiredResponse(getHeader);
|
|
822
|
+
} catch {
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
const requirements = paymentPayload.accepted;
|
|
826
|
+
if (!requirements) {
|
|
827
|
+
throw new Error("Invalid x402 v2 payment payload: missing `accepted`");
|
|
828
|
+
}
|
|
829
|
+
const ctx = {
|
|
830
|
+
paymentPayload,
|
|
831
|
+
requirements,
|
|
832
|
+
...settleResponse ? { settleResponse } : {},
|
|
833
|
+
...paymentRequired ? { paymentRequired } : {}
|
|
834
|
+
};
|
|
835
|
+
const result = await this.client.handlePaymentResponse(ctx);
|
|
836
|
+
return { recovered: result?.recovered === true, settleResponse };
|
|
837
|
+
}
|
|
838
|
+
/**
|
|
839
|
+
* Parses HTTP status, headers, and body into an `HTTPResourceResponse`.
|
|
840
|
+
*
|
|
841
|
+
* Decodes the x402 payment header into `header`: the `PAYMENT-RESPONSE`
|
|
842
|
+
* settlement if present, otherwise the `PAYMENT-REQUIRED` declaration on
|
|
843
|
+
* 402 responses (whose `error` field carries the server's failure reason).
|
|
844
|
+
*
|
|
845
|
+
* @param args - Normalized response inputs from any HTTP transport
|
|
846
|
+
* @param args.status - HTTP response status code
|
|
847
|
+
* @param args.getHeader - Callback to read response headers by name
|
|
848
|
+
* @param args.body - Response body payload
|
|
849
|
+
* @returns The parsed status, body, and decoded payment header
|
|
850
|
+
*/
|
|
851
|
+
parsePaymentResult(args) {
|
|
852
|
+
const { status, getHeader, body } = args;
|
|
853
|
+
let header;
|
|
854
|
+
try {
|
|
855
|
+
header = this.getPaymentSettleResponse(getHeader);
|
|
856
|
+
} catch {
|
|
857
|
+
if (status === 402) {
|
|
858
|
+
try {
|
|
859
|
+
header = this.getPaymentRequiredResponse(getHeader, body);
|
|
860
|
+
} catch {
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
let paymentStatus = "none";
|
|
865
|
+
if (header && !("success" in header)) {
|
|
866
|
+
paymentStatus = "payment_required";
|
|
867
|
+
}
|
|
868
|
+
if (header && "success" in header) {
|
|
869
|
+
paymentStatus = header.success ? "settled" : "settle_failed";
|
|
870
|
+
}
|
|
871
|
+
return { status, paymentStatus, body, header };
|
|
872
|
+
}
|
|
873
|
+
/**
|
|
874
|
+
* Parses a fetch Response into an `HTTPResourceResponse` for app-level convenience.
|
|
875
|
+
*
|
|
876
|
+
* @param response - The fetch Response to process
|
|
877
|
+
* @returns The parsed status, body, and decoded payment header
|
|
878
|
+
*/
|
|
879
|
+
async processResponse(response) {
|
|
880
|
+
const getHeader = (name) => response.headers.get(name);
|
|
881
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
882
|
+
const body = contentType.includes("application/json") ? await response.json() : await response.text();
|
|
883
|
+
return this.parsePaymentResult({ status: response.status, getHeader, body });
|
|
884
|
+
}
|
|
885
|
+
/**
|
|
886
|
+
* Manual HTTP hooks run before extension hooks scoped to the 402 response.
|
|
887
|
+
*
|
|
888
|
+
* @param paymentRequired - The payment required response from the server
|
|
889
|
+
* @returns Hooks in invocation order
|
|
890
|
+
*/
|
|
891
|
+
getPaymentRequiredHooks(paymentRequired) {
|
|
892
|
+
const hooks = [...this.paymentRequiredHooks];
|
|
893
|
+
const declaredExtensions = paymentRequired.extensions;
|
|
894
|
+
if (!declaredExtensions) return hooks;
|
|
895
|
+
for (const extension of this.client.getExtensions()) {
|
|
896
|
+
const httpExtension = extension;
|
|
897
|
+
const hook = httpExtension.transportHooks?.http?.onPaymentRequired;
|
|
898
|
+
if (!hook || !(extension.key in declaredExtensions)) continue;
|
|
899
|
+
hooks.push((context) => hook(declaredExtensions[extension.key], context));
|
|
900
|
+
}
|
|
901
|
+
return hooks;
|
|
902
|
+
}
|
|
903
|
+
};
|
|
904
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
905
|
+
0 && (module.exports = {
|
|
906
|
+
x402Client,
|
|
907
|
+
x402HTTPClient
|
|
908
|
+
});
|
|
909
|
+
//# sourceMappingURL=index.js.map
|