@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,433 @@
1
+ import { h as Price, N as Network, S as SettleResponse, P as PaymentPayload, a as PaymentRequirements, c as PaymentRequired, x as x402ResourceServer } from './mechanisms-q7I6xfUE.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
+ }
94
+ /**
95
+ * Route configuration for HTTP endpoints
96
+ *
97
+ * The 'accepts' field defines payment options for the route.
98
+ * Can be a single PaymentOption or an array of PaymentOptions for multiple payment methods.
99
+ */
100
+ interface RouteConfig {
101
+ accepts: PaymentOption | PaymentOption[];
102
+ resource?: string;
103
+ description?: string;
104
+ mimeType?: string;
105
+ customPaywallHtml?: string;
106
+ /**
107
+ * Optional callback to generate a custom response for unpaid API requests.
108
+ * This allows servers to return preview data, error messages, or other content
109
+ * when a request lacks payment.
110
+ *
111
+ * For browser requests (Accept: text/html), the paywall HTML takes precedence.
112
+ * This callback is only used for API clients.
113
+ *
114
+ * If not provided, defaults to { contentType: 'application/json', body: {} }.
115
+ *
116
+ * @param context - The HTTP request context
117
+ * @returns An object containing both contentType and body for the 402 response
118
+ */
119
+ unpaidResponseBody?: UnpaidResponseBody;
120
+ /**
121
+ * Optional callback to generate a custom response for settlement failures.
122
+ * If not provided, defaults to { contentType: 'application/json', body: {} }.
123
+ *
124
+ * @param context - The HTTP request context
125
+ * @param settleResult - The settlement failure result
126
+ * @returns An object containing both contentType and body for the 402 response
127
+ */
128
+ settlementFailedResponseBody?: SettlementFailedResponseBody;
129
+ extensions?: Record<string, unknown>;
130
+ }
131
+ /**
132
+ * Routes configuration - maps path patterns to route configs
133
+ */
134
+ type RoutesConfig = Record<string, RouteConfig> | RouteConfig;
135
+ /**
136
+ * Hook that runs on every request to a protected route, before payment processing.
137
+ * Can grant access without payment, deny the request, or continue to payment flow.
138
+ *
139
+ * @returns
140
+ * - `void` - Continue to payment processing (default behavior)
141
+ * - `{ grantAccess: true }` - Grant access without requiring payment
142
+ * - `{ abort: true; reason: string }` - Deny the request (returns 403)
143
+ */
144
+ type ProtectedRequestHook = (context: HTTPRequestContext, routeConfig: RouteConfig) => Promise<void | {
145
+ grantAccess: true;
146
+ } | {
147
+ abort: true;
148
+ reason: string;
149
+ }>;
150
+ /**
151
+ * Compiled route for efficient matching
152
+ */
153
+ interface CompiledRoute {
154
+ verb: string;
155
+ regex: RegExp;
156
+ config: RouteConfig;
157
+ }
158
+ /**
159
+ * HTTP request context that encapsulates all request data
160
+ */
161
+ interface HTTPRequestContext {
162
+ adapter: HTTPAdapter;
163
+ path: string;
164
+ method: string;
165
+ paymentHeader?: string;
166
+ }
167
+ /**
168
+ * HTTP transport context contains both request context and optional response data.
169
+ */
170
+ interface HTTPTransportContext {
171
+ /** The HTTP request context */
172
+ request: HTTPRequestContext;
173
+ /** The response body buffer */
174
+ responseBody?: Buffer;
175
+ }
176
+ /**
177
+ * HTTP response instructions for the framework middleware
178
+ */
179
+ interface HTTPResponseInstructions {
180
+ status: number;
181
+ headers: Record<string, string>;
182
+ body?: unknown;
183
+ isHtml?: boolean;
184
+ }
185
+ /**
186
+ * Result of processing an HTTP request for payment
187
+ */
188
+ type HTTPProcessResult = {
189
+ type: "no-payment-required";
190
+ } | {
191
+ type: "payment-verified";
192
+ paymentPayload: PaymentPayload;
193
+ paymentRequirements: PaymentRequirements;
194
+ declaredExtensions?: Record<string, unknown>;
195
+ } | {
196
+ type: "payment-error";
197
+ response: HTTPResponseInstructions;
198
+ };
199
+ /**
200
+ * Result of processSettlement
201
+ */
202
+ type ProcessSettleSuccessResponse = SettleResponse & {
203
+ success: true;
204
+ headers: Record<string, string>;
205
+ requirements: PaymentRequirements;
206
+ };
207
+ type ProcessSettleFailureResponse = SettleResponse & {
208
+ success: false;
209
+ errorReason: string;
210
+ errorMessage?: string;
211
+ headers: Record<string, string>;
212
+ response: HTTPResponseInstructions;
213
+ };
214
+ type ProcessSettleResultResponse = ProcessSettleSuccessResponse | ProcessSettleFailureResponse;
215
+ /**
216
+ * Represents a validation error for a specific route's payment configuration.
217
+ */
218
+ interface RouteValidationError {
219
+ /** The route pattern (e.g., "GET /api/weather") */
220
+ routePattern: string;
221
+ /** The payment scheme that failed validation */
222
+ scheme: string;
223
+ /** The network that failed validation */
224
+ network: Network;
225
+ /** The type of validation failure */
226
+ reason: "missing_scheme" | "missing_facilitator";
227
+ /** Human-readable error message */
228
+ message: string;
229
+ }
230
+ /**
231
+ * Error thrown when route configuration validation fails.
232
+ */
233
+ declare class RouteConfigurationError extends Error {
234
+ /** The validation errors that caused this exception */
235
+ readonly errors: RouteValidationError[];
236
+ /**
237
+ * Creates a new RouteConfigurationError with the given validation errors.
238
+ *
239
+ * @param errors - The validation errors that caused this exception.
240
+ */
241
+ constructor(errors: RouteValidationError[]);
242
+ }
243
+ /**
244
+ * HTTP-enhanced x402 resource server
245
+ * Provides framework-agnostic HTTP protocol handling
246
+ */
247
+ declare class x402HTTPResourceServer {
248
+ private ResourceServer;
249
+ private compiledRoutes;
250
+ private routesConfig;
251
+ private paywallProvider?;
252
+ private protectedRequestHooks;
253
+ /**
254
+ * Creates a new x402HTTPResourceServer instance.
255
+ *
256
+ * @param ResourceServer - The core x402ResourceServer instance to use
257
+ * @param routes - Route configuration for payment-protected endpoints
258
+ */
259
+ constructor(ResourceServer: x402ResourceServer, routes: RoutesConfig);
260
+ /**
261
+ * Get the underlying x402ResourceServer instance.
262
+ *
263
+ * @returns The underlying x402ResourceServer instance
264
+ */
265
+ get server(): x402ResourceServer;
266
+ /**
267
+ * Get the routes configuration.
268
+ *
269
+ * @returns The routes configuration
270
+ */
271
+ get routes(): RoutesConfig;
272
+ /**
273
+ * Initialize the HTTP resource server.
274
+ *
275
+ * This method initializes the underlying resource server (fetching facilitator support)
276
+ * and then validates that all route payment configurations have corresponding
277
+ * registered schemes and facilitator support.
278
+ *
279
+ * @throws RouteConfigurationError if any route's payment options don't have
280
+ * corresponding registered schemes or facilitator support
281
+ *
282
+ * @example
283
+ * ```typescript
284
+ * const httpServer = new x402HTTPResourceServer(server, routes);
285
+ * await httpServer.initialize();
286
+ * ```
287
+ */
288
+ initialize(): Promise<void>;
289
+ /**
290
+ * Register a custom paywall provider for generating HTML
291
+ *
292
+ * @param provider - PaywallProvider instance
293
+ * @returns This service instance for chaining
294
+ */
295
+ registerPaywallProvider(provider: PaywallProvider): this;
296
+ /**
297
+ * Register a hook that runs on every request to a protected route, before payment processing.
298
+ * Hooks are executed in order of registration. The first hook to return a non-void result wins.
299
+ *
300
+ * @param hook - The request hook function
301
+ * @returns The x402HTTPResourceServer instance for chaining
302
+ */
303
+ onProtectedRequest(hook: ProtectedRequestHook): this;
304
+ /**
305
+ * Process HTTP request and return response instructions
306
+ * This is the main entry point for framework middleware
307
+ *
308
+ * @param context - HTTP request context
309
+ * @param paywallConfig - Optional paywall configuration
310
+ * @returns Process result indicating next action for middleware
311
+ */
312
+ processHTTPRequest(context: HTTPRequestContext, paywallConfig?: PaywallConfig): Promise<HTTPProcessResult>;
313
+ /**
314
+ * Process settlement after successful response
315
+ *
316
+ * @param paymentPayload - The verified payment payload
317
+ * @param requirements - The matching payment requirements
318
+ * @param declaredExtensions - Optional declared extensions (for per-key enrichment)
319
+ * @param transportContext - Optional HTTP transport context
320
+ * @returns ProcessSettleResultResponse - SettleResponse with headers if success or errorReason if failure
321
+ */
322
+ processSettlement(paymentPayload: PaymentPayload, requirements: PaymentRequirements, declaredExtensions?: Record<string, unknown>, transportContext?: HTTPTransportContext): Promise<ProcessSettleResultResponse>;
323
+ /**
324
+ * Check if a request requires payment based on route configuration
325
+ *
326
+ * @param context - HTTP request context
327
+ * @returns True if the route requires payment, false otherwise
328
+ */
329
+ requiresPayment(context: HTTPRequestContext): boolean;
330
+ /**
331
+ * Build HTTPResponseInstructions for settlement failure.
332
+ * Uses settlementFailedResponseBody hook if configured, otherwise defaults to empty body.
333
+ *
334
+ * @param failure - Settlement failure result with headers
335
+ * @param transportContext - Optional HTTP transport context for the request
336
+ * @returns HTTP response instructions for the 402 settlement failure response
337
+ */
338
+ private buildSettlementFailureResponse;
339
+ /**
340
+ * Normalizes a RouteConfig's accepts field into an array of PaymentOptions
341
+ * Handles both single PaymentOption and array formats
342
+ *
343
+ * @param routeConfig - Route configuration
344
+ * @returns Array of payment options
345
+ */
346
+ private normalizePaymentOptions;
347
+ /**
348
+ * Validates that all payment options in routes have corresponding registered schemes
349
+ * and facilitator support.
350
+ *
351
+ * @returns Array of validation errors (empty if all routes are valid)
352
+ */
353
+ private validateRouteConfiguration;
354
+ /**
355
+ * Get route configuration for a request
356
+ *
357
+ * @param path - Request path
358
+ * @param method - HTTP method
359
+ * @returns Route configuration or undefined if no match
360
+ */
361
+ private getRouteConfig;
362
+ /**
363
+ * Extract payment from HTTP headers (handles v1 and v2)
364
+ *
365
+ * @param adapter - HTTP adapter
366
+ * @returns Decoded payment payload or null
367
+ */
368
+ private extractPayment;
369
+ /**
370
+ * Check if request is from a web browser
371
+ *
372
+ * @param adapter - HTTP adapter
373
+ * @returns True if request appears to be from a browser
374
+ */
375
+ private isWebBrowser;
376
+ /**
377
+ * Create HTTP response instructions from payment required
378
+ *
379
+ * @param paymentRequired - Payment requirements
380
+ * @param isWebBrowser - Whether request is from browser
381
+ * @param paywallConfig - Paywall configuration
382
+ * @param customHtml - Custom HTML template
383
+ * @param unpaidResponse - Optional custom response (content type and body) for unpaid API requests
384
+ * @returns Response instructions
385
+ */
386
+ private createHTTPResponse;
387
+ /**
388
+ * Create HTTP payment required response (v1 puts in body, v2 puts in header)
389
+ *
390
+ * @param paymentRequired - Payment required object
391
+ * @returns Headers and body for the HTTP response
392
+ */
393
+ private createHTTPPaymentRequiredResponse;
394
+ /**
395
+ * Create settlement response headers
396
+ *
397
+ * @param settleResponse - Settlement response
398
+ * @returns Headers to add to response
399
+ */
400
+ private createSettlementHeaders;
401
+ /**
402
+ * Parse route pattern into verb and regex
403
+ *
404
+ * @param pattern - Route pattern like "GET /api/*" or "/api/[id]"
405
+ * @returns Parsed pattern with verb and regex
406
+ */
407
+ private parseRoutePattern;
408
+ /**
409
+ * Normalize path for matching
410
+ *
411
+ * @param path - Raw path from request
412
+ * @returns Normalized path
413
+ */
414
+ private normalizePath;
415
+ /**
416
+ * Generate paywall HTML for browser requests
417
+ *
418
+ * @param paymentRequired - Payment required response
419
+ * @param paywallConfig - Optional paywall configuration
420
+ * @param customHtml - Optional custom HTML template
421
+ * @returns HTML string
422
+ */
423
+ private generatePaywallHTML;
424
+ /**
425
+ * Extract display amount from payment requirements.
426
+ *
427
+ * @param paymentRequired - The payment required object
428
+ * @returns The display amount in decimal format
429
+ */
430
+ private getDisplayAmount;
431
+ }
432
+
433
+ 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 };