@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.
Files changed (72) hide show
  1. package/README.md +294 -0
  2. package/dist/cjs/client/index.d.ts +149 -0
  3. package/dist/cjs/client/index.js +909 -0
  4. package/dist/cjs/client/index.js.map +1 -0
  5. package/dist/cjs/facilitator/index.d.ts +206 -0
  6. package/dist/cjs/facilitator/index.js +431 -0
  7. package/dist/cjs/facilitator/index.js.map +1 -0
  8. package/dist/cjs/http/index.d.ts +50 -0
  9. package/dist/cjs/http/index.js +1452 -0
  10. package/dist/cjs/http/index.js.map +1 -0
  11. package/dist/cjs/index.d.ts +3 -0
  12. package/dist/cjs/index.js +31 -0
  13. package/dist/cjs/index.js.map +1 -0
  14. package/dist/cjs/schemas/index.d.ts +891 -0
  15. package/dist/cjs/schemas/index.js +216 -0
  16. package/dist/cjs/schemas/index.js.map +1 -0
  17. package/dist/cjs/server/index.d.ts +79 -0
  18. package/dist/cjs/server/index.js +2568 -0
  19. package/dist/cjs/server/index.js.map +1 -0
  20. package/dist/cjs/types/index.d.ts +1 -0
  21. package/dist/cjs/types/index.js +97 -0
  22. package/dist/cjs/types/index.js.map +1 -0
  23. package/dist/cjs/types/v1/index.d.ts +1 -0
  24. package/dist/cjs/types/v1/index.js +19 -0
  25. package/dist/cjs/types/v1/index.js.map +1 -0
  26. package/dist/cjs/utils/index.d.ts +77 -0
  27. package/dist/cjs/utils/index.js +179 -0
  28. package/dist/cjs/utils/index.js.map +1 -0
  29. package/dist/cjs/x402Client-BgegfQgE.d.ts +1807 -0
  30. package/dist/cjs/x402Client-TQHctrG7.d.ts +1807 -0
  31. package/dist/esm/chunk-ABS7D6VX.mjs +145 -0
  32. package/dist/esm/chunk-ABS7D6VX.mjs.map +1 -0
  33. package/dist/esm/chunk-AGOUMC4P.mjs +68 -0
  34. package/dist/esm/chunk-AGOUMC4P.mjs.map +1 -0
  35. package/dist/esm/chunk-BJTO5JO5.mjs +11 -0
  36. package/dist/esm/chunk-BJTO5JO5.mjs.map +1 -0
  37. package/dist/esm/chunk-FPXAE3OS.mjs +161 -0
  38. package/dist/esm/chunk-FPXAE3OS.mjs.map +1 -0
  39. package/dist/esm/chunk-IL77TMJL.mjs +1275 -0
  40. package/dist/esm/chunk-IL77TMJL.mjs.map +1 -0
  41. package/dist/esm/chunk-VE37GDG2.mjs +7 -0
  42. package/dist/esm/chunk-VE37GDG2.mjs.map +1 -0
  43. package/dist/esm/client/index.d.mts +149 -0
  44. package/dist/esm/client/index.mjs +504 -0
  45. package/dist/esm/client/index.mjs.map +1 -0
  46. package/dist/esm/facilitator/index.d.mts +206 -0
  47. package/dist/esm/facilitator/index.mjs +399 -0
  48. package/dist/esm/facilitator/index.mjs.map +1 -0
  49. package/dist/esm/http/index.d.mts +50 -0
  50. package/dist/esm/http/index.mjs +35 -0
  51. package/dist/esm/http/index.mjs.map +1 -0
  52. package/dist/esm/index.d.mts +3 -0
  53. package/dist/esm/index.mjs +8 -0
  54. package/dist/esm/index.mjs.map +1 -0
  55. package/dist/esm/schemas/index.d.mts +891 -0
  56. package/dist/esm/schemas/index.mjs +70 -0
  57. package/dist/esm/schemas/index.mjs.map +1 -0
  58. package/dist/esm/server/index.d.mts +79 -0
  59. package/dist/esm/server/index.mjs +1318 -0
  60. package/dist/esm/server/index.mjs.map +1 -0
  61. package/dist/esm/types/index.d.mts +1 -0
  62. package/dist/esm/types/index.mjs +14 -0
  63. package/dist/esm/types/index.mjs.map +1 -0
  64. package/dist/esm/types/v1/index.d.mts +1 -0
  65. package/dist/esm/types/v1/index.mjs +1 -0
  66. package/dist/esm/types/v1/index.mjs.map +1 -0
  67. package/dist/esm/utils/index.d.mts +77 -0
  68. package/dist/esm/utils/index.mjs +28 -0
  69. package/dist/esm/utils/index.mjs.map +1 -0
  70. package/dist/esm/x402Client-BgegfQgE.d.mts +1807 -0
  71. package/dist/esm/x402Client-TQHctrG7.d.mts +1807 -0
  72. package/package.json +142 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/http/x402HTTPResourceServer.ts","../../src/http/httpFacilitatorClient.ts","../../src/http/x402HTTPClient.ts","../../src/http/index.ts"],"sourcesContent":["import {\n x402ResourceServer,\n SettlementOverrides,\n SkipHandlerDirective,\n PaymentCancellationDispatcher,\n} from \"../server\";\nimport {\n decodePaymentSignatureHeader,\n encodePaymentRequiredHeader,\n encodePaymentResponseHeader,\n} from \".\";\nimport {\n PaymentPayload,\n PaymentRequired,\n SettleResponse,\n SettleError,\n FacilitatorResponseError,\n Price,\n Network,\n PaymentRequirements,\n} from \"../types\";\nimport { x402Version } from \"..\";\n\nexport const SETTLEMENT_OVERRIDES_HEADER = \"Settlement-Overrides\";\n\n/**\n * Framework-agnostic HTTP adapter interface\n * Implementations provide framework-specific HTTP operations\n */\nexport interface HTTPAdapter {\n getHeader(name: string): string | undefined;\n getMethod(): string;\n getPath(): string;\n getUrl(): string;\n getAcceptHeader(): string;\n getUserAgent(): string;\n\n /**\n * Get query parameters from the request URL\n *\n * @returns Record of query parameter key-value pairs\n */\n getQueryParams?(): Record<string, string | string[]>;\n\n /**\n * Get a specific query parameter by name\n *\n * @param name - The query parameter name\n * @returns The query parameter value(s) or undefined\n */\n getQueryParam?(name: string): string | string[] | undefined;\n\n /**\n * Get the parsed request body\n * Framework adapters should parse JSON/form data appropriately\n *\n * @returns The parsed request body\n */\n getBody?(): unknown;\n}\n\n/**\n * Paywall configuration for HTML responses\n */\nexport interface PaywallConfig {\n appName?: string;\n appLogo?: string;\n sessionTokenEndpoint?: string;\n currentUrl?: string;\n testnet?: boolean;\n}\n\n/**\n * Paywall provider interface for generating HTML\n */\nexport interface PaywallProvider {\n generateHtml(paymentRequired: PaymentRequired, config?: PaywallConfig): string;\n}\n\n/**\n * Dynamic payTo function that receives HTTP request context\n */\nexport type DynamicPayTo = (context: HTTPRequestContext) => string | Promise<string>;\n\n/**\n * Dynamic price function that receives HTTP request context\n */\nexport type DynamicPrice = (context: HTTPRequestContext) => Price | Promise<Price>;\n\n/**\n * Result of response body callbacks containing content type and body.\n */\nexport interface HTTPResponseBody {\n /**\n * The content type for the response (e.g., 'application/json', 'text/plain').\n */\n contentType: string;\n\n /**\n * The response body to include in the 402 response.\n */\n body: unknown;\n}\n\n/**\n * Dynamic function to generate a custom response for unpaid requests.\n * Receives the HTTP request context and returns the content type and body to include in the 402 response.\n */\nexport type UnpaidResponseBody = (\n context: HTTPRequestContext,\n) => HTTPResponseBody | Promise<HTTPResponseBody>;\n\n/**\n * Dynamic function to generate a custom response for settlement failures.\n * Receives the HTTP request context and settle failure result, returns the content type and body.\n */\nexport type SettlementFailedResponseBody = (\n context: HTTPRequestContext,\n settleResult: Omit<ProcessSettleFailureResponse, \"response\">,\n) => HTTPResponseBody | Promise<HTTPResponseBody>;\n\n/**\n * A single payment option for a route\n * Represents one way a client can pay for access to the resource\n */\nexport interface PaymentOption {\n scheme: string;\n payTo: string | DynamicPayTo;\n price: Price | DynamicPrice;\n network: Network;\n maxTimeoutSeconds?: number;\n extra?: Record<string, unknown>;\n}\n\n/**\n * Route configuration for HTTP endpoints\n *\n * The 'accepts' field defines payment options for the route.\n * Can be a single PaymentOption or an array of PaymentOptions for multiple payment methods.\n */\nexport interface RouteConfig {\n // Payment option(s): single or array\n accepts: PaymentOption | PaymentOption[];\n\n // HTTP-specific metadata\n resource?: string;\n description?: string;\n mimeType?: string;\n serviceName?: string;\n tags?: string[];\n iconUrl?: string;\n customPaywallHtml?: string;\n\n /**\n * Optional callback to generate a custom response for unpaid API requests.\n * This allows servers to return preview data, error messages, or other content\n * when a request lacks payment.\n *\n * For browser requests (Accept: text/html), the paywall HTML takes precedence.\n * This callback is only used for API clients.\n *\n * If not provided, defaults to { contentType: 'application/json', body: {} }.\n *\n * @param context - The HTTP request context\n * @returns An object containing both contentType and body for the 402 response\n */\n unpaidResponseBody?: UnpaidResponseBody;\n\n /**\n * Optional callback to generate a custom response for settlement failures.\n * If not provided, defaults to { contentType: 'application/json', body: {} }.\n *\n * @param context - The HTTP request context\n * @param settleResult - The settlement failure result\n * @returns An object containing both contentType and body for the 402 response\n */\n settlementFailedResponseBody?: SettlementFailedResponseBody;\n\n // Extensions\n extensions?: Record<string, unknown>;\n}\n\n/**\n * Routes configuration - maps path patterns to route configs\n */\nexport type RoutesConfig = Record<string, RouteConfig> | RouteConfig;\n\n/**\n * Check if any routes in the configuration declare bazaar extensions.\n *\n * @param routes - Route configuration\n * @returns True if any route has extensions.bazaar defined\n */\nexport function checkIfBazaarNeeded(routes: RoutesConfig): boolean {\n if (\"accepts\" in routes) {\n return !!(routes.extensions && \"bazaar\" in routes.extensions);\n }\n\n return Object.values(routes).some(routeConfig => {\n return !!(routeConfig.extensions && \"bazaar\" in routeConfig.extensions);\n });\n}\n\n/**\n * Hook that runs on every request to a protected route, before payment processing.\n * Can grant access without payment, deny the request, or continue to payment flow.\n *\n * @returns\n * - `void` - Continue to payment processing (default behavior)\n * - `{ grantAccess: true }` - Grant access without requiring payment\n * - `{ abort: true; reason: string }` - Deny the request (returns 403)\n */\nexport type ProtectedRequestHook = (\n context: HTTPRequestContext,\n routeConfig: RouteConfig,\n) => Promise<void | { grantAccess: true } | { abort: true; reason: string }>;\n\nexport interface HTTPResourceServerExtensionHooks {\n onProtectedRequest?: (\n declaration: unknown,\n context: HTTPRequestContext,\n routeConfig: RouteConfig,\n ) => Promise<void | { grantAccess: true } | { abort: true; reason: string }>;\n}\n\nexport interface ResourceServerTransportExtensionHooks {\n http?: HTTPResourceServerExtensionHooks;\n}\n\n/**\n * Compiled route for efficient matching\n */\nexport interface CompiledRoute {\n verb: string;\n regex: RegExp;\n config: RouteConfig;\n pattern: string;\n}\n\n/**\n * HTTP request context that encapsulates all request data\n */\nexport interface HTTPRequestContext {\n adapter: HTTPAdapter;\n path: string;\n method: string;\n paymentHeader?: string;\n routePattern?: string;\n}\n\n/**\n * HTTP transport context contains both request context and optional response data.\n */\nexport interface HTTPTransportContext {\n /** The HTTP request context */\n request: HTTPRequestContext;\n /** The response body buffer */\n responseBody?: Buffer;\n /** Response headers set by the route handler (used for settlement overrides) */\n responseHeaders?: Record<string, string>;\n}\n\n/**\n * HTTP response instructions for the framework middleware\n */\nexport interface HTTPResponseInstructions {\n status: number;\n headers: Record<string, string>;\n body?: unknown; // e.g. Paywall for web browser requests, but could be any other type\n isHtml?: boolean; // e.g. if body is a paywall, then isHtml is true\n}\n\n/**\n * Result of processing an HTTP request for payment\n */\nexport type HTTPProcessResult =\n | { type: \"no-payment-required\" }\n | {\n type: \"payment-verified\";\n cancellationDispatcher: PaymentCancellationDispatcher;\n paymentPayload: PaymentPayload;\n paymentRequirements: PaymentRequirements;\n declaredExtensions?: Record<string, unknown>;\n }\n | { type: \"payment-error\"; response: HTTPResponseInstructions };\n\n/**\n * Result of processSettlement\n */\nexport type ProcessSettleSuccessResponse = SettleResponse & {\n success: true;\n headers: Record<string, string>;\n requirements: PaymentRequirements;\n};\n\nexport type ProcessSettleFailureResponse = SettleResponse & {\n success: false;\n errorReason: string;\n errorMessage?: string;\n headers: Record<string, string>;\n response: HTTPResponseInstructions;\n};\n\nexport type ProcessSettleResultResponse =\n | ProcessSettleSuccessResponse\n | ProcessSettleFailureResponse;\n\n/**\n * Represents a validation error for a specific route's payment configuration.\n */\nexport interface RouteValidationError {\n /** The route pattern (e.g., \"GET /api/weather\") */\n routePattern: string;\n /** The payment scheme that failed validation */\n scheme: string;\n /** The network that failed validation */\n network: Network;\n /** The type of validation failure */\n reason: \"missing_scheme\" | \"missing_facilitator\";\n /** Human-readable error message */\n message: string;\n}\n\n/**\n * Error thrown when route configuration validation fails.\n */\nexport class RouteConfigurationError extends Error {\n /** The validation errors that caused this exception */\n public readonly errors: RouteValidationError[];\n\n /**\n * Creates a new RouteConfigurationError with the given validation errors.\n *\n * @param errors - The validation errors that caused this exception.\n */\n constructor(errors: RouteValidationError[]) {\n const message = `x402 Route Configuration Errors:\\n${errors.map(e => ` - ${e.message}`).join(\"\\n\")}`;\n super(message);\n this.name = \"RouteConfigurationError\";\n this.errors = errors;\n }\n}\n\n// Static fallback paywall served when @bankofai/x402-paywall is not installed.\n// Intentionally contains zero request- or config-derived interpolation:\n// the protocol-level payment requirements still ship in response headers\n// and the JSON 402 body for non-browser clients, so any agent or SDK can\n// read them without us reflecting attacker-controlled bytes into HTML.\n// Browser-end-user payment requires installing @bankofai/x402-paywall.\nconst FALLBACK_PAYWALL_HTML = `<!DOCTYPE html>\n<html>\n <head>\n <title>Payment Required</title>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n </head>\n <body>\n <div style=\"max-width: 600px; margin: 50px auto; padding: 20px; font-family: system-ui, -apple-system, sans-serif;\">\n <h1>Payment Required</h1>\n <p>This resource is protected by the x402 payment protocol.</p>\n <p style=\"margin-top: 2rem; padding: 1rem; background: #fef3c7; border-radius: 0.5rem;\">\n <strong>Note to developers:</strong> install <code>@bankofai/x402-paywall</code> to enable\n the in-browser wallet connection and payment UI. Programmatic clients should read\n the payment requirements from the 402 response headers and JSON body.\n </p>\n </div>\n </body>\n</html>`;\n\n/**\n * HTTP-enhanced x402 resource server\n * Provides framework-agnostic HTTP protocol handling\n */\nexport class x402HTTPResourceServer {\n private ResourceServer: x402ResourceServer;\n private compiledRoutes: CompiledRoute[] = [];\n private routesConfig: RoutesConfig;\n private paywallProvider?: PaywallProvider;\n private protectedRequestHooks: ProtectedRequestHook[] = [];\n\n /**\n * Creates a new x402HTTPResourceServer instance.\n *\n * @param ResourceServer - The core x402ResourceServer instance to use\n * @param routes - Route configuration for payment-protected endpoints\n */\n constructor(ResourceServer: x402ResourceServer, routes: RoutesConfig) {\n this.ResourceServer = ResourceServer;\n this.routesConfig = routes;\n\n // Handle both single route and multiple routes\n const normalizedRoutes =\n typeof routes === \"object\" && !(\"accepts\" in routes)\n ? (routes as Record<string, RouteConfig>)\n : { \"*\": routes as RouteConfig };\n\n for (const [pattern, config] of Object.entries(normalizedRoutes)) {\n const parsed = this.parseRoutePattern(pattern);\n this.compiledRoutes.push({\n verb: parsed.verb,\n regex: parsed.regex,\n config,\n pattern: parsed.path,\n });\n }\n }\n\n /**\n * Get the underlying x402ResourceServer instance.\n *\n * @returns The underlying x402ResourceServer instance\n */\n get server(): x402ResourceServer {\n return this.ResourceServer;\n }\n\n /**\n * Get the routes configuration.\n *\n * @returns The routes configuration\n */\n get routes(): RoutesConfig {\n return this.routesConfig;\n }\n\n /**\n * Initialize the HTTP resource server.\n *\n * This method initializes the underlying resource server (fetching facilitator support)\n * and then validates that all route payment configurations have corresponding\n * registered schemes and facilitator support.\n *\n * @throws RouteConfigurationError if any route's payment options don't have\n * corresponding registered schemes or facilitator support\n *\n * @example\n * ```typescript\n * const httpServer = new x402HTTPResourceServer(server, routes);\n * await httpServer.initialize();\n * ```\n */\n async initialize(): Promise<void> {\n // First, initialize the underlying resource server (fetches facilitator support)\n await this.ResourceServer.initialize();\n\n // Then validate route configuration\n const errors = this.validateRouteConfiguration();\n if (errors.length > 0) {\n throw new RouteConfigurationError(errors);\n }\n }\n\n /**\n * Register a custom paywall provider for generating HTML\n *\n * @param provider - PaywallProvider instance\n * @returns This service instance for chaining\n */\n registerPaywallProvider(provider: PaywallProvider): this {\n this.paywallProvider = provider;\n return this;\n }\n\n /**\n * Register a hook that runs on every request to a protected route, before payment processing.\n * Hooks are executed in order of registration. The first hook to return a non-void result wins.\n *\n * @param hook - The request hook function\n * @returns The x402HTTPResourceServer instance for chaining\n */\n onProtectedRequest(hook: ProtectedRequestHook): this {\n this.protectedRequestHooks.push(hook);\n return this;\n }\n\n /**\n * Process HTTP request and return response instructions\n * This is the main entry point for framework middleware\n *\n * @param context - HTTP request context\n * @param paywallConfig - Optional paywall configuration\n * @returns Process result indicating next action for middleware\n */\n async processHTTPRequest(\n context: HTTPRequestContext,\n paywallConfig?: PaywallConfig,\n ): Promise<HTTPProcessResult> {\n const method = context.method || context.adapter.getMethod();\n context = { ...context, method };\n const { adapter, path } = context;\n\n // Find matching route\n const routeMatch = this.getRouteConfig(path, method);\n if (!routeMatch) {\n return { type: \"no-payment-required\" }; // No payment required for this route\n }\n const { config: routeConfig, pattern: routePattern } = routeMatch;\n const enrichedContext: HTTPRequestContext = { ...context, routePattern };\n\n // Execute request hooks before any payment processing\n for (const hook of this.getProtectedRequestHooks(routeConfig)) {\n const result = await hook(enrichedContext, routeConfig);\n if (result && \"grantAccess\" in result) {\n return { type: \"no-payment-required\" };\n }\n if (result && \"abort\" in result) {\n return {\n type: \"payment-error\",\n response: {\n status: 403,\n headers: { \"Content-Type\": \"application/json\" },\n body: { error: result.reason },\n },\n };\n }\n }\n\n // Normalize accepts field to array of payment options\n const paymentOptions = this.normalizePaymentOptions(routeConfig);\n\n // Check for payment header (v1 or v2)\n const paymentPayload = this.extractPayment(adapter);\n\n // Create resource info, using config override if provided\n const resourceInfo = {\n url: routeConfig.resource || enrichedContext.adapter.getUrl(),\n description: routeConfig.description || \"\",\n mimeType: routeConfig.mimeType || \"\",\n ...(routeConfig.serviceName !== undefined && { serviceName: routeConfig.serviceName }),\n ...(routeConfig.tags !== undefined && { tags: routeConfig.tags }),\n ...(routeConfig.iconUrl !== undefined && { iconUrl: routeConfig.iconUrl }),\n };\n\n // Build requirements from all payment options\n // (this method handles resolving dynamic functions internally)\n let requirements = await this.ResourceServer.buildPaymentRequirementsFromOptions(\n paymentOptions,\n enrichedContext,\n );\n\n let extensions = routeConfig.extensions;\n if (extensions) {\n extensions = this.ResourceServer.enrichExtensions(extensions, enrichedContext);\n }\n\n // createPaymentRequiredResponse already handles extension enrichment in the core layer\n const transportContext: HTTPTransportContext = { request: enrichedContext };\n const paymentRequired = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n !paymentPayload ? \"Payment required\" : undefined,\n extensions,\n transportContext,\n );\n\n // If no payment provided\n if (!paymentPayload) {\n // Resolve custom unpaid response body if provided\n const unpaidBody = routeConfig.unpaidResponseBody\n ? await routeConfig.unpaidResponseBody(enrichedContext)\n : undefined;\n\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(\n paymentRequired,\n this.isWebBrowser(adapter),\n paywallConfig,\n routeConfig.customPaywallHtml,\n unpaidBody,\n ),\n };\n }\n\n // Verify payment\n try {\n const matchingRequirements = this.ResourceServer.findMatchingRequirements(\n paymentRequired.accepts,\n paymentPayload,\n );\n\n if (!matchingRequirements) {\n const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n \"No matching payment requirements\",\n extensions,\n transportContext,\n );\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(errorResponse, false, paywallConfig),\n };\n }\n\n const extensionResult = this.ResourceServer.validateExtensions(\n paymentRequired,\n paymentPayload,\n );\n if (!extensionResult.valid) {\n const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n extensionResult.invalidReason,\n extensions,\n transportContext,\n paymentPayload,\n );\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(errorResponse, false, paywallConfig),\n };\n }\n\n const verifyResult = await this.ResourceServer.verifyPayment(\n paymentPayload,\n matchingRequirements,\n extensions,\n transportContext,\n );\n\n if (!verifyResult.isValid) {\n const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n verifyResult.invalidReason,\n extensions,\n transportContext,\n paymentPayload,\n );\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(errorResponse, false, paywallConfig),\n };\n }\n\n // Bypass the resource handler\n if (verifyResult.skipHandler) {\n return await this.processSkipHandlerSettlement(\n paymentPayload,\n matchingRequirements,\n extensions,\n transportContext,\n verifyResult.skipHandler,\n );\n }\n\n const cancellationDispatcher = this.ResourceServer.createPaymentCancellationDispatcher(\n paymentPayload,\n matchingRequirements,\n extensions,\n transportContext,\n );\n\n // Payment is valid, return data needed for settlement\n return {\n type: \"payment-verified\",\n cancellationDispatcher,\n paymentPayload,\n paymentRequirements: matchingRequirements,\n declaredExtensions: extensions,\n };\n } catch (error) {\n if (error instanceof FacilitatorResponseError) {\n throw error;\n }\n const errorResponse = await this.ResourceServer.createPaymentRequiredResponse(\n requirements,\n resourceInfo,\n error instanceof Error ? error.message : \"Payment verification failed\",\n extensions,\n transportContext,\n );\n return {\n type: \"payment-error\",\n response: this.createHTTPResponse(errorResponse, false, paywallConfig),\n };\n }\n }\n\n /**\n * Process settlement after successful response\n *\n * @param paymentPayload - The verified payment payload\n * @param requirements - The matching payment requirements\n * @param declaredExtensions - Optional declared extensions (for per-key enrichment)\n * @param transportContext - Optional HTTP transport context\n * @param settlementOverrides - Optional settlement overrides (e.g., partial settlement amount)\n * @returns ProcessSettleResultResponse - SettleResponse with headers if success or errorReason if failure\n */\n async processSettlement(\n paymentPayload: PaymentPayload,\n requirements: PaymentRequirements,\n declaredExtensions?: Record<string, unknown>,\n transportContext?: HTTPTransportContext,\n settlementOverrides?: SettlementOverrides,\n ): Promise<ProcessSettleResultResponse> {\n if (transportContext?.request && !transportContext.request.method) {\n transportContext = {\n ...transportContext,\n request: {\n ...transportContext.request,\n method: transportContext.request.adapter.getMethod(),\n },\n };\n }\n try {\n // Resolve overrides: explicit param takes precedence, fall back to response header\n let resolvedOverrides = settlementOverrides;\n if (!resolvedOverrides && transportContext?.responseHeaders) {\n const overridesKey = SETTLEMENT_OVERRIDES_HEADER.toLowerCase();\n const rawValue = Object.entries(transportContext.responseHeaders).find(\n ([key]) => key.toLowerCase() === overridesKey,\n )?.[1];\n if (rawValue) {\n try {\n resolvedOverrides = JSON.parse(rawValue);\n } catch {\n // Ignore malformed header\n }\n }\n }\n\n const settleResponse = await this.ResourceServer.settlePayment(\n paymentPayload,\n requirements,\n declaredExtensions,\n transportContext,\n resolvedOverrides,\n );\n\n if (!settleResponse.success) {\n const failure = {\n ...settleResponse,\n success: false as const,\n errorReason: settleResponse.errorReason || \"Settlement failed\",\n errorMessage:\n settleResponse.errorMessage || settleResponse.errorReason || \"Settlement failed\",\n headers: this.createSettlementHeaders(settleResponse),\n };\n const response = await this.buildSettlementFailureResponse(failure, transportContext);\n return { ...failure, response };\n }\n\n return {\n ...settleResponse,\n success: true,\n headers: this.createSettlementHeaders(settleResponse),\n requirements,\n };\n } catch (error) {\n if (error instanceof FacilitatorResponseError) {\n throw error;\n }\n if (error instanceof SettleError) {\n const errorReason = error.errorReason || error.message;\n const settleResponse: SettleResponse = {\n success: false,\n errorReason,\n errorMessage: error.errorMessage || errorReason,\n payer: error.payer,\n network: error.network,\n transaction: error.transaction,\n };\n const failure = {\n ...settleResponse,\n success: false as const,\n errorReason,\n headers: this.createSettlementHeaders(settleResponse),\n };\n const response = await this.buildSettlementFailureResponse(failure, transportContext);\n return { ...failure, response };\n }\n const errorReason = error instanceof Error ? error.message : \"Settlement failed\";\n const settleResponse: SettleResponse = {\n success: false,\n errorReason,\n errorMessage: errorReason,\n network: requirements.network as Network,\n transaction: \"\",\n };\n const failure = {\n ...settleResponse,\n success: false as const,\n errorReason,\n headers: this.createSettlementHeaders(settleResponse),\n };\n const response = await this.buildSettlementFailureResponse(failure, transportContext);\n return { ...failure, response };\n }\n }\n\n /**\n * Check if a request requires payment based on route configuration\n *\n * @param context - HTTP request context\n * @returns True if the route requires payment, false otherwise\n */\n requiresPayment(context: HTTPRequestContext): boolean {\n const method = context.method || context.adapter.getMethod();\n return this.getRouteConfig(context.path, method) !== undefined;\n }\n\n /**\n * Settle a verified payment that requested `skipHandler`, packaging the\n * result as a `payment-error` HTTPProcessResult so framework adapters can\n * write the response without invoking the route handler.\n *\n * - On success: status 200 + PAYMENT-RESPONSE header + configured body.\n * - On failure: the standard 402 settlement-failure response.\n *\n * @param paymentPayload - Verified payment payload.\n * @param requirements - Matched payment requirements.\n * @param declaredExtensions - Optional declared extensions for the route.\n * @param transportContext - Optional HTTP transport context.\n * @param skipHandlerResponse - Optional content type + body to return on success.\n * @returns A `payment-error` HTTPProcessResult carrying the final response.\n */\n private async processSkipHandlerSettlement(\n paymentPayload: PaymentPayload,\n requirements: PaymentRequirements,\n declaredExtensions: Record<string, unknown> | undefined,\n transportContext: HTTPTransportContext,\n skipHandlerResponse: SkipHandlerDirective | undefined,\n ): Promise<HTTPProcessResult> {\n const settleResult = await this.processSettlement(\n paymentPayload,\n requirements,\n declaredExtensions,\n transportContext,\n );\n\n if (!settleResult.success) {\n return { type: \"payment-error\", response: settleResult.response };\n }\n\n const contentType = skipHandlerResponse?.contentType ?? \"application/json\";\n const body = skipHandlerResponse?.body ?? {};\n\n return {\n type: \"payment-error\",\n response: {\n status: 200,\n headers: {\n \"Content-Type\": contentType,\n ...settleResult.headers,\n },\n body,\n isHtml: contentType.includes(\"text/html\"),\n },\n };\n }\n\n /**\n * Build HTTPResponseInstructions for settlement failure.\n * Uses settlementFailedResponseBody hook if configured, otherwise defaults to empty body.\n *\n * @param failure - Settlement failure result with headers\n * @param transportContext - Optional HTTP transport context for the request\n * @returns HTTP response instructions for the 402 settlement failure response\n */\n private async buildSettlementFailureResponse(\n failure: Omit<ProcessSettleFailureResponse, \"response\">,\n transportContext?: HTTPTransportContext,\n ): Promise<HTTPResponseInstructions> {\n const settlementHeaders = failure.headers;\n const routeConfig = transportContext\n ? this.getRouteConfig(transportContext.request.path, transportContext.request.method)\n : undefined;\n\n const customBody = routeConfig?.config.settlementFailedResponseBody\n ? await routeConfig.config.settlementFailedResponseBody(transportContext!.request, failure)\n : undefined;\n\n const contentType = customBody ? customBody.contentType : \"application/json\";\n const body = customBody ? customBody.body : {};\n\n return {\n status: 402,\n headers: {\n \"Content-Type\": contentType,\n ...settlementHeaders,\n },\n body,\n isHtml: contentType.includes(\"text/html\"),\n };\n }\n\n /**\n * Normalizes a RouteConfig's accepts field into an array of PaymentOptions\n * Handles both single PaymentOption and array formats\n *\n * @param routeConfig - Route configuration\n * @returns Array of payment options\n */\n private normalizePaymentOptions(routeConfig: RouteConfig): PaymentOption[] {\n return Array.isArray(routeConfig.accepts) ? routeConfig.accepts : [routeConfig.accepts];\n }\n\n /**\n * Manual request hooks run before extension transport hooks for declared extensions.\n *\n * @param routeConfig - Route configuration for the matched request\n * @returns Hooks in invocation order\n */\n private getProtectedRequestHooks(routeConfig: RouteConfig): ProtectedRequestHook[] {\n const hooks = [...this.protectedRequestHooks];\n const declaredExtensions = routeConfig.extensions;\n if (!declaredExtensions) return hooks;\n\n for (const extension of this.ResourceServer.getExtensions()) {\n const hook = extension.transportHooks?.http?.onProtectedRequest;\n if (!hook || !(extension.key in declaredExtensions)) continue;\n\n hooks.push((context, routeConfig) =>\n hook(declaredExtensions[extension.key], context, routeConfig),\n );\n }\n\n return hooks;\n }\n\n /**\n * Validates that all payment options in routes have corresponding registered schemes\n * and facilitator support.\n *\n * @returns Array of validation errors (empty if all routes are valid)\n */\n private validateRouteConfiguration(): RouteValidationError[] {\n const errors: RouteValidationError[] = [];\n\n // Normalize routes to array of [pattern, config] pairs\n const normalizedRoutes =\n typeof this.routesConfig === \"object\" && !(\"accepts\" in this.routesConfig)\n ? Object.entries(this.routesConfig as Record<string, RouteConfig>)\n : [[\"*\", this.routesConfig as RouteConfig] as [string, RouteConfig]];\n\n for (const [pattern, config] of normalizedRoutes) {\n // Warn if wildcard routes are used with discovery extensions\n const pathPart = pattern.includes(\" \") ? pattern.split(/\\s+/)[1] : pattern;\n if (\n pathPart &&\n pathPart.includes(\"*\") &&\n config.extensions &&\n \"bazaar\" in config.extensions\n ) {\n console.warn(\n `[x402] Route \"${pattern}\": Wildcard (*) patterns with bazaar discovery extensions ` +\n `will auto-generate parameter names (var1, var2, ...). ` +\n `Consider using named parameters instead (e.g. /weather/:city) for better discovery metadata.`,\n );\n }\n\n const paymentOptions = this.normalizePaymentOptions(config);\n\n for (const option of paymentOptions) {\n // Check 1: Is scheme registered?\n if (!this.ResourceServer.hasRegisteredScheme(option.network, option.scheme)) {\n errors.push({\n routePattern: pattern,\n scheme: option.scheme,\n network: option.network,\n reason: \"missing_scheme\",\n message: `Route \"${pattern}\": No scheme implementation registered for \"${option.scheme}\" on network \"${option.network}\"`,\n });\n // Skip facilitator check if scheme isn't registered\n continue;\n }\n\n // Check 2: Does facilitator support this scheme/network combination?\n const supportedKind = this.ResourceServer.getSupportedKind(\n x402Version,\n option.network,\n option.scheme,\n );\n\n if (!supportedKind) {\n errors.push({\n routePattern: pattern,\n scheme: option.scheme,\n network: option.network,\n reason: \"missing_facilitator\",\n message: `Route \"${pattern}\": Facilitator does not support scheme \"${option.scheme}\" on network \"${option.network}\"`,\n });\n }\n }\n }\n\n return errors;\n }\n\n /**\n * Get route configuration for a request\n *\n * @param path - Request path\n * @param method - HTTP method\n * @returns Route configuration and pattern, or undefined if no match\n */\n private getRouteConfig(\n path: string,\n method: string,\n ): { config: RouteConfig; pattern: string } | undefined {\n const normalizedPath = this.normalizePath(path);\n const upperMethod = method.toUpperCase();\n\n const matchingRoute = this.compiledRoutes.find(\n route =>\n route.regex.test(normalizedPath) && (route.verb === \"*\" || route.verb === upperMethod),\n );\n\n if (!matchingRoute) return undefined;\n return { config: matchingRoute.config, pattern: matchingRoute.pattern };\n }\n\n /**\n * Extract payment from HTTP headers (handles v1 and v2)\n *\n * @param adapter - HTTP adapter\n * @returns Decoded payment payload or null\n */\n private extractPayment(adapter: HTTPAdapter): PaymentPayload | null {\n // Check v2 header first (PAYMENT-SIGNATURE)\n const header = adapter.getHeader(\"payment-signature\") || adapter.getHeader(\"PAYMENT-SIGNATURE\");\n\n if (header) {\n try {\n return decodePaymentSignatureHeader(header);\n } catch (error) {\n console.warn(\"Failed to decode PAYMENT-SIGNATURE header:\", error);\n }\n }\n\n return null;\n }\n\n /**\n * Check if request is from a web browser\n *\n * @param adapter - HTTP adapter\n * @returns True if request appears to be from a browser\n */\n private isWebBrowser(adapter: HTTPAdapter): boolean {\n const accept = adapter.getAcceptHeader();\n const userAgent = adapter.getUserAgent();\n return accept.includes(\"text/html\") && userAgent.includes(\"Mozilla\");\n }\n\n /**\n * Create HTTP response instructions from payment required\n *\n * @param paymentRequired - Payment requirements\n * @param isWebBrowser - Whether request is from browser\n * @param paywallConfig - Paywall configuration\n * @param customHtml - Custom HTML template\n * @param unpaidResponse - Optional custom response (content type and body) for unpaid API requests\n * @returns Response instructions\n */\n private createHTTPResponse(\n paymentRequired: PaymentRequired,\n isWebBrowser: boolean,\n paywallConfig?: PaywallConfig,\n customHtml?: string,\n unpaidResponse?: HTTPResponseBody,\n ): HTTPResponseInstructions {\n // Use 412 Precondition Failed for permit2_allowance_required error\n // This signals client needs to approve Permit2 before retrying\n const status = paymentRequired.error === \"permit2_allowance_required\" ? 412 : 402;\n const response = this.createHTTPPaymentRequiredResponse(paymentRequired);\n\n if (isWebBrowser) {\n const html = this.generatePaywallHTML(paymentRequired, paywallConfig, customHtml);\n return {\n status,\n headers: {\n \"Content-Type\": \"text/html\",\n ...response.headers,\n },\n body: html,\n isHtml: true,\n };\n }\n\n // Use callback result if provided, otherwise default to JSON with empty object\n const contentType = unpaidResponse ? unpaidResponse.contentType : \"application/json\";\n const body = unpaidResponse ? unpaidResponse.body : {};\n\n return {\n status,\n headers: {\n \"Content-Type\": contentType,\n ...response.headers,\n },\n body,\n };\n }\n\n /**\n * Create HTTP payment required response (v1 puts in body, v2 puts in header)\n *\n * @param paymentRequired - Payment required object\n * @returns Headers and body for the HTTP response\n */\n private createHTTPPaymentRequiredResponse(paymentRequired: PaymentRequired): {\n headers: Record<string, string>;\n } {\n return {\n headers: {\n \"PAYMENT-REQUIRED\": encodePaymentRequiredHeader(paymentRequired),\n },\n };\n }\n\n /**\n * Create settlement response headers\n *\n * @param settleResponse - Settlement response\n * @returns Headers to add to response\n */\n private createSettlementHeaders(settleResponse: SettleResponse): Record<string, string> {\n const encoded = encodePaymentResponseHeader(settleResponse);\n return { \"PAYMENT-RESPONSE\": encoded };\n }\n\n /**\n * Parse route pattern into verb and regex\n *\n * @param pattern - Route pattern like \"GET /api/*\", \"/api/[id]\", or \"/api/:id\"\n * @returns Parsed pattern with verb and regex\n */\n private parseRoutePattern(pattern: string): { verb: string; regex: RegExp; path: string } {\n const [verb, path] = pattern.includes(\" \") ? pattern.split(/\\s+/) : [\"*\", pattern];\n\n const regex = new RegExp(\n `^${\n path\n .replace(/\\\\/g, \"\\\\\\\\\") // Escape backslashes first\n .replace(/[$()+.?^{|}]/g, \"\\\\$&\") // Escape regex special chars\n .replace(/\\*/g, \".*?\") // Wildcards\n .replace(/\\[([^\\]]+)\\]/g, \"[^/]+\") // Parameters (Next.js style [param])\n .replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, \"[^/]+\") // Parameters (Express style :param)\n .replace(/\\//g, \"\\\\/\") // Escape slashes\n }$`,\n \"i\",\n );\n\n return { verb: verb.toUpperCase(), regex, path };\n }\n\n /**\n * Normalize path for matching\n *\n * @param path - Raw path from request\n * @returns Normalized path\n */\n private normalizePath(path: string): string {\n const pathWithoutQuery = path.split(/[?#]/)[0];\n\n // Decode percent-escapes per segment, preserving encoded path separators\n // (%2F, %5C) as their literal escaped form. Otherwise an attacker could\n // hide a \"/\" inside a single segment (e.g. /api/report/a%2Fb), bypassing\n // a :param route whose regex compiles to [^/]+ while the framework still\n // dispatches the request as a single-segment match.\n const parts = pathWithoutQuery.split(/(%2[fF]|%5[cC])/);\n const decoded = parts\n .map((part, i) => {\n if (i % 2 === 1) return part;\n try {\n return decodeURIComponent(part);\n } catch {\n return part;\n }\n })\n .join(\"\");\n\n return decoded\n .replace(/\\\\/g, \"/\")\n .replace(/\\/+/g, \"/\")\n .replace(/(.+?)\\/+$/, \"$1\");\n }\n\n /**\n * Generate paywall HTML for browser requests\n *\n * @param paymentRequired - Payment required response\n * @param paywallConfig - Optional paywall configuration\n * @param customHtml - Optional custom HTML template\n * @returns HTML string\n */\n private generatePaywallHTML(\n paymentRequired: PaymentRequired,\n paywallConfig?: PaywallConfig,\n customHtml?: string,\n ): string {\n if (customHtml) {\n return customHtml;\n }\n\n // Use custom paywall provider if set\n if (this.paywallProvider) {\n return this.paywallProvider.generateHtml(paymentRequired, paywallConfig);\n }\n\n // Try to use @bankofai/x402-paywall if available (optional dependency)\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const paywall = require(\"@bankofai/x402-paywall\");\n const displayAmount = this.getDisplayAmount(paymentRequired);\n const resource = paymentRequired.resource;\n\n return paywall.getPaywallHtml({\n amount: displayAmount,\n paymentRequired,\n currentUrl: resource?.url || paywallConfig?.currentUrl || \"\",\n testnet: paywallConfig?.testnet ?? true,\n appName: paywallConfig?.appName,\n appLogo: paywallConfig?.appLogo,\n sessionTokenEndpoint: paywallConfig?.sessionTokenEndpoint,\n });\n } catch {\n // @bankofai/x402-paywall not installed, fall back to basic HTML\n }\n\n return FALLBACK_PAYWALL_HTML;\n }\n\n /**\n * Extract display amount from payment requirements.\n * Uses the registered scheme's decimal precision for the asset, falling back to 6.\n *\n * @param paymentRequired - The payment required object\n * @returns The display amount in decimal format\n */\n private getDisplayAmount(paymentRequired: PaymentRequired): number {\n const accepts = paymentRequired.accepts;\n if (accepts && accepts.length > 0) {\n const firstReq = accepts[0];\n if (\"amount\" in firstReq) {\n const decimals = this.ResourceServer.getAssetDecimalsForRequirements(firstReq);\n return parseFloat(firstReq.amount) / 10 ** decimals;\n }\n }\n return 0;\n }\n}\n","import { PaymentPayload, PaymentRequirements } from \"../types/payments\";\nimport {\n VerifyResponse,\n SettleResponse,\n SupportedResponse,\n VerifyError,\n SettleError,\n FacilitatorResponseError,\n} from \"../types/facilitator\";\nimport { z } from \"../schemas\";\nimport { safeBase64Decode } from \"../utils\";\n\nconst DEFAULT_FACILITATOR_URL = \"https://x402.org/facilitator\";\n\nexport interface FacilitatorConfig {\n url?: string;\n createAuthHeaders?: () => Promise<{\n verify: Record<string, string>;\n settle: Record<string, string>;\n supported: Record<string, string>;\n bazaar?: Record<string, string>;\n }>;\n}\n\n/**\n * Interface for facilitator clients\n * Can be implemented for HTTP-based or local facilitators\n */\nexport interface FacilitatorClient {\n /**\n * Verify a payment with the facilitator\n *\n * @param paymentPayload - The payment to verify\n * @param paymentRequirements - The requirements to verify against\n * @returns Verification response\n */\n verify(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise<VerifyResponse>;\n\n /**\n * Settle a payment with the facilitator\n *\n * @param paymentPayload - The payment to settle\n * @param paymentRequirements - The requirements for settlement\n * @returns Settlement response\n */\n settle(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise<SettleResponse>;\n\n /**\n * Get supported payment kinds and extensions from the facilitator\n *\n * @returns Supported payment kinds and extensions\n */\n getSupported(): Promise<SupportedResponse>;\n}\n\n/** Number of retries for getSupported() on 429 rate limit errors */\nconst GET_SUPPORTED_RETRIES = 3;\n/** Base delay in ms for exponential backoff on retries */\nconst GET_SUPPORTED_RETRY_DELAY_MS = 1000;\n/** Upper bound on retry delay to prevent pathological waits from a misbehaving server */\nconst MAX_RETRY_DELAY_MS = 30_000;\n\n/**\n * Resolves the delay before the next 429 retry. Parses Retry-After per RFC 7231 §7.1.3\n * (delta-seconds or HTTP-date) and falls back to exponential backoff when the header\n * is absent, unparseable, or non-positive. The result is clamped to MAX_RETRY_DELAY_MS.\n *\n * @param retryAfter - Raw `Retry-After` header value, or null if not present\n * @param attempt - Zero-based retry attempt index used for exponential backoff\n * @returns Delay in milliseconds to wait before the next attempt\n */\nexport function computeRetryDelay(retryAfter: string | null, attempt: number): number {\n let delay: number | null = null;\n\n if (retryAfter !== null) {\n const seconds = Number(retryAfter);\n if (!isNaN(seconds)) {\n // delta-seconds form\n delay = seconds * 1000;\n } else {\n // HTTP-date form\n const retryDate = Date.parse(retryAfter);\n if (!isNaN(retryDate)) {\n delay = retryDate - Date.now();\n }\n }\n }\n\n // Fall back to exponential backoff for missing, invalid, or non-positive values\n if (delay === null || delay <= 0) {\n delay = GET_SUPPORTED_RETRY_DELAY_MS * Math.pow(2, attempt);\n }\n\n return Math.min(delay, MAX_RETRY_DELAY_MS);\n}\n\nconst verifyResponseSchema: z.ZodType<VerifyResponse, z.ZodTypeDef, unknown> = z.object({\n isValid: z.boolean(),\n invalidReason: z\n .string()\n .nullish()\n .transform(v => v ?? undefined),\n invalidMessage: z\n .string()\n .nullish()\n .transform(v => v ?? undefined),\n payer: z\n .string()\n .nullish()\n .transform(v => v ?? undefined),\n extensions: z\n .record(z.string(), z.unknown())\n .nullish()\n .transform(v => v ?? undefined),\n extra: z\n .record(z.string(), z.unknown())\n .nullish()\n .transform(v => v ?? undefined),\n});\n\nconst settleResponseSchema: z.ZodType<SettleResponse, z.ZodTypeDef, unknown> = z.object({\n success: z.boolean(),\n errorReason: z\n .string()\n .nullish()\n .transform(v => v ?? undefined),\n errorMessage: z\n .string()\n .nullish()\n .transform(v => v ?? undefined),\n payer: z\n .string()\n .nullish()\n .transform(v => v ?? undefined),\n transaction: z.string(),\n network: z.custom<SettleResponse[\"network\"]>(value => typeof value === \"string\"),\n amount: z\n .string()\n .nullish()\n .transform(v => v ?? undefined),\n extensions: z\n .record(z.string(), z.unknown())\n .nullish()\n .transform(v => v ?? undefined),\n extra: z\n .record(z.string(), z.unknown())\n .nullish()\n .transform(v => v ?? undefined),\n});\n\nconst supportedKindSchema: z.ZodType<SupportedResponse[\"kinds\"][number], z.ZodTypeDef, unknown> =\n z.object({\n x402Version: z.number(),\n scheme: z.string(),\n network: z.custom<SupportedResponse[\"kinds\"][number][\"network\"]>(\n value => typeof value === \"string\",\n ),\n extra: z\n .record(z.string(), z.unknown())\n .nullish()\n .transform(v => v ?? undefined),\n });\n\nconst supportedResponseSchema: z.ZodType<SupportedResponse, z.ZodTypeDef, unknown> = z.object({\n kinds: z.array(supportedKindSchema),\n extensions: z.array(z.string()).default([]),\n signers: z.record(z.string(), z.array(z.string())).default({}),\n});\n\n/**\n * Produces a compact excerpt of a facilitator response body for error messages.\n *\n * @param text - The raw response body text\n * @param limit - The maximum number of characters to include\n * @returns A normalized excerpt suitable for logs and thrown errors\n */\nfunction responseExcerpt(text: string, limit: number = 200): string {\n const compact = text.trim().replace(/\\s+/g, \" \");\n if (!compact) {\n return \"<empty response>\";\n }\n\n if (compact.length <= limit) {\n return compact;\n }\n\n return `${compact.slice(0, limit - 3)}...`;\n}\n\nconst EXTENSION_RESPONSE_LOG_FIELD_ALLOWLIST = [\"status\", \"rejectedReason\", \"reason\", \"code\"];\n\n/**\n * Reads the `EXTENSION-RESPONSES` header from a facilitator HTTP response and logs\n * allowlisted fields. Silently ignores malformed headers.\n *\n * @param response - The HTTP response from the facilitator\n */\nfunction logExtensionResponsesHeader(response: Response): void {\n const header = response.headers.get(\"EXTENSION-RESPONSES\");\n if (!header) return;\n try {\n const decoded = JSON.parse(safeBase64Decode(header));\n if (!decoded || typeof decoded !== \"object\" || Array.isArray(decoded)) return;\n const sanitized: Record<string, Record<string, unknown>> = {};\n for (const [extensionKey, payload] of Object.entries(decoded as Record<string, unknown>)) {\n const source =\n payload && typeof payload === \"object\" && !Array.isArray(payload)\n ? (payload as Record<string, unknown>)\n : {};\n const filtered: Record<string, unknown> = {};\n for (const key of EXTENSION_RESPONSE_LOG_FIELD_ALLOWLIST) {\n if (source[key] !== undefined) {\n filtered[key] = source[key];\n }\n }\n sanitized[extensionKey] = filtered;\n }\n console.log(`[x402] extension responses: ${JSON.stringify(sanitized)}`);\n } catch {\n // Ignore malformed header\n }\n}\n\n/**\n * Parses and validates a successful facilitator response body.\n *\n * @param response - The HTTP response returned by the facilitator\n * @param schema - The schema used to validate the response payload\n * @param operation - The facilitator operation name for error reporting\n * @returns The validated facilitator payload\n */\nasync function parseSuccessResponse<T>(\n response: Response,\n schema: z.ZodType<T, z.ZodTypeDef, unknown>,\n operation: string,\n): Promise<T> {\n const text = await response.text();\n\n let data: unknown;\n try {\n data = JSON.parse(text);\n } catch {\n throw new FacilitatorResponseError(\n `Facilitator ${operation} returned invalid JSON: ${responseExcerpt(text)}`,\n );\n }\n\n const parsed = schema.safeParse(data);\n if (!parsed.success) {\n throw new FacilitatorResponseError(\n `Facilitator ${operation} returned invalid data: ${responseExcerpt(text)}`,\n );\n }\n\n return parsed.data;\n}\n\n/**\n * HTTP-based client for interacting with x402 facilitator services\n * Handles HTTP communication with facilitator endpoints\n */\nexport class HTTPFacilitatorClient implements FacilitatorClient {\n readonly url: string;\n private readonly _createAuthHeaders?: FacilitatorConfig[\"createAuthHeaders\"];\n\n /**\n * Creates a new HTTPFacilitatorClient instance.\n *\n * @param config - Configuration options for the facilitator client\n */\n constructor(config?: FacilitatorConfig) {\n // Normalize URL: strip trailing slashes to prevent redirect loops (e.g. 308)\n // when constructing endpoint paths like `${url}/supported`\n this.url = (config?.url || DEFAULT_FACILITATOR_URL).replace(/\\/+$/, \"\");\n this._createAuthHeaders = config?.createAuthHeaders;\n }\n\n /**\n * Verify a payment with the facilitator\n *\n * @param paymentPayload - The payment to verify\n * @param paymentRequirements - The requirements to verify against\n * @returns Verification response\n */\n async verify(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise<VerifyResponse> {\n let headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n if (this._createAuthHeaders) {\n const authHeaders = await this.createAuthHeaders(\"verify\");\n headers = { ...headers, ...authHeaders.headers };\n }\n\n const response = await fetch(`${this.url}/verify`, {\n method: \"POST\",\n headers,\n redirect: \"follow\",\n body: JSON.stringify({\n x402Version: paymentPayload.x402Version,\n paymentPayload: this.toJsonSafe(paymentPayload),\n paymentRequirements: this.toJsonSafe(paymentRequirements),\n }),\n });\n\n if (!response.ok) {\n const text = await response.text();\n let data: unknown;\n try {\n data = JSON.parse(text);\n } catch {\n throw new Error(`Facilitator verify failed (${response.status}): ${responseExcerpt(text)}`);\n }\n\n if (typeof data === \"object\" && data !== null && \"isValid\" in data) {\n throw new VerifyError(response.status, data as VerifyResponse);\n }\n\n throw new Error(\n `Facilitator verify failed (${response.status}): ${responseExcerpt(JSON.stringify(data))}`,\n );\n }\n\n const verifyResult = await parseSuccessResponse(response, verifyResponseSchema, \"verify\");\n logExtensionResponsesHeader(response);\n return verifyResult;\n }\n\n /**\n * Settle a payment with the facilitator\n *\n * @param paymentPayload - The payment to settle\n * @param paymentRequirements - The requirements for settlement\n * @returns Settlement response\n */\n async settle(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n ): Promise<SettleResponse> {\n let headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n if (this._createAuthHeaders) {\n const authHeaders = await this.createAuthHeaders(\"settle\");\n headers = { ...headers, ...authHeaders.headers };\n }\n\n const response = await fetch(`${this.url}/settle`, {\n method: \"POST\",\n headers,\n redirect: \"follow\",\n body: JSON.stringify({\n x402Version: paymentPayload.x402Version,\n paymentPayload: this.toJsonSafe(paymentPayload),\n paymentRequirements: this.toJsonSafe(paymentRequirements),\n }),\n });\n\n if (!response.ok) {\n const text = await response.text();\n let data: unknown;\n try {\n data = JSON.parse(text);\n } catch {\n throw new Error(`Facilitator settle failed (${response.status}): ${responseExcerpt(text)}`);\n }\n\n if (typeof data === \"object\" && data !== null && \"success\" in data) {\n throw new SettleError(response.status, data as SettleResponse);\n }\n\n throw new Error(\n `Facilitator settle failed (${response.status}): ${responseExcerpt(JSON.stringify(data))}`,\n );\n }\n\n const settleResult = await parseSuccessResponse(response, settleResponseSchema, \"settle\");\n logExtensionResponsesHeader(response);\n return settleResult;\n }\n\n /**\n * Get supported payment kinds and extensions from the facilitator.\n * Retries with exponential backoff on 429 rate limit errors.\n *\n * @returns Supported payment kinds and extensions\n */\n async getSupported(): Promise<SupportedResponse> {\n let headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n if (this._createAuthHeaders) {\n const authHeaders = await this.createAuthHeaders(\"supported\");\n headers = { ...headers, ...authHeaders.headers };\n }\n\n let lastError: Error | null = null;\n for (let attempt = 0; attempt < GET_SUPPORTED_RETRIES; attempt++) {\n const response = await fetch(`${this.url}/supported`, {\n method: \"GET\",\n headers,\n redirect: \"follow\",\n });\n\n if (response.ok) {\n return parseSuccessResponse(response, supportedResponseSchema, \"supported\");\n }\n\n const errorText = await response.text().catch(() => response.statusText);\n lastError = new Error(\n `Facilitator getSupported failed (${response.status}): ${responseExcerpt(errorText)}`,\n );\n\n // Retry on 429, honoring the server's Retry-After when available.\n if (response.status === 429 && attempt < GET_SUPPORTED_RETRIES - 1) {\n const delay = computeRetryDelay(response.headers.get(\"Retry-After\"), attempt);\n await new Promise(resolve => setTimeout(resolve, delay));\n continue;\n }\n\n throw lastError;\n }\n\n throw lastError ?? new Error(\"Facilitator getSupported failed after retries\");\n }\n\n /**\n * Creates authentication headers for a specific path.\n *\n * @param path - The path to create authentication headers for (e.g., \"verify\", \"settle\", \"supported\")\n * @returns An object containing the authentication headers for the specified path\n */\n async createAuthHeaders(path: string): Promise<{\n headers: Record<string, string>;\n }> {\n if (this._createAuthHeaders) {\n const authHeaders = (await this._createAuthHeaders()) as Record<\n string,\n Record<string, string>\n >;\n return {\n headers: authHeaders[path] ?? {},\n };\n }\n return {\n headers: {},\n };\n }\n\n /**\n * Helper to convert objects to JSON-safe format.\n * Handles BigInt and other non-JSON types.\n *\n * @param obj - The object to convert\n * @returns The JSON-safe representation of the object\n */\n private toJsonSafe(obj: unknown): unknown {\n return JSON.parse(\n JSON.stringify(obj, (_, value) => (typeof value === \"bigint\" ? value.toString() : value)),\n );\n }\n}\n","import {\n decodePaymentRequiredHeader,\n decodePaymentResponseHeader,\n encodePaymentSignatureHeader,\n} from \".\";\nimport { SettleResponse } from \"../types\";\nimport { PaymentPayload, PaymentRequired } from \"../types/payments\";\nimport { x402Client, type PaymentResponseContext } from \"../client/x402Client\";\n\n/**\n * Context provided to onPaymentRequired hooks.\n */\nexport interface PaymentRequiredContext {\n paymentRequired: PaymentRequired;\n}\n\n/**\n * Hook called when a 402 response is received, before payment processing.\n * Return headers to try before payment, or void to proceed directly to payment.\n */\nexport type PaymentRequiredHook = (\n context: PaymentRequiredContext,\n) => Promise<{ headers: Record<string, string> } | void>;\n\nexport interface HTTPClientExtensionHooks {\n onPaymentRequired?: (\n declaration: unknown,\n context: PaymentRequiredContext,\n ) => Promise<{ headers: Record<string, string> } | void>;\n}\n\ntype HTTPClientTransportExtension = {\n transportHooks?: {\n http?: HTTPClientExtensionHooks;\n };\n};\n\n/**\n * HTTP-specific client for handling x402 payment protocol over HTTP.\n *\n * Wraps a x402Client to provide HTTP-specific encoding/decoding functionality\n * for payment headers and responses while maintaining the builder pattern.\n */\nexport class x402HTTPClient {\n private paymentRequiredHooks: PaymentRequiredHook[] = [];\n\n /**\n * Creates a new x402HTTPClient instance.\n *\n * @param client - The underlying x402Client for payment logic\n */\n constructor(private readonly client: x402Client) {}\n\n /**\n * Register a hook to handle 402 responses before payment.\n * Hooks run in order; first to return headers wins.\n *\n * @param hook - The hook function to register\n * @returns This instance for chaining\n */\n onPaymentRequired(hook: PaymentRequiredHook): this {\n this.paymentRequiredHooks.push(hook);\n return this;\n }\n\n /**\n * Run hooks and return headers if any hook provides them.\n *\n * @param paymentRequired - The payment required response from the server\n * @returns Headers to use for retry, or null to proceed to payment\n */\n async handlePaymentRequired(\n paymentRequired: PaymentRequired,\n ): Promise<Record<string, string> | null> {\n for (const hook of this.getPaymentRequiredHooks(paymentRequired)) {\n const result = await hook({ paymentRequired });\n if (result?.headers) {\n return result.headers;\n }\n }\n return null;\n }\n\n /**\n * Encodes a payment payload into appropriate HTTP headers based on version.\n *\n * @param paymentPayload - The payment payload to encode\n * @returns HTTP headers containing the encoded payment signature\n */\n encodePaymentSignatureHeader(paymentPayload: PaymentPayload): Record<string, string> {\n switch (paymentPayload.x402Version) {\n case 2:\n return {\n \"PAYMENT-SIGNATURE\": encodePaymentSignatureHeader(paymentPayload),\n };\n case 1:\n return {\n \"X-PAYMENT\": encodePaymentSignatureHeader(paymentPayload),\n };\n default:\n throw new Error(\n `Unsupported x402 version: ${(paymentPayload as PaymentPayload).x402Version}`,\n );\n }\n }\n\n /**\n * Extracts payment required information from HTTP response.\n *\n * @param getHeader - Function to retrieve header value by name (case-insensitive)\n * @param body - Optional response body for v1 compatibility\n * @returns The payment required object\n */\n getPaymentRequiredResponse(\n getHeader: (name: string) => string | null | undefined,\n body?: unknown,\n ): PaymentRequired {\n // v2\n const paymentRequired = getHeader(\"PAYMENT-REQUIRED\");\n if (paymentRequired) {\n return decodePaymentRequiredHeader(paymentRequired);\n }\n\n // v1\n if (\n body &&\n body instanceof Object &&\n \"x402Version\" in body &&\n (body as PaymentRequired).x402Version === 1\n ) {\n return body as PaymentRequired;\n }\n\n throw new Error(\"Invalid payment required response\");\n }\n\n /**\n * Extracts payment settlement response from HTTP headers.\n *\n * @param getHeader - Function to retrieve header value by name (case-insensitive)\n * @returns The settlement response object\n */\n getPaymentSettleResponse(getHeader: (name: string) => string | null | undefined): SettleResponse {\n // v2\n const paymentResponse = getHeader(\"PAYMENT-RESPONSE\");\n if (paymentResponse) {\n return decodePaymentResponseHeader(paymentResponse);\n }\n\n // v1\n const xPaymentResponse = getHeader(\"X-PAYMENT-RESPONSE\");\n if (xPaymentResponse) {\n return decodePaymentResponseHeader(xPaymentResponse);\n }\n\n throw new Error(\"Payment response header not found\");\n }\n\n /**\n * Creates a payment payload for the given payment requirements.\n * Delegates to the underlying x402Client.\n *\n * @param paymentRequired - The payment required response from the server\n * @returns Promise resolving to the payment payload\n */\n async createPaymentPayload(paymentRequired: PaymentRequired): Promise<PaymentPayload> {\n return this.client.createPaymentPayload(paymentRequired);\n }\n\n /**\n * Parses response headers into protocol types, fires payment response hooks (v2 only),\n * and returns whether a hook signaled recovery.\n *\n * Called by transport wrappers (fetch, axios) after the paid request completes.\n *\n * @param paymentPayload - The payload that was sent with the request\n * @param getHeader - Function to retrieve a response header by name\n * @param status - The HTTP status code of the response\n * @returns Whether a hook recovered and the parsed settle response (if any)\n */\n async processPaymentResult(\n paymentPayload: PaymentPayload,\n getHeader: (name: string) => string | null | undefined,\n status: number,\n ): Promise<{ recovered: boolean; settleResponse?: SettleResponse }> {\n let settleResponse: SettleResponse | undefined;\n try {\n settleResponse = this.getPaymentSettleResponse(getHeader);\n } catch {\n /* no header */\n }\n\n if (paymentPayload.x402Version === 1) {\n return { recovered: false, settleResponse };\n }\n\n let paymentRequired: PaymentRequired | undefined;\n if (!settleResponse && status === 402) {\n try {\n paymentRequired = this.getPaymentRequiredResponse(getHeader);\n } catch {\n /* no header */\n }\n }\n\n const requirements = paymentPayload.accepted;\n if (!requirements) {\n throw new Error(\"Invalid x402 v2 payment payload: missing `accepted`\");\n }\n\n const ctx: PaymentResponseContext = {\n paymentPayload,\n requirements,\n ...(settleResponse ? { settleResponse } : {}),\n ...(paymentRequired ? { paymentRequired } : {}),\n };\n\n const result = await this.client.handlePaymentResponse(ctx);\n return { recovered: result?.recovered === true, settleResponse };\n }\n\n /**\n * Parses HTTP status, headers, and body into an `HTTPResourceResponse`.\n *\n * Decodes the x402 payment header into `header`: the `PAYMENT-RESPONSE`\n * settlement if present, otherwise the `PAYMENT-REQUIRED` declaration on\n * 402 responses (whose `error` field carries the server's failure reason).\n *\n * @param args - Normalized response inputs from any HTTP transport\n * @param args.status - HTTP response status code\n * @param args.getHeader - Callback to read response headers by name\n * @param args.body - Response body payload\n * @returns The parsed status, body, and decoded payment header\n */\n parsePaymentResult(args: {\n status: number;\n getHeader: (name: string) => string | null | undefined;\n body: unknown;\n }): HTTPResourceResponse {\n const { status, getHeader, body } = args;\n\n let header: SettleResponse | PaymentRequired | undefined;\n try {\n header = this.getPaymentSettleResponse(getHeader);\n } catch {\n if (status === 402) {\n try {\n header = this.getPaymentRequiredResponse(getHeader, body);\n } catch {\n /* no payment header */\n }\n }\n }\n\n let paymentStatus: HTTPPaymentStatus = \"none\";\n if (header && !(\"success\" in header)) {\n paymentStatus = \"payment_required\";\n }\n if (header && \"success\" in header) {\n paymentStatus = header.success ? \"settled\" : \"settle_failed\";\n }\n\n return { status, paymentStatus, body, header };\n }\n\n /**\n * Parses a fetch Response into an `HTTPResourceResponse` for app-level convenience.\n *\n * @param response - The fetch Response to process\n * @returns The parsed status, body, and decoded payment header\n */\n async processResponse(response: Response): Promise<HTTPResourceResponse> {\n const getHeader = (name: string) => response.headers.get(name);\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n const body = contentType.includes(\"application/json\")\n ? await response.json()\n : await response.text();\n\n return this.parsePaymentResult({ status: response.status, getHeader, body });\n }\n\n /**\n * Manual HTTP hooks run before extension hooks scoped to the 402 response.\n *\n * @param paymentRequired - The payment required response from the server\n * @returns Hooks in invocation order\n */\n private getPaymentRequiredHooks(paymentRequired: PaymentRequired): PaymentRequiredHook[] {\n const hooks = [...this.paymentRequiredHooks];\n const declaredExtensions = paymentRequired.extensions;\n if (!declaredExtensions) return hooks;\n\n for (const extension of this.client.getExtensions()) {\n const httpExtension = extension as HTTPClientTransportExtension;\n const hook = httpExtension.transportHooks?.http?.onPaymentRequired;\n if (!hook || !(extension.key in declaredExtensions)) continue;\n\n hooks.push(context => hook(declaredExtensions[extension.key], context));\n }\n\n return hooks;\n }\n}\n\n/**\n * Parsed result of an HTTP request to an x402 resource.\n */\nexport type HTTPResourceResponse = {\n /** HTTP status code. */\n status: number;\n /** x402 payment outcome. */\n paymentStatus: HTTPPaymentStatus;\n /** Parsed response body. */\n body: unknown;\n /**\n * Decoded x402 payment header, if present:\n * - SettleResponse (from PAYMENT-RESPONSE / X-PAYMENT-RESPONSE)\n * - PaymentRequired (from PAYMENT-REQUIRED; its `error` carries the server reason)\n */\n header?: SettleResponse | PaymentRequired;\n};\n\nexport type HTTPPaymentStatus = \"settled\" | \"settle_failed\" | \"payment_required\" | \"none\";\n","import { SettleResponse } from \"../types\";\nimport { PaymentPayload, PaymentRequired } from \"../types/payments\";\nimport { Base64EncodedRegex, safeBase64Decode, safeBase64Encode } from \"../utils\";\n\n// HTTP Methods that typically use query parameters\nexport type QueryParamMethods = \"GET\" | \"HEAD\" | \"DELETE\";\n\n// HTTP Methods that typically use request body\nexport type BodyMethods = \"POST\" | \"PUT\" | \"PATCH\";\n\n/**\n * Encodes a payment payload as a base64 header value.\n *\n * @param paymentPayload - The payment payload to encode\n * @returns Base64 encoded string representation of the payment payload\n */\nexport function encodePaymentSignatureHeader(paymentPayload: PaymentPayload): string {\n return safeBase64Encode(JSON.stringify(paymentPayload));\n}\n\n/**\n * Decodes a base64 payment signature header into a payment payload.\n *\n * @param paymentSignatureHeader - The base64 encoded payment signature header\n * @returns The decoded payment payload\n */\nexport function decodePaymentSignatureHeader(paymentSignatureHeader: string): PaymentPayload {\n if (!Base64EncodedRegex.test(paymentSignatureHeader)) {\n throw new Error(\"Invalid payment signature header\");\n }\n return JSON.parse(safeBase64Decode(paymentSignatureHeader)) as PaymentPayload;\n}\n\n/**\n * Encodes a payment required object as a base64 header value.\n *\n * @param paymentRequired - The payment required object to encode\n * @returns Base64 encoded string representation of the payment required object\n */\nexport function encodePaymentRequiredHeader(paymentRequired: PaymentRequired): string {\n return safeBase64Encode(JSON.stringify(paymentRequired));\n}\n\n/**\n * Decodes a base64 payment required header into a payment required object.\n *\n * @param paymentRequiredHeader - The base64 encoded payment required header\n * @returns The decoded payment required object\n */\nexport function decodePaymentRequiredHeader(paymentRequiredHeader: string): PaymentRequired {\n if (!Base64EncodedRegex.test(paymentRequiredHeader)) {\n throw new Error(\"Invalid payment required header\");\n }\n return JSON.parse(safeBase64Decode(paymentRequiredHeader)) as PaymentRequired;\n}\n\n/**\n * Encodes a payment response as a base64 header value.\n *\n * @param paymentResponse - The payment response to encode\n * @returns Base64 encoded string representation of the payment response\n */\nexport function encodePaymentResponseHeader(paymentResponse: SettleResponse): string {\n return safeBase64Encode(JSON.stringify(paymentResponse));\n}\n\n/**\n * Decodes a base64 payment response header into a settle response.\n *\n * @param paymentResponseHeader - The base64 encoded payment response header\n * @returns The decoded settle response\n */\nexport function decodePaymentResponseHeader(paymentResponseHeader: string): SettleResponse {\n if (!Base64EncodedRegex.test(paymentResponseHeader)) {\n throw new Error(\"Invalid payment response header\");\n }\n return JSON.parse(safeBase64Decode(paymentResponseHeader)) as SettleResponse;\n}\n\n// Export HTTP service and types\nexport {\n x402HTTPResourceServer,\n HTTPAdapter,\n HTTPRequestContext,\n HTTPTransportContext,\n HTTPResponseInstructions,\n HTTPProcessResult,\n PaywallConfig,\n PaywallProvider,\n PaymentOption,\n RouteConfig,\n RoutesConfig,\n CompiledRoute,\n DynamicPayTo,\n DynamicPrice,\n UnpaidResponseBody,\n HTTPResponseBody,\n SettlementFailedResponseBody,\n ProcessSettleResultResponse,\n ProcessSettleSuccessResponse,\n ProcessSettleFailureResponse,\n RouteValidationError,\n RouteConfigurationError,\n ProtectedRequestHook,\n HTTPResourceServerExtensionHooks,\n ResourceServerTransportExtensionHooks,\n} from \"./x402HTTPResourceServer\";\nexport {\n HTTPFacilitatorClient,\n FacilitatorClient,\n FacilitatorConfig,\n} from \"./httpFacilitatorClient\";\nexport { FacilitatorResponseError, getFacilitatorResponseError } from \"../types\";\nexport {\n x402HTTPClient,\n PaymentRequiredContext,\n PaymentRequiredHook,\n HTTPClientExtensionHooks,\n HTTPResourceResponse,\n HTTPPaymentStatus,\n} from \"./x402HTTPClient\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuBO,IAAM,8BAA8B;AA0KpC,SAAS,oBAAoB,QAA+B;AACjE,MAAI,aAAa,QAAQ;AACvB,WAAO,CAAC,EAAE,OAAO,cAAc,YAAY,OAAO;AAAA,EACpD;AAEA,SAAO,OAAO,OAAO,MAAM,EAAE,KAAK,iBAAe;AAC/C,WAAO,CAAC,EAAE,YAAY,cAAc,YAAY,YAAY;AAAA,EAC9D,CAAC;AACH;AA6HO,IAAM,0BAAN,cAAsC,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASjD,YAAY,QAAgC;AAC1C,UAAM,UAAU;AAAA,EAAqC,OAAO,IAAI,OAAK,OAAO,EAAE,OAAO,EAAE,EAAE,KAAK,IAAI,CAAC;AACnG,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EAChB;AACF;AAQA,IAAM,wBAAwB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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AAM,KAAK,aAAW,KAAK,mBAAmB,UAAU,GAAG,GAAG,OAAO,CAAC;AAAA,IACxE;AAEA,WAAO;AAAA,EACT;AACF;;;AC9RO,SAAS,6BAA6B,gBAAwC;AACnF,SAAO,iBAAiB,KAAK,UAAU,cAAc,CAAC;AACxD;AAQO,SAAS,6BAA6B,wBAAgD;AAC3F,MAAI,CAAC,mBAAmB,KAAK,sBAAsB,GAAG;AACpD,UAAM,IAAI,MAAM,kCAAkC;AAAA,EACpD;AACA,SAAO,KAAK,MAAM,iBAAiB,sBAAsB,CAAC;AAC5D;AAQO,SAAS,4BAA4B,iBAA0C;AACpF,SAAO,iBAAiB,KAAK,UAAU,eAAe,CAAC;AACzD;AAQO,SAAS,4BAA4B,uBAAgD;AAC1F,MAAI,CAAC,mBAAmB,KAAK,qBAAqB,GAAG;AACnD,UAAM,IAAI,MAAM,iCAAiC;AAAA,EACnD;AACA,SAAO,KAAK,MAAM,iBAAiB,qBAAqB,CAAC;AAC3D;AAQO,SAAS,4BAA4B,iBAAyC;AACnF,SAAO,iBAAiB,KAAK,UAAU,eAAe,CAAC;AACzD;AAQO,SAAS,4BAA4B,uBAA+C;AACzF,MAAI,CAAC,mBAAmB,KAAK,qBAAqB,GAAG;AACnD,UAAM,IAAI,MAAM,iCAAiC;AAAA,EACnD;AACA,SAAO,KAAK,MAAM,iBAAiB,qBAAqB,CAAC;AAC3D;","names":["errorReason","settleResponse","failure","response","routeConfig"]}
@@ -0,0 +1,7 @@
1
+ // src/index.ts
2
+ var x402Version = 2;
3
+
4
+ export {
5
+ x402Version
6
+ };
7
+ //# sourceMappingURL=chunk-VE37GDG2.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export const x402Version = 2;\n"],"mappings":";AAAO,IAAM,cAAc;","names":[]}
@@ -0,0 +1,149 @@
1
+ import { c as PaymentRequired, ae as x402Client, P as PaymentPayload, S as SettleResponse } from '../x402Client-TQHctrG7.mjs';
2
+ export { aj as AfterPaymentCreationHook, ai as BeforePaymentCreationHook, aq as ClientExtension, ao as ClientExtensionHooks, ap as ClientTransportExtensionHooks, ak as OnPaymentCreationFailureHook, am as OnPaymentResponseHook, ag as PaymentCreatedContext, af as PaymentCreationContext, ah as PaymentCreationFailureContext, ar as PaymentPolicy, al as PaymentResponseContext, as as SchemeRegistration, an as SelectPaymentRequirements, at as x402ClientConfig } from '../x402Client-TQHctrG7.mjs';
3
+
4
+ /**
5
+ * Context provided to onPaymentRequired hooks.
6
+ */
7
+ interface PaymentRequiredContext {
8
+ paymentRequired: PaymentRequired;
9
+ }
10
+ /**
11
+ * Hook called when a 402 response is received, before payment processing.
12
+ * Return headers to try before payment, or void to proceed directly to payment.
13
+ */
14
+ type PaymentRequiredHook = (context: PaymentRequiredContext) => Promise<{
15
+ headers: Record<string, string>;
16
+ } | void>;
17
+ interface HTTPClientExtensionHooks {
18
+ onPaymentRequired?: (declaration: unknown, context: PaymentRequiredContext) => Promise<{
19
+ headers: Record<string, string>;
20
+ } | void>;
21
+ }
22
+ /**
23
+ * HTTP-specific client for handling x402 payment protocol over HTTP.
24
+ *
25
+ * Wraps a x402Client to provide HTTP-specific encoding/decoding functionality
26
+ * for payment headers and responses while maintaining the builder pattern.
27
+ */
28
+ declare class x402HTTPClient {
29
+ private readonly client;
30
+ private paymentRequiredHooks;
31
+ /**
32
+ * Creates a new x402HTTPClient instance.
33
+ *
34
+ * @param client - The underlying x402Client for payment logic
35
+ */
36
+ constructor(client: x402Client);
37
+ /**
38
+ * Register a hook to handle 402 responses before payment.
39
+ * Hooks run in order; first to return headers wins.
40
+ *
41
+ * @param hook - The hook function to register
42
+ * @returns This instance for chaining
43
+ */
44
+ onPaymentRequired(hook: PaymentRequiredHook): this;
45
+ /**
46
+ * Run hooks and return headers if any hook provides them.
47
+ *
48
+ * @param paymentRequired - The payment required response from the server
49
+ * @returns Headers to use for retry, or null to proceed to payment
50
+ */
51
+ handlePaymentRequired(paymentRequired: PaymentRequired): Promise<Record<string, string> | null>;
52
+ /**
53
+ * Encodes a payment payload into appropriate HTTP headers based on version.
54
+ *
55
+ * @param paymentPayload - The payment payload to encode
56
+ * @returns HTTP headers containing the encoded payment signature
57
+ */
58
+ encodePaymentSignatureHeader(paymentPayload: PaymentPayload): Record<string, string>;
59
+ /**
60
+ * Extracts payment required information from HTTP response.
61
+ *
62
+ * @param getHeader - Function to retrieve header value by name (case-insensitive)
63
+ * @param body - Optional response body for v1 compatibility
64
+ * @returns The payment required object
65
+ */
66
+ getPaymentRequiredResponse(getHeader: (name: string) => string | null | undefined, body?: unknown): PaymentRequired;
67
+ /**
68
+ * Extracts payment settlement response from HTTP headers.
69
+ *
70
+ * @param getHeader - Function to retrieve header value by name (case-insensitive)
71
+ * @returns The settlement response object
72
+ */
73
+ getPaymentSettleResponse(getHeader: (name: string) => string | null | undefined): SettleResponse;
74
+ /**
75
+ * Creates a payment payload for the given payment requirements.
76
+ * Delegates to the underlying x402Client.
77
+ *
78
+ * @param paymentRequired - The payment required response from the server
79
+ * @returns Promise resolving to the payment payload
80
+ */
81
+ createPaymentPayload(paymentRequired: PaymentRequired): Promise<PaymentPayload>;
82
+ /**
83
+ * Parses response headers into protocol types, fires payment response hooks (v2 only),
84
+ * and returns whether a hook signaled recovery.
85
+ *
86
+ * Called by transport wrappers (fetch, axios) after the paid request completes.
87
+ *
88
+ * @param paymentPayload - The payload that was sent with the request
89
+ * @param getHeader - Function to retrieve a response header by name
90
+ * @param status - The HTTP status code of the response
91
+ * @returns Whether a hook recovered and the parsed settle response (if any)
92
+ */
93
+ processPaymentResult(paymentPayload: PaymentPayload, getHeader: (name: string) => string | null | undefined, status: number): Promise<{
94
+ recovered: boolean;
95
+ settleResponse?: SettleResponse;
96
+ }>;
97
+ /**
98
+ * Parses HTTP status, headers, and body into an `HTTPResourceResponse`.
99
+ *
100
+ * Decodes the x402 payment header into `header`: the `PAYMENT-RESPONSE`
101
+ * settlement if present, otherwise the `PAYMENT-REQUIRED` declaration on
102
+ * 402 responses (whose `error` field carries the server's failure reason).
103
+ *
104
+ * @param args - Normalized response inputs from any HTTP transport
105
+ * @param args.status - HTTP response status code
106
+ * @param args.getHeader - Callback to read response headers by name
107
+ * @param args.body - Response body payload
108
+ * @returns The parsed status, body, and decoded payment header
109
+ */
110
+ parsePaymentResult(args: {
111
+ status: number;
112
+ getHeader: (name: string) => string | null | undefined;
113
+ body: unknown;
114
+ }): HTTPResourceResponse;
115
+ /**
116
+ * Parses a fetch Response into an `HTTPResourceResponse` for app-level convenience.
117
+ *
118
+ * @param response - The fetch Response to process
119
+ * @returns The parsed status, body, and decoded payment header
120
+ */
121
+ processResponse(response: Response): Promise<HTTPResourceResponse>;
122
+ /**
123
+ * Manual HTTP hooks run before extension hooks scoped to the 402 response.
124
+ *
125
+ * @param paymentRequired - The payment required response from the server
126
+ * @returns Hooks in invocation order
127
+ */
128
+ private getPaymentRequiredHooks;
129
+ }
130
+ /**
131
+ * Parsed result of an HTTP request to an x402 resource.
132
+ */
133
+ type HTTPResourceResponse = {
134
+ /** HTTP status code. */
135
+ status: number;
136
+ /** x402 payment outcome. */
137
+ paymentStatus: HTTPPaymentStatus;
138
+ /** Parsed response body. */
139
+ body: unknown;
140
+ /**
141
+ * Decoded x402 payment header, if present:
142
+ * - SettleResponse (from PAYMENT-RESPONSE / X-PAYMENT-RESPONSE)
143
+ * - PaymentRequired (from PAYMENT-REQUIRED; its `error` carries the server reason)
144
+ */
145
+ header?: SettleResponse | PaymentRequired;
146
+ };
147
+ type HTTPPaymentStatus = "settled" | "settle_failed" | "payment_required" | "none";
148
+
149
+ export { type HTTPClientExtensionHooks, type HTTPPaymentStatus, type HTTPResourceResponse, type PaymentRequiredContext, type PaymentRequiredHook, x402Client, x402HTTPClient };