@bankofai/x402-core 2.6.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.
Files changed (74) hide show
  1. package/README.md +293 -0
  2. package/dist/cjs/assetRegistry-CL0zA4s0.d.ts +831 -0
  3. package/dist/cjs/assetRegistry-CRVM0KEs.d.ts +831 -0
  4. package/dist/cjs/client/index.d.ts +329 -0
  5. package/dist/cjs/client/index.js +712 -0
  6. package/dist/cjs/client/index.js.map +1 -0
  7. package/dist/cjs/facilitator/index.d.ts +206 -0
  8. package/dist/cjs/facilitator/index.js +625 -0
  9. package/dist/cjs/facilitator/index.js.map +1 -0
  10. package/dist/cjs/http/index.d.ts +51 -0
  11. package/dist/cjs/http/index.js +1178 -0
  12. package/dist/cjs/http/index.js.map +1 -0
  13. package/dist/cjs/index.d.ts +13 -0
  14. package/dist/cjs/index.js +250 -0
  15. package/dist/cjs/index.js.map +1 -0
  16. package/dist/cjs/mechanisms-q7I6xfUE.d.ts +726 -0
  17. package/dist/cjs/schemas/index.d.ts +825 -0
  18. package/dist/cjs/schemas/index.js +212 -0
  19. package/dist/cjs/schemas/index.js.map +1 -0
  20. package/dist/cjs/server/index.d.ts +2 -0
  21. package/dist/cjs/server/index.js +1782 -0
  22. package/dist/cjs/server/index.js.map +1 -0
  23. package/dist/cjs/types/index.d.ts +1 -0
  24. package/dist/cjs/types/index.js +72 -0
  25. package/dist/cjs/types/index.js.map +1 -0
  26. package/dist/cjs/types/v1/index.d.ts +1 -0
  27. package/dist/cjs/types/v1/index.js +19 -0
  28. package/dist/cjs/types/v1/index.js.map +1 -0
  29. package/dist/cjs/utils/index.d.ts +48 -0
  30. package/dist/cjs/utils/index.js +116 -0
  31. package/dist/cjs/utils/index.js.map +1 -0
  32. package/dist/cjs/x402HTTPResourceServer-BFVo1_74.d.ts +433 -0
  33. package/dist/cjs/x402HTTPResourceServer-DaU2yFzy.d.ts +434 -0
  34. package/dist/cjs/x402HTTPResourceServer-DswI2hZQ.d.ts +434 -0
  35. package/dist/esm/assetRegistry-CRVM0KEs.d.mts +831 -0
  36. package/dist/esm/chunk-BJTO5JO5.mjs +11 -0
  37. package/dist/esm/chunk-BJTO5JO5.mjs.map +1 -0
  38. package/dist/esm/chunk-DACUCTGT.mjs +891 -0
  39. package/dist/esm/chunk-DACUCTGT.mjs.map +1 -0
  40. package/dist/esm/chunk-DFUINDLZ.mjs +221 -0
  41. package/dist/esm/chunk-DFUINDLZ.mjs.map +1 -0
  42. package/dist/esm/chunk-HRQUGJ3Y.mjs +45 -0
  43. package/dist/esm/chunk-HRQUGJ3Y.mjs.map +1 -0
  44. package/dist/esm/chunk-TDLQZ6MP.mjs +86 -0
  45. package/dist/esm/chunk-TDLQZ6MP.mjs.map +1 -0
  46. package/dist/esm/client/index.d.mts +329 -0
  47. package/dist/esm/client/index.mjs +330 -0
  48. package/dist/esm/client/index.mjs.map +1 -0
  49. package/dist/esm/facilitator/index.d.mts +206 -0
  50. package/dist/esm/facilitator/index.mjs +398 -0
  51. package/dist/esm/facilitator/index.mjs.map +1 -0
  52. package/dist/esm/http/index.d.mts +51 -0
  53. package/dist/esm/http/index.mjs +29 -0
  54. package/dist/esm/http/index.mjs.map +1 -0
  55. package/dist/esm/index.d.mts +13 -0
  56. package/dist/esm/index.mjs +14 -0
  57. package/dist/esm/index.mjs.map +1 -0
  58. package/dist/esm/schemas/index.d.mts +825 -0
  59. package/dist/esm/schemas/index.mjs +158 -0
  60. package/dist/esm/schemas/index.mjs.map +1 -0
  61. package/dist/esm/server/index.d.mts +2 -0
  62. package/dist/esm/server/index.mjs +712 -0
  63. package/dist/esm/server/index.mjs.map +1 -0
  64. package/dist/esm/types/index.d.mts +1 -0
  65. package/dist/esm/types/index.mjs +10 -0
  66. package/dist/esm/types/index.mjs.map +1 -0
  67. package/dist/esm/types/v1/index.d.mts +1 -0
  68. package/dist/esm/types/v1/index.mjs +1 -0
  69. package/dist/esm/types/v1/index.mjs.map +1 -0
  70. package/dist/esm/utils/index.d.mts +48 -0
  71. package/dist/esm/utils/index.mjs +20 -0
  72. package/dist/esm/utils/index.mjs.map +1 -0
  73. package/dist/esm/x402HTTPResourceServer-B6uf_UDm.d.mts +434 -0
  74. package/package.json +139 -0
@@ -0,0 +1,434 @@
1
+ import { j as Price, N as Network, S as SettleResponse, P as PaymentPayload, a as PaymentRequirements, c as PaymentRequired, x as x402ResourceServer } from './assetRegistry-CL0zA4s0.js';
2
+
3
+ /**
4
+ * Framework-agnostic HTTP adapter interface
5
+ * Implementations provide framework-specific HTTP operations
6
+ */
7
+ interface HTTPAdapter {
8
+ getHeader(name: string): string | undefined;
9
+ getMethod(): string;
10
+ getPath(): string;
11
+ getUrl(): string;
12
+ getAcceptHeader(): string;
13
+ getUserAgent(): string;
14
+ /**
15
+ * Get query parameters from the request URL
16
+ *
17
+ * @returns Record of query parameter key-value pairs
18
+ */
19
+ getQueryParams?(): Record<string, string | string[]>;
20
+ /**
21
+ * Get a specific query parameter by name
22
+ *
23
+ * @param name - The query parameter name
24
+ * @returns The query parameter value(s) or undefined
25
+ */
26
+ getQueryParam?(name: string): string | string[] | undefined;
27
+ /**
28
+ * Get the parsed request body
29
+ * Framework adapters should parse JSON/form data appropriately
30
+ *
31
+ * @returns The parsed request body
32
+ */
33
+ getBody?(): unknown;
34
+ }
35
+ /**
36
+ * Paywall configuration for HTML responses
37
+ */
38
+ interface PaywallConfig {
39
+ appName?: string;
40
+ appLogo?: string;
41
+ sessionTokenEndpoint?: string;
42
+ currentUrl?: string;
43
+ testnet?: boolean;
44
+ }
45
+ /**
46
+ * Paywall provider interface for generating HTML
47
+ */
48
+ interface PaywallProvider {
49
+ generateHtml(paymentRequired: PaymentRequired, config?: PaywallConfig): string;
50
+ }
51
+ /**
52
+ * Dynamic payTo function that receives HTTP request context
53
+ */
54
+ type DynamicPayTo = (context: HTTPRequestContext) => string | Promise<string>;
55
+ /**
56
+ * Dynamic price function that receives HTTP request context
57
+ */
58
+ type DynamicPrice = (context: HTTPRequestContext) => Price | Promise<Price>;
59
+ /**
60
+ * Result of response body callbacks containing content type and body.
61
+ */
62
+ interface HTTPResponseBody {
63
+ /**
64
+ * The content type for the response (e.g., 'application/json', 'text/plain').
65
+ */
66
+ contentType: string;
67
+ /**
68
+ * The response body to include in the 402 response.
69
+ */
70
+ body: unknown;
71
+ }
72
+ /**
73
+ * Dynamic function to generate a custom response for unpaid requests.
74
+ * Receives the HTTP request context and returns the content type and body to include in the 402 response.
75
+ */
76
+ type UnpaidResponseBody = (context: HTTPRequestContext) => HTTPResponseBody | Promise<HTTPResponseBody>;
77
+ /**
78
+ * Dynamic function to generate a custom response for settlement failures.
79
+ * Receives the HTTP request context and settle failure result, returns the content type and body.
80
+ */
81
+ type SettlementFailedResponseBody = (context: HTTPRequestContext, settleResult: Omit<ProcessSettleFailureResponse, "response">) => HTTPResponseBody | Promise<HTTPResponseBody>;
82
+ /**
83
+ * A single payment option for a route
84
+ * Represents one way a client can pay for access to the resource
85
+ */
86
+ interface PaymentOption {
87
+ scheme: string;
88
+ payTo: string | DynamicPayTo;
89
+ price: Price | DynamicPrice;
90
+ network: Network;
91
+ maxTimeoutSeconds?: number;
92
+ extra?: Record<string, unknown>;
93
+ assets?: string[];
94
+ }
95
+ /**
96
+ * Route configuration for HTTP endpoints
97
+ *
98
+ * The 'accepts' field defines payment options for the route.
99
+ * Can be a single PaymentOption or an array of PaymentOptions for multiple payment methods.
100
+ */
101
+ interface RouteConfig {
102
+ accepts: PaymentOption | PaymentOption[];
103
+ resource?: string;
104
+ description?: string;
105
+ mimeType?: string;
106
+ customPaywallHtml?: string;
107
+ /**
108
+ * Optional callback to generate a custom response for unpaid API requests.
109
+ * This allows servers to return preview data, error messages, or other content
110
+ * when a request lacks payment.
111
+ *
112
+ * For browser requests (Accept: text/html), the paywall HTML takes precedence.
113
+ * This callback is only used for API clients.
114
+ *
115
+ * If not provided, defaults to { contentType: 'application/json', body: {} }.
116
+ *
117
+ * @param context - The HTTP request context
118
+ * @returns An object containing both contentType and body for the 402 response
119
+ */
120
+ unpaidResponseBody?: UnpaidResponseBody;
121
+ /**
122
+ * Optional callback to generate a custom response for settlement failures.
123
+ * If not provided, defaults to { contentType: 'application/json', body: {} }.
124
+ *
125
+ * @param context - The HTTP request context
126
+ * @param settleResult - The settlement failure result
127
+ * @returns An object containing both contentType and body for the 402 response
128
+ */
129
+ settlementFailedResponseBody?: SettlementFailedResponseBody;
130
+ extensions?: Record<string, unknown>;
131
+ }
132
+ /**
133
+ * Routes configuration - maps path patterns to route configs
134
+ */
135
+ type RoutesConfig = Record<string, RouteConfig> | RouteConfig;
136
+ /**
137
+ * Hook that runs on every request to a protected route, before payment processing.
138
+ * Can grant access without payment, deny the request, or continue to payment flow.
139
+ *
140
+ * @returns
141
+ * - `void` - Continue to payment processing (default behavior)
142
+ * - `{ grantAccess: true }` - Grant access without requiring payment
143
+ * - `{ abort: true; reason: string }` - Deny the request (returns 403)
144
+ */
145
+ type ProtectedRequestHook = (context: HTTPRequestContext, routeConfig: RouteConfig) => Promise<void | {
146
+ grantAccess: true;
147
+ } | {
148
+ abort: true;
149
+ reason: string;
150
+ }>;
151
+ /**
152
+ * Compiled route for efficient matching
153
+ */
154
+ interface CompiledRoute {
155
+ verb: string;
156
+ regex: RegExp;
157
+ config: RouteConfig;
158
+ }
159
+ /**
160
+ * HTTP request context that encapsulates all request data
161
+ */
162
+ interface HTTPRequestContext {
163
+ adapter: HTTPAdapter;
164
+ path: string;
165
+ method: string;
166
+ paymentHeader?: string;
167
+ }
168
+ /**
169
+ * HTTP transport context contains both request context and optional response data.
170
+ */
171
+ interface HTTPTransportContext {
172
+ /** The HTTP request context */
173
+ request: HTTPRequestContext;
174
+ /** The response body buffer */
175
+ responseBody?: Buffer;
176
+ }
177
+ /**
178
+ * HTTP response instructions for the framework middleware
179
+ */
180
+ interface HTTPResponseInstructions {
181
+ status: number;
182
+ headers: Record<string, string>;
183
+ body?: unknown;
184
+ isHtml?: boolean;
185
+ }
186
+ /**
187
+ * Result of processing an HTTP request for payment
188
+ */
189
+ type HTTPProcessResult = {
190
+ type: "no-payment-required";
191
+ } | {
192
+ type: "payment-verified";
193
+ paymentPayload: PaymentPayload;
194
+ paymentRequirements: PaymentRequirements;
195
+ declaredExtensions?: Record<string, unknown>;
196
+ } | {
197
+ type: "payment-error";
198
+ response: HTTPResponseInstructions;
199
+ };
200
+ /**
201
+ * Result of processSettlement
202
+ */
203
+ type ProcessSettleSuccessResponse = SettleResponse & {
204
+ success: true;
205
+ headers: Record<string, string>;
206
+ requirements: PaymentRequirements;
207
+ };
208
+ type ProcessSettleFailureResponse = SettleResponse & {
209
+ success: false;
210
+ errorReason: string;
211
+ errorMessage?: string;
212
+ headers: Record<string, string>;
213
+ response: HTTPResponseInstructions;
214
+ };
215
+ type ProcessSettleResultResponse = ProcessSettleSuccessResponse | ProcessSettleFailureResponse;
216
+ /**
217
+ * Represents a validation error for a specific route's payment configuration.
218
+ */
219
+ interface RouteValidationError {
220
+ /** The route pattern (e.g., "GET /api/weather") */
221
+ routePattern: string;
222
+ /** The payment scheme that failed validation */
223
+ scheme: string;
224
+ /** The network that failed validation */
225
+ network: Network;
226
+ /** The type of validation failure */
227
+ reason: "missing_scheme" | "missing_facilitator";
228
+ /** Human-readable error message */
229
+ message: string;
230
+ }
231
+ /**
232
+ * Error thrown when route configuration validation fails.
233
+ */
234
+ declare class RouteConfigurationError extends Error {
235
+ /** The validation errors that caused this exception */
236
+ readonly errors: RouteValidationError[];
237
+ /**
238
+ * Creates a new RouteConfigurationError with the given validation errors.
239
+ *
240
+ * @param errors - The validation errors that caused this exception.
241
+ */
242
+ constructor(errors: RouteValidationError[]);
243
+ }
244
+ /**
245
+ * HTTP-enhanced x402 resource server
246
+ * Provides framework-agnostic HTTP protocol handling
247
+ */
248
+ declare class x402HTTPResourceServer {
249
+ private ResourceServer;
250
+ private compiledRoutes;
251
+ private routesConfig;
252
+ private paywallProvider?;
253
+ private protectedRequestHooks;
254
+ /**
255
+ * Creates a new x402HTTPResourceServer instance.
256
+ *
257
+ * @param ResourceServer - The core x402ResourceServer instance to use
258
+ * @param routes - Route configuration for payment-protected endpoints
259
+ */
260
+ constructor(ResourceServer: x402ResourceServer, routes: RoutesConfig);
261
+ /**
262
+ * Get the underlying x402ResourceServer instance.
263
+ *
264
+ * @returns The underlying x402ResourceServer instance
265
+ */
266
+ get server(): x402ResourceServer;
267
+ /**
268
+ * Get the routes configuration.
269
+ *
270
+ * @returns The routes configuration
271
+ */
272
+ get routes(): RoutesConfig;
273
+ /**
274
+ * Initialize the HTTP resource server.
275
+ *
276
+ * This method initializes the underlying resource server (fetching facilitator support)
277
+ * and then validates that all route payment configurations have corresponding
278
+ * registered schemes and facilitator support.
279
+ *
280
+ * @throws RouteConfigurationError if any route's payment options don't have
281
+ * corresponding registered schemes or facilitator support
282
+ *
283
+ * @example
284
+ * ```typescript
285
+ * const httpServer = new x402HTTPResourceServer(server, routes);
286
+ * await httpServer.initialize();
287
+ * ```
288
+ */
289
+ initialize(): Promise<void>;
290
+ /**
291
+ * Register a custom paywall provider for generating HTML
292
+ *
293
+ * @param provider - PaywallProvider instance
294
+ * @returns This service instance for chaining
295
+ */
296
+ registerPaywallProvider(provider: PaywallProvider): this;
297
+ /**
298
+ * Register a hook that runs on every request to a protected route, before payment processing.
299
+ * Hooks are executed in order of registration. The first hook to return a non-void result wins.
300
+ *
301
+ * @param hook - The request hook function
302
+ * @returns The x402HTTPResourceServer instance for chaining
303
+ */
304
+ onProtectedRequest(hook: ProtectedRequestHook): this;
305
+ /**
306
+ * Process HTTP request and return response instructions
307
+ * This is the main entry point for framework middleware
308
+ *
309
+ * @param context - HTTP request context
310
+ * @param paywallConfig - Optional paywall configuration
311
+ * @returns Process result indicating next action for middleware
312
+ */
313
+ processHTTPRequest(context: HTTPRequestContext, paywallConfig?: PaywallConfig): Promise<HTTPProcessResult>;
314
+ /**
315
+ * Process settlement after successful response
316
+ *
317
+ * @param paymentPayload - The verified payment payload
318
+ * @param requirements - The matching payment requirements
319
+ * @param declaredExtensions - Optional declared extensions (for per-key enrichment)
320
+ * @param transportContext - Optional HTTP transport context
321
+ * @returns ProcessSettleResultResponse - SettleResponse with headers if success or errorReason if failure
322
+ */
323
+ processSettlement(paymentPayload: PaymentPayload, requirements: PaymentRequirements, declaredExtensions?: Record<string, unknown>, transportContext?: HTTPTransportContext): Promise<ProcessSettleResultResponse>;
324
+ /**
325
+ * Check if a request requires payment based on route configuration
326
+ *
327
+ * @param context - HTTP request context
328
+ * @returns True if the route requires payment, false otherwise
329
+ */
330
+ requiresPayment(context: HTTPRequestContext): boolean;
331
+ /**
332
+ * Build HTTPResponseInstructions for settlement failure.
333
+ * Uses settlementFailedResponseBody hook if configured, otherwise defaults to empty body.
334
+ *
335
+ * @param failure - Settlement failure result with headers
336
+ * @param transportContext - Optional HTTP transport context for the request
337
+ * @returns HTTP response instructions for the 402 settlement failure response
338
+ */
339
+ private buildSettlementFailureResponse;
340
+ /**
341
+ * Normalizes a RouteConfig's accepts field into an array of PaymentOptions
342
+ * Handles both single PaymentOption and array formats
343
+ *
344
+ * @param routeConfig - Route configuration
345
+ * @returns Array of payment options
346
+ */
347
+ private normalizePaymentOptions;
348
+ /**
349
+ * Validates that all payment options in routes have corresponding registered schemes
350
+ * and facilitator support.
351
+ *
352
+ * @returns Array of validation errors (empty if all routes are valid)
353
+ */
354
+ private validateRouteConfiguration;
355
+ /**
356
+ * Get route configuration for a request
357
+ *
358
+ * @param path - Request path
359
+ * @param method - HTTP method
360
+ * @returns Route configuration or undefined if no match
361
+ */
362
+ private getRouteConfig;
363
+ /**
364
+ * Extract payment from HTTP headers (handles v1 and v2)
365
+ *
366
+ * @param adapter - HTTP adapter
367
+ * @returns Decoded payment payload or null
368
+ */
369
+ private extractPayment;
370
+ /**
371
+ * Check if request is from a web browser
372
+ *
373
+ * @param adapter - HTTP adapter
374
+ * @returns True if request appears to be from a browser
375
+ */
376
+ private isWebBrowser;
377
+ /**
378
+ * Create HTTP response instructions from payment required
379
+ *
380
+ * @param paymentRequired - Payment requirements
381
+ * @param isWebBrowser - Whether request is from browser
382
+ * @param paywallConfig - Paywall configuration
383
+ * @param customHtml - Custom HTML template
384
+ * @param unpaidResponse - Optional custom response (content type and body) for unpaid API requests
385
+ * @returns Response instructions
386
+ */
387
+ private createHTTPResponse;
388
+ /**
389
+ * Create HTTP payment required response (v1 puts in body, v2 puts in header)
390
+ *
391
+ * @param paymentRequired - Payment required object
392
+ * @returns Headers and body for the HTTP response
393
+ */
394
+ private createHTTPPaymentRequiredResponse;
395
+ /**
396
+ * Create settlement response headers
397
+ *
398
+ * @param settleResponse - Settlement response
399
+ * @returns Headers to add to response
400
+ */
401
+ private createSettlementHeaders;
402
+ /**
403
+ * Parse route pattern into verb and regex
404
+ *
405
+ * @param pattern - Route pattern like "GET /api/*" or "/api/[id]"
406
+ * @returns Parsed pattern with verb and regex
407
+ */
408
+ private parseRoutePattern;
409
+ /**
410
+ * Normalize path for matching
411
+ *
412
+ * @param path - Raw path from request
413
+ * @returns Normalized path
414
+ */
415
+ private normalizePath;
416
+ /**
417
+ * Generate paywall HTML for browser requests
418
+ *
419
+ * @param paymentRequired - Payment required response
420
+ * @param paywallConfig - Optional paywall configuration
421
+ * @param customHtml - Optional custom HTML template
422
+ * @returns HTML string
423
+ */
424
+ private generatePaywallHTML;
425
+ /**
426
+ * Extract display amount from payment requirements.
427
+ *
428
+ * @param paymentRequired - The payment required object
429
+ * @returns The display amount in decimal format
430
+ */
431
+ private getDisplayAmount;
432
+ }
433
+
434
+ export { type CompiledRoute as C, type DynamicPayTo as D, type HTTPAdapter as H, type PaymentOption as P, type RouteConfig as R, type SettlementFailedResponseBody as S, type UnpaidResponseBody as U, type DynamicPrice as a, type HTTPProcessResult as b, type HTTPRequestContext as c, type HTTPResponseBody as d, type HTTPResponseInstructions as e, type HTTPTransportContext as f, type PaywallConfig as g, type PaywallProvider as h, type ProcessSettleFailureResponse as i, type ProcessSettleResultResponse as j, type ProcessSettleSuccessResponse as k, type ProtectedRequestHook as l, RouteConfigurationError as m, type RouteValidationError as n, type RoutesConfig as o, x402HTTPResourceServer as x };