@okxweb3/app-x402-core 0.1.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.
Files changed (66) hide show
  1. package/README.md +267 -0
  2. package/dist/cjs/OKXFacilitatorClient-BvyQB1QM.d.ts +59 -0
  3. package/dist/cjs/client/index.d.ts +320 -0
  4. package/dist/cjs/client/index.js +564 -0
  5. package/dist/cjs/client/index.js.map +1 -0
  6. package/dist/cjs/facilitator/index.d.ts +198 -0
  7. package/dist/cjs/facilitator/index.js +533 -0
  8. package/dist/cjs/facilitator/index.js.map +1 -0
  9. package/dist/cjs/http/index.d.ts +51 -0
  10. package/dist/cjs/http/index.js +1226 -0
  11. package/dist/cjs/http/index.js.map +1 -0
  12. package/dist/cjs/index.d.ts +6 -0
  13. package/dist/cjs/index.js +155 -0
  14. package/dist/cjs/index.js.map +1 -0
  15. package/dist/cjs/mechanisms-sojpSwWW.d.ts +763 -0
  16. package/dist/cjs/schemas/index.d.ts +309 -0
  17. package/dist/cjs/schemas/index.js +127 -0
  18. package/dist/cjs/schemas/index.js.map +1 -0
  19. package/dist/cjs/server/index.d.ts +2 -0
  20. package/dist/cjs/server/index.js +1880 -0
  21. package/dist/cjs/server/index.js.map +1 -0
  22. package/dist/cjs/types/index.d.ts +1 -0
  23. package/dist/cjs/types/index.js +97 -0
  24. package/dist/cjs/types/index.js.map +1 -0
  25. package/dist/cjs/utils/index.d.ts +48 -0
  26. package/dist/cjs/utils/index.js +116 -0
  27. package/dist/cjs/utils/index.js.map +1 -0
  28. package/dist/cjs/x402HTTPResourceServer-CcsAkcgI.d.ts +466 -0
  29. package/dist/esm/OKXFacilitatorClient-D5E3LX50.d.mts +59 -0
  30. package/dist/esm/chunk-CAXWAW23.mjs +68 -0
  31. package/dist/esm/chunk-CAXWAW23.mjs.map +1 -0
  32. package/dist/esm/chunk-CS33MEMU.mjs +86 -0
  33. package/dist/esm/chunk-CS33MEMU.mjs.map +1 -0
  34. package/dist/esm/chunk-O3IYMTNT.mjs +118 -0
  35. package/dist/esm/chunk-O3IYMTNT.mjs.map +1 -0
  36. package/dist/esm/chunk-TDLQZ6MP.mjs +86 -0
  37. package/dist/esm/chunk-TDLQZ6MP.mjs.map +1 -0
  38. package/dist/esm/chunk-XBQG2CDV.mjs +1792 -0
  39. package/dist/esm/chunk-XBQG2CDV.mjs.map +1 -0
  40. package/dist/esm/client/index.d.mts +320 -0
  41. package/dist/esm/client/index.mjs +318 -0
  42. package/dist/esm/client/index.mjs.map +1 -0
  43. package/dist/esm/facilitator/index.d.mts +198 -0
  44. package/dist/esm/facilitator/index.mjs +387 -0
  45. package/dist/esm/facilitator/index.mjs.map +1 -0
  46. package/dist/esm/http/index.d.mts +51 -0
  47. package/dist/esm/http/index.mjs +34 -0
  48. package/dist/esm/http/index.mjs.map +1 -0
  49. package/dist/esm/index.d.mts +6 -0
  50. package/dist/esm/index.mjs +9 -0
  51. package/dist/esm/index.mjs.map +1 -0
  52. package/dist/esm/mechanisms-sojpSwWW.d.mts +763 -0
  53. package/dist/esm/schemas/index.d.mts +309 -0
  54. package/dist/esm/schemas/index.mjs +41 -0
  55. package/dist/esm/schemas/index.mjs.map +1 -0
  56. package/dist/esm/server/index.d.mts +2 -0
  57. package/dist/esm/server/index.mjs +28 -0
  58. package/dist/esm/server/index.mjs.map +1 -0
  59. package/dist/esm/types/index.d.mts +1 -0
  60. package/dist/esm/types/index.mjs +13 -0
  61. package/dist/esm/types/index.mjs.map +1 -0
  62. package/dist/esm/utils/index.d.mts +48 -0
  63. package/dist/esm/utils/index.mjs +19 -0
  64. package/dist/esm/utils/index.mjs.map +1 -0
  65. package/dist/esm/x402HTTPResourceServer-DBeutKxq.d.mts +466 -0
  66. package/package.json +121 -0
@@ -0,0 +1,564 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/client/index.ts
31
+ var client_exports = {};
32
+ __export(client_exports, {
33
+ x402Client: () => x402Client,
34
+ x402HTTPClient: () => x402HTTPClient
35
+ });
36
+ module.exports = __toCommonJS(client_exports);
37
+
38
+ // src/facilitator/OKXFacilitatorClient.ts
39
+ var import_node_crypto = __toESM(require("crypto"));
40
+
41
+ // src/index.ts
42
+ var x402Version = 2;
43
+
44
+ // src/utils/index.ts
45
+ var findSchemesByNetwork = (map, network) => {
46
+ let implementationsByScheme = map.get(network);
47
+ if (!implementationsByScheme) {
48
+ for (const [registeredNetworkPattern, implementations] of map.entries()) {
49
+ const pattern = registeredNetworkPattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\*/g, ".*");
50
+ const regex = new RegExp(`^${pattern}$`);
51
+ if (regex.test(network)) {
52
+ implementationsByScheme = implementations;
53
+ break;
54
+ }
55
+ }
56
+ }
57
+ return implementationsByScheme;
58
+ };
59
+ var findByNetworkAndScheme = (map, scheme, network) => {
60
+ return findSchemesByNetwork(map, network)?.get(scheme);
61
+ };
62
+ var Base64EncodedRegex = /^[A-Za-z0-9+/]*={0,2}$/;
63
+ function safeBase64Encode(data) {
64
+ if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") {
65
+ const bytes = new TextEncoder().encode(data);
66
+ const binaryString = Array.from(bytes, (byte) => String.fromCharCode(byte)).join("");
67
+ return globalThis.btoa(binaryString);
68
+ }
69
+ return Buffer.from(data, "utf8").toString("base64");
70
+ }
71
+ function safeBase64Decode(data) {
72
+ if (typeof globalThis !== "undefined" && typeof globalThis.atob === "function") {
73
+ const binaryString = globalThis.atob(data);
74
+ const bytes = new Uint8Array(binaryString.length);
75
+ for (let i = 0; i < binaryString.length; i++) {
76
+ bytes[i] = binaryString.charCodeAt(i);
77
+ }
78
+ const decoder = new TextDecoder("utf-8");
79
+ return decoder.decode(bytes);
80
+ }
81
+ return Buffer.from(data, "base64").toString("utf-8");
82
+ }
83
+
84
+ // src/client/x402Client.ts
85
+ var x402Client = class _x402Client {
86
+ /**
87
+ * Creates a new x402Client instance.
88
+ *
89
+ * @param paymentRequirementsSelector - Function to select payment requirements from available options
90
+ */
91
+ constructor(paymentRequirementsSelector) {
92
+ this.registeredClientSchemes = /* @__PURE__ */ new Map();
93
+ this.policies = [];
94
+ this.registeredExtensions = /* @__PURE__ */ new Map();
95
+ this.beforePaymentCreationHooks = [];
96
+ this.afterPaymentCreationHooks = [];
97
+ this.onPaymentCreationFailureHooks = [];
98
+ this.paymentRequirementsSelector = paymentRequirementsSelector || ((x402Version2, accepts) => accepts[0]);
99
+ }
100
+ /**
101
+ * Creates a new x402Client instance from a configuration object.
102
+ *
103
+ * @param config - The client configuration including schemes, policies, and payment requirements selector
104
+ * @returns A configured x402Client instance
105
+ */
106
+ static fromConfig(config) {
107
+ const client = new _x402Client(config.paymentRequirementsSelector);
108
+ config.schemes.forEach((scheme) => {
109
+ client.register(scheme.network, scheme.client);
110
+ });
111
+ config.policies?.forEach((policy) => {
112
+ client.registerPolicy(policy);
113
+ });
114
+ return client;
115
+ }
116
+ /**
117
+ * Registers a scheme client for the current x402 version.
118
+ *
119
+ * @param network - The network to register the client for
120
+ * @param client - The scheme network client to register
121
+ * @returns The x402Client instance for chaining
122
+ */
123
+ register(network, client) {
124
+ return this._registerScheme(x402Version, 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
+ * Registers a client extension that can enrich payment payloads.
154
+ *
155
+ * Extensions are invoked after the scheme creates the base payload and the
156
+ * payload is wrapped with extensions/resource/accepted data. If the extension's
157
+ * key is present in `paymentRequired.extensions`, the extension's
158
+ * `enrichPaymentPayload` hook is called to modify the payload.
159
+ *
160
+ * @param extension - The client extension to register
161
+ * @returns The x402Client instance for chaining
162
+ */
163
+ registerExtension(extension) {
164
+ this.registeredExtensions.set(extension.key, extension);
165
+ return this;
166
+ }
167
+ /**
168
+ * Register a hook to execute before payment payload creation.
169
+ * Can abort creation by returning { abort: true, reason: string }
170
+ *
171
+ * @param hook - The hook function to register
172
+ * @returns The x402Client instance for chaining
173
+ */
174
+ onBeforePaymentCreation(hook) {
175
+ this.beforePaymentCreationHooks.push(hook);
176
+ return this;
177
+ }
178
+ /**
179
+ * Register a hook to execute after successful payment payload creation.
180
+ *
181
+ * @param hook - The hook function to register
182
+ * @returns The x402Client instance for chaining
183
+ */
184
+ onAfterPaymentCreation(hook) {
185
+ this.afterPaymentCreationHooks.push(hook);
186
+ return this;
187
+ }
188
+ /**
189
+ * Register a hook to execute when payment payload creation fails.
190
+ * Can recover from failure by returning { recovered: true, payload: PaymentPayload }
191
+ *
192
+ * @param hook - The hook function to register
193
+ * @returns The x402Client instance for chaining
194
+ */
195
+ onPaymentCreationFailure(hook) {
196
+ this.onPaymentCreationFailureHooks.push(hook);
197
+ return this;
198
+ }
199
+ /**
200
+ * Creates a payment payload based on a PaymentRequired response.
201
+ *
202
+ * Automatically extracts x402Version, resource, and extensions from the PaymentRequired
203
+ * response and constructs a complete PaymentPayload with the accepted requirements.
204
+ *
205
+ * @param paymentRequired - The PaymentRequired response from the server
206
+ * @returns Promise resolving to the complete payment payload
207
+ */
208
+ async createPaymentPayload(paymentRequired) {
209
+ const clientSchemesByNetwork = this.registeredClientSchemes.get(paymentRequired.x402Version);
210
+ if (!clientSchemesByNetwork) {
211
+ throw new Error(`No client registered for x402 version: ${paymentRequired.x402Version}`);
212
+ }
213
+ const requirements = this.selectPaymentRequirements(paymentRequired.x402Version, paymentRequired.accepts);
214
+ const context = {
215
+ paymentRequired,
216
+ selectedRequirements: requirements
217
+ };
218
+ for (const hook of this.beforePaymentCreationHooks) {
219
+ const result = await hook(context);
220
+ if (result && "abort" in result && result.abort) {
221
+ throw new Error(`Payment creation aborted: ${result.reason}`);
222
+ }
223
+ }
224
+ try {
225
+ const schemeNetworkClient = findByNetworkAndScheme(clientSchemesByNetwork, requirements.scheme, requirements.network);
226
+ if (!schemeNetworkClient) {
227
+ throw new Error(`No client registered for scheme: ${requirements.scheme} and network: ${requirements.network}`);
228
+ }
229
+ const partialPayload = await schemeNetworkClient.createPaymentPayload(
230
+ paymentRequired.x402Version,
231
+ requirements,
232
+ { extensions: paymentRequired.extensions }
233
+ );
234
+ const mergedExtensions = this.mergeExtensions(
235
+ paymentRequired.extensions,
236
+ partialPayload.extensions
237
+ );
238
+ const acceptedRequirements = partialPayload.acceptedExtraOverrides && Object.keys(partialPayload.acceptedExtraOverrides).length > 0 ? {
239
+ ...requirements,
240
+ extra: {
241
+ ...requirements.extra,
242
+ ...partialPayload.acceptedExtraOverrides
243
+ }
244
+ } : requirements;
245
+ let paymentPayload = {
246
+ x402Version: partialPayload.x402Version,
247
+ payload: partialPayload.payload,
248
+ extensions: mergedExtensions,
249
+ resource: paymentRequired.resource,
250
+ accepted: acceptedRequirements
251
+ };
252
+ paymentPayload = await this.enrichPaymentPayloadWithExtensions(paymentPayload, paymentRequired);
253
+ const createdContext = {
254
+ ...context,
255
+ paymentPayload
256
+ };
257
+ for (const hook of this.afterPaymentCreationHooks) {
258
+ await hook(createdContext);
259
+ }
260
+ return paymentPayload;
261
+ } catch (error) {
262
+ const failureContext = {
263
+ ...context,
264
+ error
265
+ };
266
+ for (const hook of this.onPaymentCreationFailureHooks) {
267
+ const result = await hook(failureContext);
268
+ if (result && "recovered" in result && result.recovered) {
269
+ return result.payload;
270
+ }
271
+ }
272
+ throw error;
273
+ }
274
+ }
275
+ /**
276
+ * Merges server-declared extensions with scheme-provided extensions.
277
+ * Scheme extensions overlay on top of server extensions at each key,
278
+ * preserving server-provided schema while overlaying scheme-provided info.
279
+ *
280
+ * @param serverExtensions - Extensions declared by the server in the 402 response
281
+ * @param schemeExtensions - Extensions provided by the scheme client (e.g. EIP-2612)
282
+ * @returns The merged extensions object, or undefined if both inputs are undefined
283
+ */
284
+ mergeExtensions(serverExtensions, schemeExtensions) {
285
+ if (!schemeExtensions) return serverExtensions;
286
+ if (!serverExtensions) return schemeExtensions;
287
+ const merged = { ...serverExtensions };
288
+ for (const [key, schemeValue] of Object.entries(schemeExtensions)) {
289
+ const serverValue = merged[key];
290
+ if (serverValue && typeof serverValue === "object" && schemeValue && typeof schemeValue === "object") {
291
+ merged[key] = { ...serverValue, ...schemeValue };
292
+ } else {
293
+ merged[key] = schemeValue;
294
+ }
295
+ }
296
+ return merged;
297
+ }
298
+ /**
299
+ * Enriches a payment payload by calling registered extension hooks.
300
+ * For each extension key present in the PaymentRequired response,
301
+ * invokes the corresponding extension's enrichPaymentPayload callback.
302
+ *
303
+ * @param paymentPayload - The payment payload to enrich with extension data
304
+ * @param paymentRequired - The PaymentRequired response containing extension declarations
305
+ * @returns The enriched payment payload with extension data applied
306
+ */
307
+ async enrichPaymentPayloadWithExtensions(paymentPayload, paymentRequired) {
308
+ if (!paymentRequired.extensions || this.registeredExtensions.size === 0) {
309
+ return paymentPayload;
310
+ }
311
+ let enriched = paymentPayload;
312
+ for (const [key, extension] of this.registeredExtensions) {
313
+ if (key in paymentRequired.extensions && extension.enrichPaymentPayload) {
314
+ enriched = await extension.enrichPaymentPayload(enriched, paymentRequired);
315
+ }
316
+ }
317
+ return enriched;
318
+ }
319
+ /**
320
+ * Selects appropriate payment requirements based on registered clients and policies.
321
+ *
322
+ * Selection process:
323
+ * 1. Filter by registered schemes (network + scheme support)
324
+ * 2. Apply all registered policies in order
325
+ * 3. Use selector to choose final requirement
326
+ *
327
+ * @param x402Version - The x402 protocol version
328
+ * @param paymentRequirements - Array of available payment requirements
329
+ * @returns The selected payment requirements
330
+ */
331
+ selectPaymentRequirements(x402Version2, paymentRequirements) {
332
+ const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version2);
333
+ if (!clientSchemesByNetwork) {
334
+ throw new Error(`No client registered for x402 version: ${x402Version2}`);
335
+ }
336
+ const supportedPaymentRequirements = paymentRequirements.filter((requirement) => {
337
+ let clientSchemes = findSchemesByNetwork(clientSchemesByNetwork, requirement.network);
338
+ if (!clientSchemes) {
339
+ return false;
340
+ }
341
+ return clientSchemes.has(requirement.scheme);
342
+ });
343
+ if (supportedPaymentRequirements.length === 0) {
344
+ throw new Error(`No network/scheme registered for x402 version: ${x402Version2} which comply with the payment requirements. ${JSON.stringify({
345
+ x402Version: x402Version2,
346
+ paymentRequirements,
347
+ x402Versions: Array.from(this.registeredClientSchemes.keys()),
348
+ networks: Array.from(clientSchemesByNetwork.keys()),
349
+ schemes: Array.from(clientSchemesByNetwork.values()).map((schemes) => Array.from(schemes.keys())).flat()
350
+ })}`);
351
+ }
352
+ let filteredRequirements = supportedPaymentRequirements;
353
+ for (const policy of this.policies) {
354
+ filteredRequirements = policy(x402Version2, filteredRequirements);
355
+ if (filteredRequirements.length === 0) {
356
+ throw new Error(`All payment requirements were filtered out by policies for x402 version: ${x402Version2}`);
357
+ }
358
+ }
359
+ return this.paymentRequirementsSelector(x402Version2, filteredRequirements);
360
+ }
361
+ /**
362
+ * Internal method to register a scheme client.
363
+ *
364
+ * @param x402Version - The x402 protocol version
365
+ * @param network - The network to register the client for
366
+ * @param client - The scheme network client to register
367
+ * @returns The x402Client instance for chaining
368
+ */
369
+ _registerScheme(x402Version2, network, client) {
370
+ if (!this.registeredClientSchemes.has(x402Version2)) {
371
+ this.registeredClientSchemes.set(x402Version2, /* @__PURE__ */ new Map());
372
+ }
373
+ const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version2);
374
+ if (!clientSchemesByNetwork.has(network)) {
375
+ clientSchemesByNetwork.set(network, /* @__PURE__ */ new Map());
376
+ }
377
+ const clientByScheme = clientSchemesByNetwork.get(network);
378
+ if (!clientByScheme.has(client.scheme)) {
379
+ clientByScheme.set(client.scheme, client);
380
+ }
381
+ return this;
382
+ }
383
+ };
384
+
385
+ // src/schemas/index.ts
386
+ var import_zod = require("zod");
387
+ var import_zod2 = require("zod");
388
+ var NonEmptyString = import_zod.z.string().min(1);
389
+ var Any = import_zod.z.record(import_zod.z.unknown());
390
+ var OptionalAny = import_zod.z.record(import_zod.z.unknown()).optional().nullable();
391
+ var NetworkSchema = import_zod.z.string().min(3).refine((val) => val.includes(":"), {
392
+ message: "Network must be in CAIP-2 format (e.g., 'eip155:196')"
393
+ });
394
+ var ResourceInfoSchema = import_zod.z.object({
395
+ url: NonEmptyString,
396
+ description: import_zod.z.string().optional(),
397
+ mimeType: import_zod.z.string().optional()
398
+ });
399
+ var PaymentRequirementsSchema = import_zod.z.object({
400
+ scheme: NonEmptyString,
401
+ network: NetworkSchema,
402
+ amount: NonEmptyString,
403
+ asset: NonEmptyString,
404
+ payTo: NonEmptyString,
405
+ maxTimeoutSeconds: import_zod.z.number().positive(),
406
+ extra: OptionalAny
407
+ });
408
+ var PaymentRequiredSchema = import_zod.z.object({
409
+ x402Version: import_zod.z.literal(2),
410
+ error: import_zod.z.string().optional(),
411
+ resource: ResourceInfoSchema,
412
+ accepts: import_zod.z.array(PaymentRequirementsSchema).min(1),
413
+ extensions: OptionalAny
414
+ });
415
+ var PaymentPayloadSchema = import_zod.z.object({
416
+ x402Version: import_zod.z.literal(2),
417
+ resource: ResourceInfoSchema.optional(),
418
+ accepted: PaymentRequirementsSchema,
419
+ payload: Any,
420
+ extensions: OptionalAny
421
+ });
422
+
423
+ // src/http/httpFacilitatorClient.ts
424
+ var verifyResponseSchema = import_zod2.z.object({
425
+ isValid: import_zod2.z.boolean(),
426
+ invalidReason: import_zod2.z.string().nullish().transform((v) => v ?? void 0),
427
+ invalidMessage: import_zod2.z.string().nullish().transform((v) => v ?? void 0),
428
+ payer: import_zod2.z.string().nullish().transform((v) => v ?? void 0),
429
+ extensions: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()).nullish().transform((v) => v ?? void 0)
430
+ });
431
+ var settleResponseSchema = import_zod2.z.object({
432
+ success: import_zod2.z.boolean(),
433
+ // OKX extension: pending (async), success (immediate), timeout (on-chain timed out)
434
+ status: import_zod2.z.enum(["pending", "success", "timeout"]).nullish().transform((v) => v ?? void 0).optional(),
435
+ errorReason: import_zod2.z.string().nullish().transform((v) => v ?? void 0),
436
+ errorMessage: import_zod2.z.string().nullish().transform((v) => v ?? void 0),
437
+ payer: import_zod2.z.string().nullish().transform((v) => v ?? void 0),
438
+ transaction: import_zod2.z.string(),
439
+ network: import_zod2.z.custom((value) => typeof value === "string"),
440
+ amount: import_zod2.z.string().nullish().transform((v) => v ?? void 0),
441
+ extensions: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()).nullish().transform((v) => v ?? void 0)
442
+ });
443
+ var supportedKindSchema = import_zod2.z.object({
444
+ x402Version: import_zod2.z.number(),
445
+ scheme: import_zod2.z.string(),
446
+ network: import_zod2.z.custom(
447
+ (value) => typeof value === "string"
448
+ ),
449
+ extra: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()).nullish().transform((v) => v ?? void 0)
450
+ });
451
+ var supportedResponseSchema = import_zod2.z.object({
452
+ kinds: import_zod2.z.array(supportedKindSchema),
453
+ extensions: import_zod2.z.array(import_zod2.z.string()).default([]),
454
+ signers: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.array(import_zod2.z.string())).default({})
455
+ });
456
+
457
+ // src/http/index.ts
458
+ function encodePaymentSignatureHeader(paymentPayload) {
459
+ return safeBase64Encode(JSON.stringify(paymentPayload));
460
+ }
461
+ function decodePaymentRequiredHeader(paymentRequiredHeader) {
462
+ if (!Base64EncodedRegex.test(paymentRequiredHeader)) {
463
+ throw new Error("Invalid payment required header");
464
+ }
465
+ return JSON.parse(safeBase64Decode(paymentRequiredHeader));
466
+ }
467
+ function decodePaymentResponseHeader(paymentResponseHeader) {
468
+ if (!Base64EncodedRegex.test(paymentResponseHeader)) {
469
+ throw new Error("Invalid payment response header");
470
+ }
471
+ return JSON.parse(safeBase64Decode(paymentResponseHeader));
472
+ }
473
+
474
+ // src/http/x402HTTPClient.ts
475
+ var x402HTTPClient = class {
476
+ /**
477
+ * Creates a new x402HTTPClient instance.
478
+ *
479
+ * @param client - The underlying x402Client for payment logic
480
+ */
481
+ constructor(client) {
482
+ this.client = client;
483
+ this.paymentRequiredHooks = [];
484
+ }
485
+ /**
486
+ * Register a hook to handle 402 responses before payment.
487
+ * Hooks run in order; first to return headers wins.
488
+ *
489
+ * @param hook - The hook function to register
490
+ * @returns This instance for chaining
491
+ */
492
+ onPaymentRequired(hook) {
493
+ this.paymentRequiredHooks.push(hook);
494
+ return this;
495
+ }
496
+ /**
497
+ * Run hooks and return headers if any hook provides them.
498
+ *
499
+ * @param paymentRequired - The payment required response from the server
500
+ * @returns Headers to use for retry, or null to proceed to payment
501
+ */
502
+ async handlePaymentRequired(paymentRequired) {
503
+ for (const hook of this.paymentRequiredHooks) {
504
+ const result = await hook({ paymentRequired });
505
+ if (result?.headers) {
506
+ return result.headers;
507
+ }
508
+ }
509
+ return null;
510
+ }
511
+ /**
512
+ * Encodes a payment payload into appropriate HTTP headers based on version.
513
+ *
514
+ * @param paymentPayload - The payment payload to encode
515
+ * @returns HTTP headers containing the encoded payment signature
516
+ */
517
+ encodePaymentSignatureHeader(paymentPayload) {
518
+ return {
519
+ "PAYMENT-SIGNATURE": encodePaymentSignatureHeader(paymentPayload)
520
+ };
521
+ }
522
+ /**
523
+ * Extracts payment required information from HTTP response.
524
+ *
525
+ * @param getHeader - Function to retrieve header value by name (case-insensitive)
526
+ * @returns The payment required object
527
+ */
528
+ getPaymentRequiredResponse(getHeader) {
529
+ const paymentRequired = getHeader("PAYMENT-REQUIRED");
530
+ if (paymentRequired) {
531
+ return decodePaymentRequiredHeader(paymentRequired);
532
+ }
533
+ throw new Error("Invalid payment required response");
534
+ }
535
+ /**
536
+ * Extracts payment settlement response from HTTP headers.
537
+ *
538
+ * @param getHeader - Function to retrieve header value by name (case-insensitive)
539
+ * @returns The settlement response object
540
+ */
541
+ getPaymentSettleResponse(getHeader) {
542
+ const paymentResponse = getHeader("PAYMENT-RESPONSE");
543
+ if (paymentResponse) {
544
+ return decodePaymentResponseHeader(paymentResponse);
545
+ }
546
+ throw new Error("Payment response header not found");
547
+ }
548
+ /**
549
+ * Creates a payment payload for the given payment requirements.
550
+ * Delegates to the underlying x402Client.
551
+ *
552
+ * @param paymentRequired - The payment required response from the server
553
+ * @returns Promise resolving to the payment payload
554
+ */
555
+ async createPaymentPayload(paymentRequired) {
556
+ return this.client.createPaymentPayload(paymentRequired);
557
+ }
558
+ };
559
+ // Annotate the CommonJS export names for ESM import in node:
560
+ 0 && (module.exports = {
561
+ x402Client,
562
+ x402HTTPClient
563
+ });
564
+ //# sourceMappingURL=index.js.map