@x402/next 2.7.0 → 2.8.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.
@@ -155,17 +155,37 @@ var NextAdapter = class {
155
155
  };
156
156
 
157
157
  // src/utils.ts
158
+ var getFacilitatorResponseError = import_server2.getFacilitatorResponseError;
159
+ function createFacilitatorErrorResponse(error) {
160
+ return new import_server.NextResponse(JSON.stringify({ error: error.message }), {
161
+ status: 502,
162
+ headers: { "Content-Type": "application/json" }
163
+ });
164
+ }
158
165
  function prepareHttpServer(httpServer, paywall, syncFacilitatorOnStart = true) {
159
166
  if (paywall) {
160
167
  httpServer.registerPaywallProvider(paywall);
161
168
  }
162
169
  let initPromise = syncFacilitatorOnStart ? httpServer.initialize() : null;
170
+ let isInitialized = false;
163
171
  return {
164
172
  httpServer,
173
+ /**
174
+ * Ensures facilitator initialization succeeds once, while allowing retries after failures.
175
+ */
165
176
  async init() {
166
- if (initPromise) {
177
+ if (!syncFacilitatorOnStart || isInitialized) {
178
+ return;
179
+ }
180
+ if (!initPromise) {
181
+ initPromise = httpServer.initialize();
182
+ }
183
+ try {
167
184
  await initPromise;
185
+ isInitialized = true;
186
+ } catch (error) {
168
187
  initPromise = null;
188
+ throw error;
169
189
  }
170
190
  }
171
191
  };
@@ -219,6 +239,9 @@ async function handleSettlement(httpServer, response, paymentPayload, paymentReq
219
239
  });
220
240
  return response;
221
241
  } catch (error) {
242
+ if (error instanceof import_server2.FacilitatorResponseError) {
243
+ return createFacilitatorErrorResponse(error);
244
+ }
222
245
  console.error("Settlement failed:", error);
223
246
  return new import_server.NextResponse(JSON.stringify({}), {
224
247
  status: 402,
@@ -248,12 +271,28 @@ function paymentProxyFromHTTPServer(httpServer, paywallConfig, paywall, syncFaci
248
271
  if (!httpServer.requiresPayment(context)) {
249
272
  return import_server4.NextResponse.next();
250
273
  }
251
- await init();
274
+ try {
275
+ await init();
276
+ } catch (error) {
277
+ const facilitatorError = getFacilitatorResponseError(error);
278
+ if (facilitatorError) {
279
+ return createFacilitatorErrorResponse(facilitatorError);
280
+ }
281
+ throw error;
282
+ }
252
283
  if (bazaarPromise) {
253
284
  await bazaarPromise;
254
285
  bazaarPromise = null;
255
286
  }
256
- const result = await httpServer.processHTTPRequest(context, paywallConfig);
287
+ let result;
288
+ try {
289
+ result = await httpServer.processHTTPRequest(context, paywallConfig);
290
+ } catch (error) {
291
+ if (error instanceof import_server3.FacilitatorResponseError) {
292
+ return createFacilitatorErrorResponse(error);
293
+ }
294
+ throw error;
295
+ }
257
296
  switch (result.type) {
258
297
  case "no-payment-required":
259
298
  return import_server4.NextResponse.next();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts","../../src/utils.ts","../../src/adapter.ts"],"sourcesContent":["import {\n PaywallConfig,\n PaywallProvider,\n x402ResourceServer,\n RoutesConfig,\n RouteConfig,\n FacilitatorClient,\n} from \"@x402/core/server\";\nimport { SchemeNetworkServer, Network } from \"@x402/core/types\";\nimport { NextRequest, NextResponse } from \"next/server\";\nimport {\n prepareHttpServer,\n createRequestContext,\n handlePaymentError,\n handleSettlement,\n} from \"./utils\";\nimport { x402HTTPResourceServer } from \"@x402/core/server\";\n\n/**\n * Configuration for registering a payment scheme with a specific network\n */\nexport interface SchemeRegistration {\n /**\n * The network identifier (e.g., 'eip155:84532', 'solana:mainnet')\n */\n network: Network;\n\n /**\n * The scheme server implementation for this network\n */\n server: SchemeNetworkServer;\n}\n\n/**\n * Next.js payment proxy for x402 protocol (direct HTTP server instance).\n *\n * Use this when you need to configure HTTP-level hooks.\n *\n * @param httpServer - Pre-configured x402HTTPResourceServer instance\n * @param paywallConfig - Optional configuration for the built-in paywall UI\n * @param paywall - Optional custom paywall provider (overrides default)\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)\n * @returns Next.js proxy handler\n *\n * @example\n * ```typescript\n * import { paymentProxyFromHTTPServer, x402ResourceServer, x402HTTPResourceServer } from \"@x402/next\";\n *\n * const resourceServer = new x402ResourceServer(facilitatorClient)\n * .register(NETWORK, new ExactEvmScheme());\n *\n * const httpServer = new x402HTTPResourceServer(resourceServer, routes)\n * .onProtectedRequest(requestHook);\n *\n * export const proxy = paymentProxyFromHTTPServer(httpServer);\n * ```\n */\nexport function paymentProxyFromHTTPServer(\n httpServer: x402HTTPResourceServer,\n paywallConfig?: PaywallConfig,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n) {\n const { init } = prepareHttpServer(httpServer, paywall, syncFacilitatorOnStart);\n\n // Dynamically register bazaar extension if routes declare it and not already registered\n // Skip if pre-registered (e.g., in serverless environments where static imports are used)\n let bazaarPromise: Promise<void> | null = null;\n if (checkIfBazaarNeeded(httpServer.routes) && !httpServer.server.hasExtension(\"bazaar\")) {\n bazaarPromise = import(/* webpackIgnore: true */ \"@x402/extensions/bazaar\")\n .then(({ bazaarResourceServerExtension }) => {\n httpServer.server.registerExtension(bazaarResourceServerExtension);\n })\n .catch(err => {\n console.error(\"Failed to load bazaar extension:\", err);\n });\n }\n\n return async (req: NextRequest) => {\n const context = createRequestContext(req);\n\n // Check if route requires payment before initializing facilitator\n if (!httpServer.requiresPayment(context)) {\n return NextResponse.next();\n }\n\n // Only initialize when processing a protected route\n await init();\n\n // Await bazaar extension loading if needed\n if (bazaarPromise) {\n await bazaarPromise;\n bazaarPromise = null;\n }\n\n // Process payment requirement check\n const result = await httpServer.processHTTPRequest(context, paywallConfig);\n\n // Handle the different result types\n switch (result.type) {\n case \"no-payment-required\":\n // No payment needed, proceed directly to the route handler\n return NextResponse.next();\n\n case \"payment-error\":\n return handlePaymentError(result.response);\n\n case \"payment-verified\": {\n // Payment is valid, need to wrap response for settlement\n const { paymentPayload, paymentRequirements, declaredExtensions } = result;\n\n // Proceed to the next proxy or route handler\n const nextResponse = NextResponse.next();\n return handleSettlement(\n httpServer,\n nextResponse,\n paymentPayload,\n paymentRequirements,\n declaredExtensions,\n context,\n );\n }\n }\n };\n}\n\n/**\n * Next.js payment proxy for x402 protocol (direct server instance).\n *\n * Use this when you want to pass a pre-configured x402ResourceServer instance.\n * This provides more flexibility for testing, custom configuration, and reusing\n * server instances across multiple proxies.\n *\n * @param routes - Route configurations for protected endpoints\n * @param server - Pre-configured x402ResourceServer instance\n * @param paywallConfig - Optional configuration for the built-in paywall UI\n * @param paywall - Optional custom paywall provider (overrides default)\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)\n * @returns Next.js proxy handler\n *\n * @example\n * ```typescript\n * import { paymentProxy } from \"@x402/next\";\n *\n * const server = new x402ResourceServer(myFacilitatorClient)\n * .register(NETWORK, new ExactEvmScheme());\n *\n * export const proxy = paymentProxy(routes, server, paywallConfig);\n * ```\n */\nexport function paymentProxy(\n routes: RoutesConfig,\n server: x402ResourceServer,\n paywallConfig?: PaywallConfig,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n) {\n // Create the x402 HTTP server instance with the resource server\n const httpServer = new x402HTTPResourceServer(server, routes);\n\n return paymentProxyFromHTTPServer(httpServer, paywallConfig, paywall, syncFacilitatorOnStart);\n}\n\n/**\n * Next.js payment proxy for x402 protocol (configuration-based).\n *\n * Use this when you want to quickly set up proxy with simple configuration.\n * This function creates and configures the x402ResourceServer internally.\n *\n * @param routes - Route configurations for protected endpoints\n * @param facilitatorClients - Optional facilitator client(s) for payment processing\n * @param schemes - Optional array of scheme registrations for server-side payment processing\n * @param paywallConfig - Optional configuration for the built-in paywall UI\n * @param paywall - Optional custom paywall provider (overrides default)\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)\n * @returns Next.js proxy handler\n *\n * @example\n * ```typescript\n * import { paymentProxyFromConfig } from \"@x402/next\";\n *\n * export const proxy = paymentProxyFromConfig(\n * routes,\n * myFacilitatorClient,\n * [{ network: \"eip155:8453\", server: evmSchemeServer }],\n * paywallConfig\n * );\n * ```\n */\nexport function paymentProxyFromConfig(\n routes: RoutesConfig,\n facilitatorClients?: FacilitatorClient | FacilitatorClient[],\n schemes?: SchemeRegistration[],\n paywallConfig?: PaywallConfig,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n) {\n const ResourceServer = new x402ResourceServer(facilitatorClients);\n\n if (schemes) {\n schemes.forEach(({ network, server: schemeServer }) => {\n ResourceServer.register(network, schemeServer);\n });\n }\n\n // Use the direct paymentProxy with the configured server\n // Note: paymentProxy handles dynamic bazaar registration\n return paymentProxy(routes, ResourceServer, paywallConfig, paywall, syncFacilitatorOnStart);\n}\n\n/**\n * Wraps a Next.js App Router API route handler with x402 payment protection (HTTP server instance).\n *\n * Use this when you need to configure HTTP-level hooks.\n *\n * @param routeHandler - The API route handler function to wrap\n * @param httpServer - Pre-configured x402HTTPResourceServer instance\n * @param paywallConfig - Optional configuration for the built-in paywall UI\n * @param paywall - Optional custom paywall provider (overrides default)\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)\n * @returns A wrapped Next.js route handler\n *\n * @example\n * ```typescript\n * import { NextRequest, NextResponse } from \"next/server\";\n * import { withX402FromHTTPServer, x402ResourceServer, x402HTTPResourceServer } from \"@x402/next\";\n *\n * const resourceServer = new x402ResourceServer(facilitatorClient)\n * .register(NETWORK, new ExactEvmScheme());\n *\n * const httpServer = new x402HTTPResourceServer(resourceServer, { \"*\": routeConfig })\n * .onProtectedRequest(requestHook);\n *\n * const handler = async (request: NextRequest) => {\n * return NextResponse.json({ data: \"protected content\" });\n * };\n *\n * export const GET = withX402FromHTTPServer(handler, httpServer);\n * ```\n */\nexport function withX402FromHTTPServer<T = unknown>(\n routeHandler: (request: NextRequest) => Promise<NextResponse<T>>,\n httpServer: x402HTTPResourceServer,\n paywallConfig?: PaywallConfig,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n): (request: NextRequest) => Promise<NextResponse<T>> {\n const { init } = prepareHttpServer(httpServer, paywall, syncFacilitatorOnStart);\n\n // Dynamically register bazaar extension if route declares it and not already registered\n // Skip if pre-registered (e.g., in serverless environments where static imports are used)\n let bazaarPromise: Promise<void> | null = null;\n if (checkIfBazaarNeeded(httpServer.routes) && !httpServer.server.hasExtension(\"bazaar\")) {\n bazaarPromise = import(/* webpackIgnore: true */ \"@x402/extensions/bazaar\")\n .then(({ bazaarResourceServerExtension }) => {\n httpServer.server.registerExtension(bazaarResourceServerExtension);\n })\n .catch(err => {\n console.error(\"Failed to load bazaar extension:\", err);\n });\n }\n\n return async (request: NextRequest): Promise<NextResponse<T>> => {\n // Only initialize when processing a protected route\n await init();\n\n // Await bazaar extension loading if needed\n if (bazaarPromise) {\n await bazaarPromise;\n bazaarPromise = null;\n }\n\n const context = createRequestContext(request);\n\n // Process payment requirement check\n const result = await httpServer.processHTTPRequest(context, paywallConfig);\n\n // Handle the different result types\n switch (result.type) {\n case \"no-payment-required\":\n // No payment needed, proceed directly to the route handler\n return routeHandler(request);\n\n case \"payment-error\":\n return handlePaymentError(result.response) as NextResponse<T>;\n\n case \"payment-verified\": {\n // Payment is valid, need to wrap response for settlement\n const { paymentPayload, paymentRequirements, declaredExtensions } = result;\n const handlerResponse = await routeHandler(request);\n return handleSettlement(\n httpServer,\n handlerResponse,\n paymentPayload,\n paymentRequirements,\n declaredExtensions,\n context,\n ) as Promise<NextResponse<T>>;\n }\n }\n };\n}\n\n/**\n * Wraps a Next.js App Router API route handler with x402 payment protection.\n *\n * Unlike `paymentProxy` which works as middleware, `withX402` wraps individual route handlers\n * and guarantees that payment settlement only occurs after the handler returns a successful\n * response (status < 400). This provides more precise control over when payments are settled.\n *\n * @param routeHandler - The API route handler function to wrap\n * @param routeConfig - Payment configuration for this specific route\n * @param server - Pre-configured x402ResourceServer instance\n * @param paywallConfig - Optional configuration for the built-in paywall UI\n * @param paywall - Optional custom paywall provider (overrides default)\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)\n * @returns A wrapped Next.js route handler\n *\n * @example\n * ```typescript\n * import { NextRequest, NextResponse } from \"next/server\";\n * import { withX402 } from \"@x402/next\";\n *\n * const server = new x402ResourceServer(myFacilitatorClient)\n * .register(NETWORK, new ExactEvmScheme());\n *\n * const handler = async (request: NextRequest) => {\n * return NextResponse.json({ data: \"protected content\" });\n * };\n *\n * export const GET = withX402(\n * handler,\n * {\n * accepts: {\n * scheme: \"exact\",\n * payTo: \"0x123...\",\n * price: \"$0.01\",\n * network: \"eip155:84532\",\n * },\n * description: \"Access to protected API\",\n * },\n * server,\n * );\n * ```\n */\nexport function withX402<T = unknown>(\n routeHandler: (request: NextRequest) => Promise<NextResponse<T>>,\n routeConfig: RouteConfig,\n server: x402ResourceServer,\n paywallConfig?: PaywallConfig,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n): (request: NextRequest) => Promise<NextResponse<T>> {\n const routes = { \"*\": routeConfig };\n // Create the x402 HTTP server instance with the resource server\n const httpServer = new x402HTTPResourceServer(server, routes);\n\n return withX402FromHTTPServer(\n routeHandler,\n httpServer,\n paywallConfig,\n paywall,\n syncFacilitatorOnStart,\n );\n}\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 */\nfunction checkIfBazaarNeeded(routes: RoutesConfig): boolean {\n // Handle single route config\n if (\"accepts\" in routes) {\n return !!(routes.extensions && \"bazaar\" in routes.extensions);\n }\n\n // Handle multiple routes\n return Object.values(routes).some(routeConfig => {\n return !!(routeConfig.extensions && \"bazaar\" in routeConfig.extensions);\n });\n}\n\nexport type {\n PaymentRequired,\n PaymentRequirements,\n PaymentPayload,\n Network,\n SchemeNetworkServer,\n} from \"@x402/core/types\";\n\nexport type { PaywallProvider, PaywallConfig, RouteConfig } from \"@x402/core/server\";\n\nexport {\n x402ResourceServer,\n x402HTTPResourceServer,\n RouteConfigurationError,\n} from \"@x402/core/server\";\n\nexport type { RouteValidationError } from \"@x402/core/server\";\n\nexport { NextAdapter } from \"./adapter\";\n","import { NextRequest, NextResponse } from \"next/server\";\nimport {\n HTTPRequestContext,\n HTTPResponseInstructions,\n PaywallProvider,\n x402HTTPResourceServer,\n x402ResourceServer,\n RoutesConfig,\n} from \"@x402/core/server\";\nimport { PaymentPayload, PaymentRequirements } from \"@x402/core/types\";\nimport { NextAdapter } from \"./adapter\";\n\n/**\n * Result of createHttpServer\n */\nexport interface HttpServerInstance {\n httpServer: x402HTTPResourceServer;\n init: () => Promise<void>;\n}\n\n/**\n * Prepares an existing x402HTTPResourceServer with initialization logic\n *\n * @param httpServer - Pre-configured x402HTTPResourceServer instance\n * @param paywall - Optional paywall provider for custom payment UI\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on start (defaults to true)\n * @returns The HTTP server instance with initialization function\n */\nexport function prepareHttpServer(\n httpServer: x402HTTPResourceServer,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n): HttpServerInstance {\n // Register custom paywall provider if provided\n if (paywall) {\n httpServer.registerPaywallProvider(paywall);\n }\n\n // Store initialization promise (not the result)\n // httpServer.initialize() fetches facilitator support and validates routes\n let initPromise: Promise<void> | null = syncFacilitatorOnStart ? httpServer.initialize() : null;\n\n return {\n httpServer,\n async init() {\n // Ensure initialization completes before processing\n if (initPromise) {\n await initPromise;\n initPromise = null; // Clear after first await\n }\n },\n };\n}\n\n/**\n * Creates and configures the x402 HTTP server with initialization logic\n *\n * @param routes - The route configuration for the server\n * @param server - The x402 resource server instance\n * @param paywall - Optional paywall provider for custom payment UI\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on start (defaults to true)\n * @returns The HTTP server instance with initialization function\n */\nexport function createHttpServer(\n routes: RoutesConfig,\n server: x402ResourceServer,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n): HttpServerInstance {\n // Create the x402 HTTP server instance with the resource server\n const httpServer = new x402HTTPResourceServer(server, routes);\n\n return prepareHttpServer(httpServer, paywall, syncFacilitatorOnStart);\n}\n\n/**\n * Creates HTTP request context from a Next.js request\n *\n * @param request - The Next.js request object\n * @returns The HTTP request context for x402 processing\n */\nexport function createRequestContext(request: NextRequest): HTTPRequestContext {\n // Create adapter and context\n const adapter = new NextAdapter(request);\n return {\n adapter,\n path: request.nextUrl.pathname,\n method: request.method,\n paymentHeader: adapter.getHeader(\"payment-signature\") || adapter.getHeader(\"x-payment\"),\n };\n}\n\n/**\n * Handles payment error result by creating a 402 response\n *\n * @param response - The HTTP response instructions from payment verification\n * @returns A Next.js response with the appropriate 402 status and headers\n */\nexport function handlePaymentError(response: HTTPResponseInstructions): NextResponse {\n // Payment required but not provided or invalid\n const headers = new Headers(response.headers);\n if (response.isHtml) {\n headers.set(\"Content-Type\", \"text/html\");\n return new NextResponse(response.body as string, {\n status: response.status,\n headers,\n });\n }\n headers.set(\"Content-Type\", \"application/json\");\n return new NextResponse(JSON.stringify(response.body || {}), {\n status: response.status,\n headers,\n });\n}\n\n/**\n * Handles settlement after a successful response\n *\n * @param httpServer - The x402 HTTP resource server instance\n * @param response - The Next.js response from the protected route\n * @param paymentPayload - The payment payload from the client\n * @param paymentRequirements - The payment requirements for the route\n * @param declaredExtensions - Optional declared extensions (for per-key enrichment)\n * @param httpContext - Optional HTTP request context for extensions\n * @returns The response with settlement headers or an error response if settlement fails\n */\nexport async function handleSettlement(\n httpServer: x402HTTPResourceServer,\n response: NextResponse,\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n declaredExtensions?: Record<string, unknown>,\n httpContext?: HTTPRequestContext,\n): Promise<NextResponse> {\n // If the response from the protected route is >= 400, do not settle payment\n if (response.status >= 400) {\n return response;\n }\n\n try {\n // Get response body for extensions\n const responseBody = Buffer.from(await response.clone().arrayBuffer());\n\n const result = await httpServer.processSettlement(\n paymentPayload,\n paymentRequirements,\n declaredExtensions,\n { request: httpContext, responseBody },\n );\n\n if (!result.success) {\n // Settlement failed - do not return the protected resource\n const { response } = result;\n const body = response.isHtml ? response.body : JSON.stringify(response.body ?? {});\n return new NextResponse(body, {\n status: response.status,\n headers: response.headers,\n });\n }\n\n // Settlement succeeded - add headers and return original response\n Object.entries(result.headers).forEach(([key, value]) => {\n response.headers.set(key, value);\n });\n\n return response;\n } catch (error) {\n console.error(\"Settlement failed:\", error);\n // If settlement fails, return an error response\n return new NextResponse(JSON.stringify({}), {\n status: 402,\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n}\n","import { HTTPAdapter } from \"@x402/core/server\";\nimport { NextRequest } from \"next/server\";\n\n/**\n * Next.js adapter implementation\n */\nexport class NextAdapter implements HTTPAdapter {\n /**\n * Creates a new NextAdapter instance.\n *\n * @param req - The Next.js request object\n */\n constructor(private req: NextRequest) {}\n\n /**\n * Gets a header value from the request.\n *\n * @param name - The header name\n * @returns The header value or undefined\n */\n getHeader(name: string): string | undefined {\n return this.req.headers.get(name) || undefined;\n }\n\n /**\n * Gets the HTTP method of the request.\n *\n * @returns The HTTP method\n */\n getMethod(): string {\n return this.req.method;\n }\n\n /**\n * Gets the path of the request.\n *\n * @returns The request path\n */\n getPath(): string {\n return this.req.nextUrl.pathname;\n }\n\n /**\n * Gets the full URL of the request.\n *\n * @returns The full request URL\n */\n getUrl(): string {\n return this.req.url;\n }\n\n /**\n * Gets the Accept header from the request.\n *\n * @returns The Accept header value or empty string\n */\n getAcceptHeader(): string {\n return this.req.headers.get(\"Accept\") || \"\";\n }\n\n /**\n * Gets the User-Agent header from the request.\n *\n * @returns The User-Agent header value or empty string\n */\n getUserAgent(): string {\n return this.req.headers.get(\"User-Agent\") || \"\";\n }\n\n /**\n * Gets all query parameters from the request URL.\n *\n * @returns Record of query parameter key-value pairs\n */\n getQueryParams(): Record<string, string | string[]> {\n const params: Record<string, string | string[]> = {};\n this.req.nextUrl.searchParams.forEach((value, key) => {\n const existing = params[key];\n if (existing) {\n if (Array.isArray(existing)) {\n existing.push(value);\n } else {\n params[key] = [existing, value];\n }\n } else {\n params[key] = value;\n }\n });\n return params;\n }\n\n /**\n * Gets 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 const all = this.req.nextUrl.searchParams.getAll(name);\n if (all.length === 0) return undefined;\n if (all.length === 1) return all[0];\n return all;\n }\n\n /**\n * Gets the parsed request body.\n *\n * @returns Promise resolving to the parsed request body\n */\n async getBody(): Promise<unknown> {\n try {\n return await this.req.json();\n } catch {\n return undefined;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,iBAOO;AAEP,IAAAA,iBAA0C;;;ACT1C,oBAA0C;AAC1C,IAAAC,iBAOO;;;ACFA,IAAM,cAAN,MAAyC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM9C,YAAoB,KAAkB;AAAlB;AAAA,EAAmB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQvC,UAAU,MAAkC;AAC1C,WAAO,KAAK,IAAI,QAAQ,IAAI,IAAI,KAAK;AAAA,EACvC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,YAAoB;AAClB,WAAO,KAAK,IAAI;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,UAAkB;AAChB,WAAO,KAAK,IAAI,QAAQ;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,SAAiB;AACf,WAAO,KAAK,IAAI;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,kBAA0B;AACxB,WAAO,KAAK,IAAI,QAAQ,IAAI,QAAQ,KAAK;AAAA,EAC3C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,eAAuB;AACrB,WAAO,KAAK,IAAI,QAAQ,IAAI,YAAY,KAAK;AAAA,EAC/C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,iBAAoD;AAClD,UAAM,SAA4C,CAAC;AACnD,SAA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AAO;AAAA,UACL;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AA4CO,SAAS,SACd,cACA,aACA,QACA,eACA,SACA,yBAAkC,MACkB;AACpD,QAAM,SAAS,EAAE,KAAK,YAAY;AAElC,QAAM,aAAa,IAAI,sCAAuB,QAAQ,MAAM;AAE5D,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAQA,SAAS,oBAAoB,QAA+B;AAE1D,MAAI,aAAa,QAAQ;AACvB,WAAO,CAAC,EAAE,OAAO,cAAc,YAAY,OAAO;AAAA,EACpD;AAGA,SAAO,OAAO,OAAO,MAAM,EAAE,KAAK,iBAAe;AAC/C,WAAO,CAAC,EAAE,YAAY,cAAc,YAAY,YAAY;AAAA,EAC9D,CAAC;AACH;","names":["import_server","import_server","response","import_server"]}
1
+ {"version":3,"sources":["../../src/index.ts","../../src/utils.ts","../../src/adapter.ts"],"sourcesContent":["import {\n PaywallConfig,\n PaywallProvider,\n x402ResourceServer,\n RoutesConfig,\n RouteConfig,\n FacilitatorClient,\n FacilitatorResponseError,\n} from \"@x402/core/server\";\nimport { SchemeNetworkServer, Network } from \"@x402/core/types\";\nimport { NextRequest, NextResponse } from \"next/server\";\nimport {\n prepareHttpServer,\n createRequestContext,\n handlePaymentError,\n handleSettlement,\n createFacilitatorErrorResponse,\n getFacilitatorResponseError,\n} from \"./utils\";\nimport { x402HTTPResourceServer } from \"@x402/core/server\";\n\n/**\n * Configuration for registering a payment scheme with a specific network\n */\nexport interface SchemeRegistration {\n /**\n * The network identifier (e.g., 'eip155:84532', 'solana:mainnet')\n */\n network: Network;\n\n /**\n * The scheme server implementation for this network\n */\n server: SchemeNetworkServer;\n}\n\n/**\n * Next.js payment proxy for x402 protocol (direct HTTP server instance).\n *\n * Use this when you need to configure HTTP-level hooks.\n *\n * @param httpServer - Pre-configured x402HTTPResourceServer instance\n * @param paywallConfig - Optional configuration for the built-in paywall UI\n * @param paywall - Optional custom paywall provider (overrides default)\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)\n * @returns Next.js proxy handler\n *\n * @example\n * ```typescript\n * import { paymentProxyFromHTTPServer, x402ResourceServer, x402HTTPResourceServer } from \"@x402/next\";\n *\n * const resourceServer = new x402ResourceServer(facilitatorClient)\n * .register(NETWORK, new ExactEvmScheme());\n *\n * const httpServer = new x402HTTPResourceServer(resourceServer, routes)\n * .onProtectedRequest(requestHook);\n *\n * export const proxy = paymentProxyFromHTTPServer(httpServer);\n * ```\n */\nexport function paymentProxyFromHTTPServer(\n httpServer: x402HTTPResourceServer,\n paywallConfig?: PaywallConfig,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n) {\n const { init } = prepareHttpServer(httpServer, paywall, syncFacilitatorOnStart);\n\n // Dynamically register bazaar extension if routes declare it and not already registered\n // Skip if pre-registered (e.g., in serverless environments where static imports are used)\n let bazaarPromise: Promise<void> | null = null;\n if (checkIfBazaarNeeded(httpServer.routes) && !httpServer.server.hasExtension(\"bazaar\")) {\n bazaarPromise = import(/* webpackIgnore: true */ \"@x402/extensions/bazaar\")\n .then(({ bazaarResourceServerExtension }) => {\n httpServer.server.registerExtension(bazaarResourceServerExtension);\n })\n .catch(err => {\n console.error(\"Failed to load bazaar extension:\", err);\n });\n }\n\n return async (req: NextRequest) => {\n const context = createRequestContext(req);\n\n // Check if route requires payment before initializing facilitator\n if (!httpServer.requiresPayment(context)) {\n return NextResponse.next();\n }\n\n // Only initialize when processing a protected route\n try {\n await init();\n } catch (error) {\n const facilitatorError = getFacilitatorResponseError(error);\n if (facilitatorError) {\n return createFacilitatorErrorResponse(facilitatorError);\n }\n throw error;\n }\n\n // Await bazaar extension loading if needed\n if (bazaarPromise) {\n await bazaarPromise;\n bazaarPromise = null;\n }\n\n // Process payment requirement check\n let result: Awaited<ReturnType<x402HTTPResourceServer[\"processHTTPRequest\"]>>;\n try {\n result = await httpServer.processHTTPRequest(context, paywallConfig);\n } catch (error) {\n if (error instanceof FacilitatorResponseError) {\n return createFacilitatorErrorResponse(error);\n }\n throw error;\n }\n\n // Handle the different result types\n switch (result.type) {\n case \"no-payment-required\":\n // No payment needed, proceed directly to the route handler\n return NextResponse.next();\n\n case \"payment-error\":\n return handlePaymentError(result.response);\n\n case \"payment-verified\": {\n // Payment is valid, need to wrap response for settlement\n const { paymentPayload, paymentRequirements, declaredExtensions } = result;\n\n // Proceed to the next proxy or route handler\n const nextResponse = NextResponse.next();\n return handleSettlement(\n httpServer,\n nextResponse,\n paymentPayload,\n paymentRequirements,\n declaredExtensions,\n context,\n );\n }\n }\n };\n}\n\n/**\n * Next.js payment proxy for x402 protocol (direct server instance).\n *\n * Use this when you want to pass a pre-configured x402ResourceServer instance.\n * This provides more flexibility for testing, custom configuration, and reusing\n * server instances across multiple proxies.\n *\n * @param routes - Route configurations for protected endpoints\n * @param server - Pre-configured x402ResourceServer instance\n * @param paywallConfig - Optional configuration for the built-in paywall UI\n * @param paywall - Optional custom paywall provider (overrides default)\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)\n * @returns Next.js proxy handler\n *\n * @example\n * ```typescript\n * import { paymentProxy } from \"@x402/next\";\n *\n * const server = new x402ResourceServer(myFacilitatorClient)\n * .register(NETWORK, new ExactEvmScheme());\n *\n * export const proxy = paymentProxy(routes, server, paywallConfig);\n * ```\n */\nexport function paymentProxy(\n routes: RoutesConfig,\n server: x402ResourceServer,\n paywallConfig?: PaywallConfig,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n) {\n // Create the x402 HTTP server instance with the resource server\n const httpServer = new x402HTTPResourceServer(server, routes);\n\n return paymentProxyFromHTTPServer(httpServer, paywallConfig, paywall, syncFacilitatorOnStart);\n}\n\n/**\n * Next.js payment proxy for x402 protocol (configuration-based).\n *\n * Use this when you want to quickly set up proxy with simple configuration.\n * This function creates and configures the x402ResourceServer internally.\n *\n * @param routes - Route configurations for protected endpoints\n * @param facilitatorClients - Optional facilitator client(s) for payment processing\n * @param schemes - Optional array of scheme registrations for server-side payment processing\n * @param paywallConfig - Optional configuration for the built-in paywall UI\n * @param paywall - Optional custom paywall provider (overrides default)\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)\n * @returns Next.js proxy handler\n *\n * @example\n * ```typescript\n * import { paymentProxyFromConfig } from \"@x402/next\";\n *\n * export const proxy = paymentProxyFromConfig(\n * routes,\n * myFacilitatorClient,\n * [{ network: \"eip155:8453\", server: evmSchemeServer }],\n * paywallConfig\n * );\n * ```\n */\nexport function paymentProxyFromConfig(\n routes: RoutesConfig,\n facilitatorClients?: FacilitatorClient | FacilitatorClient[],\n schemes?: SchemeRegistration[],\n paywallConfig?: PaywallConfig,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n) {\n const ResourceServer = new x402ResourceServer(facilitatorClients);\n\n if (schemes) {\n schemes.forEach(({ network, server: schemeServer }) => {\n ResourceServer.register(network, schemeServer);\n });\n }\n\n // Use the direct paymentProxy with the configured server\n // Note: paymentProxy handles dynamic bazaar registration\n return paymentProxy(routes, ResourceServer, paywallConfig, paywall, syncFacilitatorOnStart);\n}\n\n/**\n * Wraps a Next.js App Router API route handler with x402 payment protection (HTTP server instance).\n *\n * Use this when you need to configure HTTP-level hooks.\n *\n * @param routeHandler - The API route handler function to wrap\n * @param httpServer - Pre-configured x402HTTPResourceServer instance\n * @param paywallConfig - Optional configuration for the built-in paywall UI\n * @param paywall - Optional custom paywall provider (overrides default)\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)\n * @returns A wrapped Next.js route handler\n *\n * @example\n * ```typescript\n * import { NextRequest, NextResponse } from \"next/server\";\n * import { withX402FromHTTPServer, x402ResourceServer, x402HTTPResourceServer } from \"@x402/next\";\n *\n * const resourceServer = new x402ResourceServer(facilitatorClient)\n * .register(NETWORK, new ExactEvmScheme());\n *\n * const httpServer = new x402HTTPResourceServer(resourceServer, { \"*\": routeConfig })\n * .onProtectedRequest(requestHook);\n *\n * const handler = async (request: NextRequest) => {\n * return NextResponse.json({ data: \"protected content\" });\n * };\n *\n * export const GET = withX402FromHTTPServer(handler, httpServer);\n * ```\n */\nexport function withX402FromHTTPServer<T = unknown>(\n routeHandler: (request: NextRequest) => Promise<NextResponse<T>>,\n httpServer: x402HTTPResourceServer,\n paywallConfig?: PaywallConfig,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n): (request: NextRequest) => Promise<NextResponse<T>> {\n const { init } = prepareHttpServer(httpServer, paywall, syncFacilitatorOnStart);\n\n // Dynamically register bazaar extension if route declares it and not already registered\n // Skip if pre-registered (e.g., in serverless environments where static imports are used)\n let bazaarPromise: Promise<void> | null = null;\n if (checkIfBazaarNeeded(httpServer.routes) && !httpServer.server.hasExtension(\"bazaar\")) {\n bazaarPromise = import(/* webpackIgnore: true */ \"@x402/extensions/bazaar\")\n .then(({ bazaarResourceServerExtension }) => {\n httpServer.server.registerExtension(bazaarResourceServerExtension);\n })\n .catch(err => {\n console.error(\"Failed to load bazaar extension:\", err);\n });\n }\n\n return async (request: NextRequest): Promise<NextResponse<T>> => {\n // Only initialize when processing a protected route\n await init();\n\n // Await bazaar extension loading if needed\n if (bazaarPromise) {\n await bazaarPromise;\n bazaarPromise = null;\n }\n\n const context = createRequestContext(request);\n\n // Process payment requirement check\n const result = await httpServer.processHTTPRequest(context, paywallConfig);\n\n // Handle the different result types\n switch (result.type) {\n case \"no-payment-required\":\n // No payment needed, proceed directly to the route handler\n return routeHandler(request);\n\n case \"payment-error\":\n return handlePaymentError(result.response) as NextResponse<T>;\n\n case \"payment-verified\": {\n // Payment is valid, need to wrap response for settlement\n const { paymentPayload, paymentRequirements, declaredExtensions } = result;\n const handlerResponse = await routeHandler(request);\n return handleSettlement(\n httpServer,\n handlerResponse,\n paymentPayload,\n paymentRequirements,\n declaredExtensions,\n context,\n ) as Promise<NextResponse<T>>;\n }\n }\n };\n}\n\n/**\n * Wraps a Next.js App Router API route handler with x402 payment protection.\n *\n * Unlike `paymentProxy` which works as middleware, `withX402` wraps individual route handlers\n * and guarantees that payment settlement only occurs after the handler returns a successful\n * response (status < 400). This provides more precise control over when payments are settled.\n *\n * @param routeHandler - The API route handler function to wrap\n * @param routeConfig - Payment configuration for this specific route\n * @param server - Pre-configured x402ResourceServer instance\n * @param paywallConfig - Optional configuration for the built-in paywall UI\n * @param paywall - Optional custom paywall provider (overrides default)\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)\n * @returns A wrapped Next.js route handler\n *\n * @example\n * ```typescript\n * import { NextRequest, NextResponse } from \"next/server\";\n * import { withX402 } from \"@x402/next\";\n *\n * const server = new x402ResourceServer(myFacilitatorClient)\n * .register(NETWORK, new ExactEvmScheme());\n *\n * const handler = async (request: NextRequest) => {\n * return NextResponse.json({ data: \"protected content\" });\n * };\n *\n * export const GET = withX402(\n * handler,\n * {\n * accepts: {\n * scheme: \"exact\",\n * payTo: \"0x123...\",\n * price: \"$0.01\",\n * network: \"eip155:84532\",\n * },\n * description: \"Access to protected API\",\n * },\n * server,\n * );\n * ```\n */\nexport function withX402<T = unknown>(\n routeHandler: (request: NextRequest) => Promise<NextResponse<T>>,\n routeConfig: RouteConfig,\n server: x402ResourceServer,\n paywallConfig?: PaywallConfig,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n): (request: NextRequest) => Promise<NextResponse<T>> {\n const routes = { \"*\": routeConfig };\n // Create the x402 HTTP server instance with the resource server\n const httpServer = new x402HTTPResourceServer(server, routes);\n\n return withX402FromHTTPServer(\n routeHandler,\n httpServer,\n paywallConfig,\n paywall,\n syncFacilitatorOnStart,\n );\n}\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 */\nfunction checkIfBazaarNeeded(routes: RoutesConfig): boolean {\n // Handle single route config\n if (\"accepts\" in routes) {\n return !!(routes.extensions && \"bazaar\" in routes.extensions);\n }\n\n // Handle multiple routes\n return Object.values(routes).some(routeConfig => {\n return !!(routeConfig.extensions && \"bazaar\" in routeConfig.extensions);\n });\n}\n\nexport type {\n PaymentRequired,\n PaymentRequirements,\n PaymentPayload,\n Network,\n SchemeNetworkServer,\n} from \"@x402/core/types\";\n\nexport type { PaywallProvider, PaywallConfig, RouteConfig } from \"@x402/core/server\";\n\nexport {\n x402ResourceServer,\n x402HTTPResourceServer,\n RouteConfigurationError,\n} from \"@x402/core/server\";\n\nexport type { RouteValidationError } from \"@x402/core/server\";\n\nexport { NextAdapter } from \"./adapter\";\n","import { NextRequest, NextResponse } from \"next/server\";\nimport {\n HTTPRequestContext,\n HTTPResponseInstructions,\n PaywallProvider,\n x402HTTPResourceServer,\n x402ResourceServer,\n RoutesConfig,\n FacilitatorResponseError,\n getFacilitatorResponseError as getCoreFacilitatorResponseError,\n} from \"@x402/core/server\";\nimport { PaymentPayload, PaymentRequirements } from \"@x402/core/types\";\nimport { NextAdapter } from \"./adapter\";\n\n/**\n * Result of createHttpServer\n */\nexport interface HttpServerInstance {\n httpServer: x402HTTPResourceServer;\n init: () => Promise<void>;\n}\n\nexport const getFacilitatorResponseError = getCoreFacilitatorResponseError;\n\n/**\n * Builds a normalized 502 response for facilitator boundary failures.\n *\n * @param error - The facilitator response error to surface\n * @returns A JSON 502 response\n */\nexport function createFacilitatorErrorResponse(error: FacilitatorResponseError): NextResponse {\n return new NextResponse(JSON.stringify({ error: error.message }), {\n status: 502,\n headers: { \"Content-Type\": \"application/json\" },\n });\n}\n\n/**\n * Prepares an existing x402HTTPResourceServer with initialization logic\n *\n * @param httpServer - Pre-configured x402HTTPResourceServer instance\n * @param paywall - Optional paywall provider for custom payment UI\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on start (defaults to true)\n * @returns The HTTP server instance with initialization function\n */\nexport function prepareHttpServer(\n httpServer: x402HTTPResourceServer,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n): HttpServerInstance {\n // Register custom paywall provider if provided\n if (paywall) {\n httpServer.registerPaywallProvider(paywall);\n }\n\n // Store initialization promise (not the result)\n // httpServer.initialize() fetches facilitator support and validates routes\n let initPromise: Promise<void> | null = syncFacilitatorOnStart ? httpServer.initialize() : null;\n let isInitialized = false;\n\n return {\n httpServer,\n /**\n * Ensures facilitator initialization succeeds once, while allowing retries after failures.\n */\n async init() {\n if (!syncFacilitatorOnStart || isInitialized) {\n return;\n }\n\n if (!initPromise) {\n initPromise = httpServer.initialize();\n }\n\n try {\n await initPromise;\n isInitialized = true;\n } catch (error) {\n initPromise = null;\n throw error;\n }\n },\n };\n}\n\n/**\n * Creates and configures the x402 HTTP server with initialization logic\n *\n * @param routes - The route configuration for the server\n * @param server - The x402 resource server instance\n * @param paywall - Optional paywall provider for custom payment UI\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on start (defaults to true)\n * @returns The HTTP server instance with initialization function\n */\nexport function createHttpServer(\n routes: RoutesConfig,\n server: x402ResourceServer,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n): HttpServerInstance {\n // Create the x402 HTTP server instance with the resource server\n const httpServer = new x402HTTPResourceServer(server, routes);\n\n return prepareHttpServer(httpServer, paywall, syncFacilitatorOnStart);\n}\n\n/**\n * Creates HTTP request context from a Next.js request\n *\n * @param request - The Next.js request object\n * @returns The HTTP request context for x402 processing\n */\nexport function createRequestContext(request: NextRequest): HTTPRequestContext {\n // Create adapter and context\n const adapter = new NextAdapter(request);\n return {\n adapter,\n path: request.nextUrl.pathname,\n method: request.method,\n paymentHeader: adapter.getHeader(\"payment-signature\") || adapter.getHeader(\"x-payment\"),\n };\n}\n\n/**\n * Handles payment error result by creating a 402 response\n *\n * @param response - The HTTP response instructions from payment verification\n * @returns A Next.js response with the appropriate 402 status and headers\n */\nexport function handlePaymentError(response: HTTPResponseInstructions): NextResponse {\n // Payment required but not provided or invalid\n const headers = new Headers(response.headers);\n if (response.isHtml) {\n headers.set(\"Content-Type\", \"text/html\");\n return new NextResponse(response.body as string, {\n status: response.status,\n headers,\n });\n }\n headers.set(\"Content-Type\", \"application/json\");\n return new NextResponse(JSON.stringify(response.body || {}), {\n status: response.status,\n headers,\n });\n}\n\n/**\n * Handles settlement after a successful response\n *\n * @param httpServer - The x402 HTTP resource server instance\n * @param response - The Next.js response from the protected route\n * @param paymentPayload - The payment payload from the client\n * @param paymentRequirements - The payment requirements for the route\n * @param declaredExtensions - Optional declared extensions (for per-key enrichment)\n * @param httpContext - Optional HTTP request context for extensions\n * @returns The response with settlement headers or an error response if settlement fails\n */\nexport async function handleSettlement(\n httpServer: x402HTTPResourceServer,\n response: NextResponse,\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n declaredExtensions?: Record<string, unknown>,\n httpContext?: HTTPRequestContext,\n): Promise<NextResponse> {\n // If the response from the protected route is >= 400, do not settle payment\n if (response.status >= 400) {\n return response;\n }\n\n try {\n // Get response body for extensions\n const responseBody = Buffer.from(await response.clone().arrayBuffer());\n\n const result = await httpServer.processSettlement(\n paymentPayload,\n paymentRequirements,\n declaredExtensions,\n { request: httpContext, responseBody },\n );\n\n if (!result.success) {\n // Settlement failed - do not return the protected resource\n const { response } = result;\n const body = response.isHtml ? response.body : JSON.stringify(response.body ?? {});\n return new NextResponse(body, {\n status: response.status,\n headers: response.headers,\n });\n }\n\n // Settlement succeeded - add headers and return original response\n Object.entries(result.headers).forEach(([key, value]) => {\n response.headers.set(key, value);\n });\n\n return response;\n } catch (error) {\n if (error instanceof FacilitatorResponseError) {\n return createFacilitatorErrorResponse(error);\n }\n console.error(\"Settlement failed:\", error);\n // If settlement fails, return an error response\n return new NextResponse(JSON.stringify({}), {\n status: 402,\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n}\n","import { HTTPAdapter } from \"@x402/core/server\";\nimport { NextRequest } from \"next/server\";\n\n/**\n * Next.js adapter implementation\n */\nexport class NextAdapter implements HTTPAdapter {\n /**\n * Creates a new NextAdapter instance.\n *\n * @param req - The Next.js request object\n */\n constructor(private req: NextRequest) {}\n\n /**\n * Gets a header value from the request.\n *\n * @param name - The header name\n * @returns The header value or undefined\n */\n getHeader(name: string): string | undefined {\n return this.req.headers.get(name) || undefined;\n }\n\n /**\n * Gets the HTTP method of the request.\n *\n * @returns The HTTP method\n */\n getMethod(): string {\n return this.req.method;\n }\n\n /**\n * Gets the path of the request.\n *\n * @returns The request path\n */\n getPath(): string {\n return this.req.nextUrl.pathname;\n }\n\n /**\n * Gets the full URL of the request.\n *\n * @returns The full request URL\n */\n getUrl(): string {\n return this.req.url;\n }\n\n /**\n * Gets the Accept header from the request.\n *\n * @returns The Accept header value or empty string\n */\n getAcceptHeader(): string {\n return this.req.headers.get(\"Accept\") || \"\";\n }\n\n /**\n * Gets the User-Agent header from the request.\n *\n * @returns The User-Agent header value or empty string\n */\n getUserAgent(): string {\n return this.req.headers.get(\"User-Agent\") || \"\";\n }\n\n /**\n * Gets all query parameters from the request URL.\n *\n * @returns Record of query parameter key-value pairs\n */\n getQueryParams(): Record<string, string | string[]> {\n const params: Record<string, string | string[]> = {};\n this.req.nextUrl.searchParams.forEach((value, key) => {\n const existing = params[key];\n if (existing) {\n if (Array.isArray(existing)) {\n existing.push(value);\n } else {\n params[key] = [existing, value];\n }\n } else {\n params[key] = value;\n }\n });\n return params;\n }\n\n /**\n * Gets 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 const all = this.req.nextUrl.searchParams.getAll(name);\n if (all.length === 0) return undefined;\n if (all.length === 1) return all[0];\n return all;\n }\n\n /**\n * Gets the parsed request body.\n *\n * @returns Promise resolving to the parsed request body\n */\n async getBody(): Promise<unknown> {\n try {\n return await this.req.json();\n } catch {\n return undefined;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AA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AM,oCAAoC,GAAG;AAAA,IACvD,CAAC;AAAA,EACL;AAEA,SAAO,OAAO,YAAmD;AAE/D,UAAM,KAAK;AAGX,QAAI,eAAe;AACjB,YAAM;AACN,sBAAgB;AAAA,IAClB;AAEA,UAAM,UAAU,qBAAqB,OAAO;AAG5C,UAAM,SAAS,MAAM,WAAW,mBAAmB,SAAS,aAAa;AAGzE,YAAQ,OAAO,MAAM;AAAA,MACnB,KAAK;AAEH,eAAO,aAAa,OAAO;AAAA,MAE7B,KAAK;AACH,eAAO,mBAAmB,OAAO,QAAQ;AAAA,MAE3C,KAAK,oBAAoB;AAEvB,cAAM,EAAE,gBAAgB,qBAAqB,mBAAmB,IAAI;AACpE,cAAM,kBAAkB,MAAM,aAAa,OAAO;AAClD,eAAO;AAAA,UACL;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AA4CO,SAAS,SACd,cACA,aACA,QACA,eACA,SACA,yBAAkC,MACkB;AACpD,QAAM,SAAS,EAAE,KAAK,YAAY;AAElC,QAAM,aAAa,IAAI,sCAAuB,QAAQ,MAAM;AAE5D,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAQA,SAAS,oBAAoB,QAA+B;AAE1D,MAAI,aAAa,QAAQ;AACvB,WAAO,CAAC,EAAE,OAAO,cAAc,YAAY,OAAO;AAAA,EACpD;AAGA,SAAO,OAAO,OAAO,MAAM,EAAE,KAAK,iBAAe;AAC/C,WAAO,CAAC,EAAE,YAAY,cAAc,YAAY,YAAY;AAAA,EAC9D,CAAC;AACH;","names":["import_server","import_server","getCoreFacilitatorResponseError","response","import_server"]}
package/dist/esm/index.js CHANGED
@@ -1,13 +1,16 @@
1
1
  // src/index.ts
2
2
  import {
3
- x402ResourceServer as x402ResourceServer2
3
+ x402ResourceServer as x402ResourceServer2,
4
+ FacilitatorResponseError as FacilitatorResponseError2
4
5
  } from "@x402/core/server";
5
6
  import { NextResponse as NextResponse2 } from "next/server";
6
7
 
7
8
  // src/utils.ts
8
9
  import { NextResponse } from "next/server";
9
10
  import {
10
- x402HTTPResourceServer
11
+ x402HTTPResourceServer,
12
+ FacilitatorResponseError,
13
+ getFacilitatorResponseError as getCoreFacilitatorResponseError
11
14
  } from "@x402/core/server";
12
15
 
13
16
  // src/adapter.ts
@@ -117,17 +120,37 @@ var NextAdapter = class {
117
120
  };
118
121
 
119
122
  // src/utils.ts
123
+ var getFacilitatorResponseError = getCoreFacilitatorResponseError;
124
+ function createFacilitatorErrorResponse(error) {
125
+ return new NextResponse(JSON.stringify({ error: error.message }), {
126
+ status: 502,
127
+ headers: { "Content-Type": "application/json" }
128
+ });
129
+ }
120
130
  function prepareHttpServer(httpServer, paywall, syncFacilitatorOnStart = true) {
121
131
  if (paywall) {
122
132
  httpServer.registerPaywallProvider(paywall);
123
133
  }
124
134
  let initPromise = syncFacilitatorOnStart ? httpServer.initialize() : null;
135
+ let isInitialized = false;
125
136
  return {
126
137
  httpServer,
138
+ /**
139
+ * Ensures facilitator initialization succeeds once, while allowing retries after failures.
140
+ */
127
141
  async init() {
128
- if (initPromise) {
142
+ if (!syncFacilitatorOnStart || isInitialized) {
143
+ return;
144
+ }
145
+ if (!initPromise) {
146
+ initPromise = httpServer.initialize();
147
+ }
148
+ try {
129
149
  await initPromise;
150
+ isInitialized = true;
151
+ } catch (error) {
130
152
  initPromise = null;
153
+ throw error;
131
154
  }
132
155
  }
133
156
  };
@@ -181,6 +204,9 @@ async function handleSettlement(httpServer, response, paymentPayload, paymentReq
181
204
  });
182
205
  return response;
183
206
  } catch (error) {
207
+ if (error instanceof FacilitatorResponseError) {
208
+ return createFacilitatorErrorResponse(error);
209
+ }
184
210
  console.error("Settlement failed:", error);
185
211
  return new NextResponse(JSON.stringify({}), {
186
212
  status: 402,
@@ -214,12 +240,28 @@ function paymentProxyFromHTTPServer(httpServer, paywallConfig, paywall, syncFaci
214
240
  if (!httpServer.requiresPayment(context)) {
215
241
  return NextResponse2.next();
216
242
  }
217
- await init();
243
+ try {
244
+ await init();
245
+ } catch (error) {
246
+ const facilitatorError = getFacilitatorResponseError(error);
247
+ if (facilitatorError) {
248
+ return createFacilitatorErrorResponse(facilitatorError);
249
+ }
250
+ throw error;
251
+ }
218
252
  if (bazaarPromise) {
219
253
  await bazaarPromise;
220
254
  bazaarPromise = null;
221
255
  }
222
- const result = await httpServer.processHTTPRequest(context, paywallConfig);
256
+ let result;
257
+ try {
258
+ result = await httpServer.processHTTPRequest(context, paywallConfig);
259
+ } catch (error) {
260
+ if (error instanceof FacilitatorResponseError2) {
261
+ return createFacilitatorErrorResponse(error);
262
+ }
263
+ throw error;
264
+ }
223
265
  switch (result.type) {
224
266
  case "no-payment-required":
225
267
  return NextResponse2.next();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts","../../src/utils.ts","../../src/adapter.ts"],"sourcesContent":["import {\n PaywallConfig,\n PaywallProvider,\n x402ResourceServer,\n RoutesConfig,\n RouteConfig,\n FacilitatorClient,\n} from \"@x402/core/server\";\nimport { SchemeNetworkServer, Network } from \"@x402/core/types\";\nimport { NextRequest, NextResponse } from \"next/server\";\nimport {\n prepareHttpServer,\n createRequestContext,\n handlePaymentError,\n handleSettlement,\n} from \"./utils\";\nimport { x402HTTPResourceServer } from \"@x402/core/server\";\n\n/**\n * Configuration for registering a payment scheme with a specific network\n */\nexport interface SchemeRegistration {\n /**\n * The network identifier (e.g., 'eip155:84532', 'solana:mainnet')\n */\n network: Network;\n\n /**\n * The scheme server implementation for this network\n */\n server: SchemeNetworkServer;\n}\n\n/**\n * Next.js payment proxy for x402 protocol (direct HTTP server instance).\n *\n * Use this when you need to configure HTTP-level hooks.\n *\n * @param httpServer - Pre-configured x402HTTPResourceServer instance\n * @param paywallConfig - Optional configuration for the built-in paywall UI\n * @param paywall - Optional custom paywall provider (overrides default)\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)\n * @returns Next.js proxy handler\n *\n * @example\n * ```typescript\n * import { paymentProxyFromHTTPServer, x402ResourceServer, x402HTTPResourceServer } from \"@x402/next\";\n *\n * const resourceServer = new x402ResourceServer(facilitatorClient)\n * .register(NETWORK, new ExactEvmScheme());\n *\n * const httpServer = new x402HTTPResourceServer(resourceServer, routes)\n * .onProtectedRequest(requestHook);\n *\n * export const proxy = paymentProxyFromHTTPServer(httpServer);\n * ```\n */\nexport function paymentProxyFromHTTPServer(\n httpServer: x402HTTPResourceServer,\n paywallConfig?: PaywallConfig,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n) {\n const { init } = prepareHttpServer(httpServer, paywall, syncFacilitatorOnStart);\n\n // Dynamically register bazaar extension if routes declare it and not already registered\n // Skip if pre-registered (e.g., in serverless environments where static imports are used)\n let bazaarPromise: Promise<void> | null = null;\n if (checkIfBazaarNeeded(httpServer.routes) && !httpServer.server.hasExtension(\"bazaar\")) {\n bazaarPromise = import(/* webpackIgnore: true */ \"@x402/extensions/bazaar\")\n .then(({ bazaarResourceServerExtension }) => {\n httpServer.server.registerExtension(bazaarResourceServerExtension);\n })\n .catch(err => {\n console.error(\"Failed to load bazaar extension:\", err);\n });\n }\n\n return async (req: NextRequest) => {\n const context = createRequestContext(req);\n\n // Check if route requires payment before initializing facilitator\n if (!httpServer.requiresPayment(context)) {\n return NextResponse.next();\n }\n\n // Only initialize when processing a protected route\n await init();\n\n // Await bazaar extension loading if needed\n if (bazaarPromise) {\n await bazaarPromise;\n bazaarPromise = null;\n }\n\n // Process payment requirement check\n const result = await httpServer.processHTTPRequest(context, paywallConfig);\n\n // Handle the different result types\n switch (result.type) {\n case \"no-payment-required\":\n // No payment needed, proceed directly to the route handler\n return NextResponse.next();\n\n case \"payment-error\":\n return handlePaymentError(result.response);\n\n case \"payment-verified\": {\n // Payment is valid, need to wrap response for settlement\n const { paymentPayload, paymentRequirements, declaredExtensions } = result;\n\n // Proceed to the next proxy or route handler\n const nextResponse = NextResponse.next();\n return handleSettlement(\n httpServer,\n nextResponse,\n paymentPayload,\n paymentRequirements,\n declaredExtensions,\n context,\n );\n }\n }\n };\n}\n\n/**\n * Next.js payment proxy for x402 protocol (direct server instance).\n *\n * Use this when you want to pass a pre-configured x402ResourceServer instance.\n * This provides more flexibility for testing, custom configuration, and reusing\n * server instances across multiple proxies.\n *\n * @param routes - Route configurations for protected endpoints\n * @param server - Pre-configured x402ResourceServer instance\n * @param paywallConfig - Optional configuration for the built-in paywall UI\n * @param paywall - Optional custom paywall provider (overrides default)\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)\n * @returns Next.js proxy handler\n *\n * @example\n * ```typescript\n * import { paymentProxy } from \"@x402/next\";\n *\n * const server = new x402ResourceServer(myFacilitatorClient)\n * .register(NETWORK, new ExactEvmScheme());\n *\n * export const proxy = paymentProxy(routes, server, paywallConfig);\n * ```\n */\nexport function paymentProxy(\n routes: RoutesConfig,\n server: x402ResourceServer,\n paywallConfig?: PaywallConfig,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n) {\n // Create the x402 HTTP server instance with the resource server\n const httpServer = new x402HTTPResourceServer(server, routes);\n\n return paymentProxyFromHTTPServer(httpServer, paywallConfig, paywall, syncFacilitatorOnStart);\n}\n\n/**\n * Next.js payment proxy for x402 protocol (configuration-based).\n *\n * Use this when you want to quickly set up proxy with simple configuration.\n * This function creates and configures the x402ResourceServer internally.\n *\n * @param routes - Route configurations for protected endpoints\n * @param facilitatorClients - Optional facilitator client(s) for payment processing\n * @param schemes - Optional array of scheme registrations for server-side payment processing\n * @param paywallConfig - Optional configuration for the built-in paywall UI\n * @param paywall - Optional custom paywall provider (overrides default)\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)\n * @returns Next.js proxy handler\n *\n * @example\n * ```typescript\n * import { paymentProxyFromConfig } from \"@x402/next\";\n *\n * export const proxy = paymentProxyFromConfig(\n * routes,\n * myFacilitatorClient,\n * [{ network: \"eip155:8453\", server: evmSchemeServer }],\n * paywallConfig\n * );\n * ```\n */\nexport function paymentProxyFromConfig(\n routes: RoutesConfig,\n facilitatorClients?: FacilitatorClient | FacilitatorClient[],\n schemes?: SchemeRegistration[],\n paywallConfig?: PaywallConfig,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n) {\n const ResourceServer = new x402ResourceServer(facilitatorClients);\n\n if (schemes) {\n schemes.forEach(({ network, server: schemeServer }) => {\n ResourceServer.register(network, schemeServer);\n });\n }\n\n // Use the direct paymentProxy with the configured server\n // Note: paymentProxy handles dynamic bazaar registration\n return paymentProxy(routes, ResourceServer, paywallConfig, paywall, syncFacilitatorOnStart);\n}\n\n/**\n * Wraps a Next.js App Router API route handler with x402 payment protection (HTTP server instance).\n *\n * Use this when you need to configure HTTP-level hooks.\n *\n * @param routeHandler - The API route handler function to wrap\n * @param httpServer - Pre-configured x402HTTPResourceServer instance\n * @param paywallConfig - Optional configuration for the built-in paywall UI\n * @param paywall - Optional custom paywall provider (overrides default)\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)\n * @returns A wrapped Next.js route handler\n *\n * @example\n * ```typescript\n * import { NextRequest, NextResponse } from \"next/server\";\n * import { withX402FromHTTPServer, x402ResourceServer, x402HTTPResourceServer } from \"@x402/next\";\n *\n * const resourceServer = new x402ResourceServer(facilitatorClient)\n * .register(NETWORK, new ExactEvmScheme());\n *\n * const httpServer = new x402HTTPResourceServer(resourceServer, { \"*\": routeConfig })\n * .onProtectedRequest(requestHook);\n *\n * const handler = async (request: NextRequest) => {\n * return NextResponse.json({ data: \"protected content\" });\n * };\n *\n * export const GET = withX402FromHTTPServer(handler, httpServer);\n * ```\n */\nexport function withX402FromHTTPServer<T = unknown>(\n routeHandler: (request: NextRequest) => Promise<NextResponse<T>>,\n httpServer: x402HTTPResourceServer,\n paywallConfig?: PaywallConfig,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n): (request: NextRequest) => Promise<NextResponse<T>> {\n const { init } = prepareHttpServer(httpServer, paywall, syncFacilitatorOnStart);\n\n // Dynamically register bazaar extension if route declares it and not already registered\n // Skip if pre-registered (e.g., in serverless environments where static imports are used)\n let bazaarPromise: Promise<void> | null = null;\n if (checkIfBazaarNeeded(httpServer.routes) && !httpServer.server.hasExtension(\"bazaar\")) {\n bazaarPromise = import(/* webpackIgnore: true */ \"@x402/extensions/bazaar\")\n .then(({ bazaarResourceServerExtension }) => {\n httpServer.server.registerExtension(bazaarResourceServerExtension);\n })\n .catch(err => {\n console.error(\"Failed to load bazaar extension:\", err);\n });\n }\n\n return async (request: NextRequest): Promise<NextResponse<T>> => {\n // Only initialize when processing a protected route\n await init();\n\n // Await bazaar extension loading if needed\n if (bazaarPromise) {\n await bazaarPromise;\n bazaarPromise = null;\n }\n\n const context = createRequestContext(request);\n\n // Process payment requirement check\n const result = await httpServer.processHTTPRequest(context, paywallConfig);\n\n // Handle the different result types\n switch (result.type) {\n case \"no-payment-required\":\n // No payment needed, proceed directly to the route handler\n return routeHandler(request);\n\n case \"payment-error\":\n return handlePaymentError(result.response) as NextResponse<T>;\n\n case \"payment-verified\": {\n // Payment is valid, need to wrap response for settlement\n const { paymentPayload, paymentRequirements, declaredExtensions } = result;\n const handlerResponse = await routeHandler(request);\n return handleSettlement(\n httpServer,\n handlerResponse,\n paymentPayload,\n paymentRequirements,\n declaredExtensions,\n context,\n ) as Promise<NextResponse<T>>;\n }\n }\n };\n}\n\n/**\n * Wraps a Next.js App Router API route handler with x402 payment protection.\n *\n * Unlike `paymentProxy` which works as middleware, `withX402` wraps individual route handlers\n * and guarantees that payment settlement only occurs after the handler returns a successful\n * response (status < 400). This provides more precise control over when payments are settled.\n *\n * @param routeHandler - The API route handler function to wrap\n * @param routeConfig - Payment configuration for this specific route\n * @param server - Pre-configured x402ResourceServer instance\n * @param paywallConfig - Optional configuration for the built-in paywall UI\n * @param paywall - Optional custom paywall provider (overrides default)\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)\n * @returns A wrapped Next.js route handler\n *\n * @example\n * ```typescript\n * import { NextRequest, NextResponse } from \"next/server\";\n * import { withX402 } from \"@x402/next\";\n *\n * const server = new x402ResourceServer(myFacilitatorClient)\n * .register(NETWORK, new ExactEvmScheme());\n *\n * const handler = async (request: NextRequest) => {\n * return NextResponse.json({ data: \"protected content\" });\n * };\n *\n * export const GET = withX402(\n * handler,\n * {\n * accepts: {\n * scheme: \"exact\",\n * payTo: \"0x123...\",\n * price: \"$0.01\",\n * network: \"eip155:84532\",\n * },\n * description: \"Access to protected API\",\n * },\n * server,\n * );\n * ```\n */\nexport function withX402<T = unknown>(\n routeHandler: (request: NextRequest) => Promise<NextResponse<T>>,\n routeConfig: RouteConfig,\n server: x402ResourceServer,\n paywallConfig?: PaywallConfig,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n): (request: NextRequest) => Promise<NextResponse<T>> {\n const routes = { \"*\": routeConfig };\n // Create the x402 HTTP server instance with the resource server\n const httpServer = new x402HTTPResourceServer(server, routes);\n\n return withX402FromHTTPServer(\n routeHandler,\n httpServer,\n paywallConfig,\n paywall,\n syncFacilitatorOnStart,\n );\n}\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 */\nfunction checkIfBazaarNeeded(routes: RoutesConfig): boolean {\n // Handle single route config\n if (\"accepts\" in routes) {\n return !!(routes.extensions && \"bazaar\" in routes.extensions);\n }\n\n // Handle multiple routes\n return Object.values(routes).some(routeConfig => {\n return !!(routeConfig.extensions && \"bazaar\" in routeConfig.extensions);\n });\n}\n\nexport type {\n PaymentRequired,\n PaymentRequirements,\n PaymentPayload,\n Network,\n SchemeNetworkServer,\n} from \"@x402/core/types\";\n\nexport type { PaywallProvider, PaywallConfig, RouteConfig } from \"@x402/core/server\";\n\nexport {\n x402ResourceServer,\n x402HTTPResourceServer,\n RouteConfigurationError,\n} from \"@x402/core/server\";\n\nexport type { RouteValidationError } from \"@x402/core/server\";\n\nexport { NextAdapter } from \"./adapter\";\n","import { NextRequest, NextResponse } from \"next/server\";\nimport {\n HTTPRequestContext,\n HTTPResponseInstructions,\n PaywallProvider,\n x402HTTPResourceServer,\n x402ResourceServer,\n RoutesConfig,\n} from \"@x402/core/server\";\nimport { PaymentPayload, PaymentRequirements } from \"@x402/core/types\";\nimport { NextAdapter } from \"./adapter\";\n\n/**\n * Result of createHttpServer\n */\nexport interface HttpServerInstance {\n httpServer: x402HTTPResourceServer;\n init: () => Promise<void>;\n}\n\n/**\n * Prepares an existing x402HTTPResourceServer with initialization logic\n *\n * @param httpServer - Pre-configured x402HTTPResourceServer instance\n * @param paywall - Optional paywall provider for custom payment UI\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on start (defaults to true)\n * @returns The HTTP server instance with initialization function\n */\nexport function prepareHttpServer(\n httpServer: x402HTTPResourceServer,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n): HttpServerInstance {\n // Register custom paywall provider if provided\n if (paywall) {\n httpServer.registerPaywallProvider(paywall);\n }\n\n // Store initialization promise (not the result)\n // httpServer.initialize() fetches facilitator support and validates routes\n let initPromise: Promise<void> | null = syncFacilitatorOnStart ? httpServer.initialize() : null;\n\n return {\n httpServer,\n async init() {\n // Ensure initialization completes before processing\n if (initPromise) {\n await initPromise;\n initPromise = null; // Clear after first await\n }\n },\n };\n}\n\n/**\n * Creates and configures the x402 HTTP server with initialization logic\n *\n * @param routes - The route configuration for the server\n * @param server - The x402 resource server instance\n * @param paywall - Optional paywall provider for custom payment UI\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on start (defaults to true)\n * @returns The HTTP server instance with initialization function\n */\nexport function createHttpServer(\n routes: RoutesConfig,\n server: x402ResourceServer,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n): HttpServerInstance {\n // Create the x402 HTTP server instance with the resource server\n const httpServer = new x402HTTPResourceServer(server, routes);\n\n return prepareHttpServer(httpServer, paywall, syncFacilitatorOnStart);\n}\n\n/**\n * Creates HTTP request context from a Next.js request\n *\n * @param request - The Next.js request object\n * @returns The HTTP request context for x402 processing\n */\nexport function createRequestContext(request: NextRequest): HTTPRequestContext {\n // Create adapter and context\n const adapter = new NextAdapter(request);\n return {\n adapter,\n path: request.nextUrl.pathname,\n method: request.method,\n paymentHeader: adapter.getHeader(\"payment-signature\") || adapter.getHeader(\"x-payment\"),\n };\n}\n\n/**\n * Handles payment error result by creating a 402 response\n *\n * @param response - The HTTP response instructions from payment verification\n * @returns A Next.js response with the appropriate 402 status and headers\n */\nexport function handlePaymentError(response: HTTPResponseInstructions): NextResponse {\n // Payment required but not provided or invalid\n const headers = new Headers(response.headers);\n if (response.isHtml) {\n headers.set(\"Content-Type\", \"text/html\");\n return new NextResponse(response.body as string, {\n status: response.status,\n headers,\n });\n }\n headers.set(\"Content-Type\", \"application/json\");\n return new NextResponse(JSON.stringify(response.body || {}), {\n status: response.status,\n headers,\n });\n}\n\n/**\n * Handles settlement after a successful response\n *\n * @param httpServer - The x402 HTTP resource server instance\n * @param response - The Next.js response from the protected route\n * @param paymentPayload - The payment payload from the client\n * @param paymentRequirements - The payment requirements for the route\n * @param declaredExtensions - Optional declared extensions (for per-key enrichment)\n * @param httpContext - Optional HTTP request context for extensions\n * @returns The response with settlement headers or an error response if settlement fails\n */\nexport async function handleSettlement(\n httpServer: x402HTTPResourceServer,\n response: NextResponse,\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n declaredExtensions?: Record<string, unknown>,\n httpContext?: HTTPRequestContext,\n): Promise<NextResponse> {\n // If the response from the protected route is >= 400, do not settle payment\n if (response.status >= 400) {\n return response;\n }\n\n try {\n // Get response body for extensions\n const responseBody = Buffer.from(await response.clone().arrayBuffer());\n\n const result = await httpServer.processSettlement(\n paymentPayload,\n paymentRequirements,\n declaredExtensions,\n { request: httpContext, responseBody },\n );\n\n if (!result.success) {\n // Settlement failed - do not return the protected resource\n const { response } = result;\n const body = response.isHtml ? response.body : JSON.stringify(response.body ?? {});\n return new NextResponse(body, {\n status: response.status,\n headers: response.headers,\n });\n }\n\n // Settlement succeeded - add headers and return original response\n Object.entries(result.headers).forEach(([key, value]) => {\n response.headers.set(key, value);\n });\n\n return response;\n } catch (error) {\n console.error(\"Settlement failed:\", error);\n // If settlement fails, return an error response\n return new NextResponse(JSON.stringify({}), {\n status: 402,\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n}\n","import { HTTPAdapter } from \"@x402/core/server\";\nimport { NextRequest } from \"next/server\";\n\n/**\n * Next.js adapter implementation\n */\nexport class NextAdapter implements HTTPAdapter {\n /**\n * Creates a new NextAdapter instance.\n *\n * @param req - The Next.js request object\n */\n constructor(private req: NextRequest) {}\n\n /**\n * Gets a header value from the request.\n *\n * @param name - The header name\n * @returns The header value or undefined\n */\n getHeader(name: string): string | undefined {\n return this.req.headers.get(name) || undefined;\n }\n\n /**\n * Gets the HTTP method of the request.\n *\n * @returns The HTTP method\n */\n getMethod(): string {\n return this.req.method;\n }\n\n /**\n * Gets the path of the request.\n *\n * @returns The request path\n */\n getPath(): string {\n return this.req.nextUrl.pathname;\n }\n\n /**\n * Gets the full URL of the request.\n *\n * @returns The full request URL\n */\n getUrl(): string {\n return this.req.url;\n }\n\n /**\n * Gets the Accept header from the request.\n *\n * @returns The Accept header value or empty string\n */\n getAcceptHeader(): string {\n return this.req.headers.get(\"Accept\") || \"\";\n }\n\n /**\n * Gets the User-Agent header from the request.\n *\n * @returns The User-Agent header value or empty string\n */\n getUserAgent(): string {\n return this.req.headers.get(\"User-Agent\") || \"\";\n }\n\n /**\n * Gets all query parameters from the request URL.\n *\n * @returns Record of query parameter key-value pairs\n */\n getQueryParams(): Record<string, string | string[]> {\n const params: Record<string, string | string[]> = {};\n this.req.nextUrl.searchParams.forEach((value, key) => {\n const existing = params[key];\n if (existing) {\n if (Array.isArray(existing)) {\n existing.push(value);\n } else {\n params[key] = [existing, value];\n }\n } else {\n params[key] = value;\n }\n });\n return params;\n }\n\n /**\n * Gets 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 const all = this.req.nextUrl.searchParams.getAll(name);\n if (all.length === 0) return undefined;\n if (all.length === 1) return all[0];\n return all;\n }\n\n /**\n * Gets the parsed request body.\n *\n * @returns Promise resolving to the parsed request body\n */\n async getBody(): Promise<unknown> {\n try {\n return await this.req.json();\n } catch {\n return undefined;\n }\n }\n}\n"],"mappings":";AAAA;AAAA,EAGE,sBAAAA;AAAA,OAIK;AAEP,SAAsB,gBAAAC,qBAAoB;;;ACT1C,SAAsB,oBAAoB;AAC1C;AAAA,EAIE;AAAA,OAGK;;;ACFA,IAAM,cAAN,MAAyC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM9C,YAAoB,KAAkB;AAAlB;AAAA,EAAmB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQvC,UAAU,MAAkC;AAC1C,WAAO,KAAK,IAAI,QAAQ,IAAI,IAAI,KAAK;AAAA,EACvC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,YAAoB;AAClB,WAAO,KAAK,IAAI;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,UAAkB;AAChB,WAAO,KAAK,IAAI,QAAQ;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,SAAiB;AACf,WAAO,KAAK,IAAI;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,kBAA0B;AACxB,WAAO,KAAK,IAAI,QAAQ,IAAI,QAAQ,KAAK;AAAA,EAC3C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,eAAuB;AACrB,WAAO,KAAK,IAAI,QAAQ,IAAI,YAAY,KAAK;AAAA,EAC/C;AAAA;AAAA;AAAA;AAAA;AA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AAK,oBAAoB;AAEvB,cAAM,EAAE,gBAAgB,qBAAqB,mBAAmB,IAAI;AACpE,cAAM,kBAAkB,MAAM,aAAa,OAAO;AAClD,eAAO;AAAA,UACL;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AA4CO,SAAS,SACd,cACA,aACA,QACA,eACA,SACA,yBAAkC,MACkB;AACpD,QAAM,SAAS,EAAE,KAAK,YAAY;AAElC,QAAM,aAAa,IAAID,wBAAuB,QAAQ,MAAM;AAE5D,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAQA,SAAS,oBAAoB,QAA+B;AAE1D,MAAI,aAAa,QAAQ;AACvB,WAAO,CAAC,EAAE,OAAO,cAAc,YAAY,OAAO;AAAA,EACpD;AAGA,SAAO,OAAO,OAAO,MAAM,EAAE,KAAK,iBAAe;AAC/C,WAAO,CAAC,EAAE,YAAY,cAAc,YAAY,YAAY;AAAA,EAC9D,CAAC;AACH;","names":["x402ResourceServer","NextResponse","response","x402HTTPResourceServer","x402ResourceServer","NextResponse"]}
1
+ {"version":3,"sources":["../../src/index.ts","../../src/utils.ts","../../src/adapter.ts"],"sourcesContent":["import {\n PaywallConfig,\n PaywallProvider,\n x402ResourceServer,\n RoutesConfig,\n RouteConfig,\n FacilitatorClient,\n FacilitatorResponseError,\n} from \"@x402/core/server\";\nimport { SchemeNetworkServer, Network } from \"@x402/core/types\";\nimport { NextRequest, NextResponse } from \"next/server\";\nimport {\n prepareHttpServer,\n createRequestContext,\n handlePaymentError,\n handleSettlement,\n createFacilitatorErrorResponse,\n getFacilitatorResponseError,\n} from \"./utils\";\nimport { x402HTTPResourceServer } from \"@x402/core/server\";\n\n/**\n * Configuration for registering a payment scheme with a specific network\n */\nexport interface SchemeRegistration {\n /**\n * The network identifier (e.g., 'eip155:84532', 'solana:mainnet')\n */\n network: Network;\n\n /**\n * The scheme server implementation for this network\n */\n server: SchemeNetworkServer;\n}\n\n/**\n * Next.js payment proxy for x402 protocol (direct HTTP server instance).\n *\n * Use this when you need to configure HTTP-level hooks.\n *\n * @param httpServer - Pre-configured x402HTTPResourceServer instance\n * @param paywallConfig - Optional configuration for the built-in paywall UI\n * @param paywall - Optional custom paywall provider (overrides default)\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)\n * @returns Next.js proxy handler\n *\n * @example\n * ```typescript\n * import { paymentProxyFromHTTPServer, x402ResourceServer, x402HTTPResourceServer } from \"@x402/next\";\n *\n * const resourceServer = new x402ResourceServer(facilitatorClient)\n * .register(NETWORK, new ExactEvmScheme());\n *\n * const httpServer = new x402HTTPResourceServer(resourceServer, routes)\n * .onProtectedRequest(requestHook);\n *\n * export const proxy = paymentProxyFromHTTPServer(httpServer);\n * ```\n */\nexport function paymentProxyFromHTTPServer(\n httpServer: x402HTTPResourceServer,\n paywallConfig?: PaywallConfig,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n) {\n const { init } = prepareHttpServer(httpServer, paywall, syncFacilitatorOnStart);\n\n // Dynamically register bazaar extension if routes declare it and not already registered\n // Skip if pre-registered (e.g., in serverless environments where static imports are used)\n let bazaarPromise: Promise<void> | null = null;\n if (checkIfBazaarNeeded(httpServer.routes) && !httpServer.server.hasExtension(\"bazaar\")) {\n bazaarPromise = import(/* webpackIgnore: true */ \"@x402/extensions/bazaar\")\n .then(({ bazaarResourceServerExtension }) => {\n httpServer.server.registerExtension(bazaarResourceServerExtension);\n })\n .catch(err => {\n console.error(\"Failed to load bazaar extension:\", err);\n });\n }\n\n return async (req: NextRequest) => {\n const context = createRequestContext(req);\n\n // Check if route requires payment before initializing facilitator\n if (!httpServer.requiresPayment(context)) {\n return NextResponse.next();\n }\n\n // Only initialize when processing a protected route\n try {\n await init();\n } catch (error) {\n const facilitatorError = getFacilitatorResponseError(error);\n if (facilitatorError) {\n return createFacilitatorErrorResponse(facilitatorError);\n }\n throw error;\n }\n\n // Await bazaar extension loading if needed\n if (bazaarPromise) {\n await bazaarPromise;\n bazaarPromise = null;\n }\n\n // Process payment requirement check\n let result: Awaited<ReturnType<x402HTTPResourceServer[\"processHTTPRequest\"]>>;\n try {\n result = await httpServer.processHTTPRequest(context, paywallConfig);\n } catch (error) {\n if (error instanceof FacilitatorResponseError) {\n return createFacilitatorErrorResponse(error);\n }\n throw error;\n }\n\n // Handle the different result types\n switch (result.type) {\n case \"no-payment-required\":\n // No payment needed, proceed directly to the route handler\n return NextResponse.next();\n\n case \"payment-error\":\n return handlePaymentError(result.response);\n\n case \"payment-verified\": {\n // Payment is valid, need to wrap response for settlement\n const { paymentPayload, paymentRequirements, declaredExtensions } = result;\n\n // Proceed to the next proxy or route handler\n const nextResponse = NextResponse.next();\n return handleSettlement(\n httpServer,\n nextResponse,\n paymentPayload,\n paymentRequirements,\n declaredExtensions,\n context,\n );\n }\n }\n };\n}\n\n/**\n * Next.js payment proxy for x402 protocol (direct server instance).\n *\n * Use this when you want to pass a pre-configured x402ResourceServer instance.\n * This provides more flexibility for testing, custom configuration, and reusing\n * server instances across multiple proxies.\n *\n * @param routes - Route configurations for protected endpoints\n * @param server - Pre-configured x402ResourceServer instance\n * @param paywallConfig - Optional configuration for the built-in paywall UI\n * @param paywall - Optional custom paywall provider (overrides default)\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)\n * @returns Next.js proxy handler\n *\n * @example\n * ```typescript\n * import { paymentProxy } from \"@x402/next\";\n *\n * const server = new x402ResourceServer(myFacilitatorClient)\n * .register(NETWORK, new ExactEvmScheme());\n *\n * export const proxy = paymentProxy(routes, server, paywallConfig);\n * ```\n */\nexport function paymentProxy(\n routes: RoutesConfig,\n server: x402ResourceServer,\n paywallConfig?: PaywallConfig,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n) {\n // Create the x402 HTTP server instance with the resource server\n const httpServer = new x402HTTPResourceServer(server, routes);\n\n return paymentProxyFromHTTPServer(httpServer, paywallConfig, paywall, syncFacilitatorOnStart);\n}\n\n/**\n * Next.js payment proxy for x402 protocol (configuration-based).\n *\n * Use this when you want to quickly set up proxy with simple configuration.\n * This function creates and configures the x402ResourceServer internally.\n *\n * @param routes - Route configurations for protected endpoints\n * @param facilitatorClients - Optional facilitator client(s) for payment processing\n * @param schemes - Optional array of scheme registrations for server-side payment processing\n * @param paywallConfig - Optional configuration for the built-in paywall UI\n * @param paywall - Optional custom paywall provider (overrides default)\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)\n * @returns Next.js proxy handler\n *\n * @example\n * ```typescript\n * import { paymentProxyFromConfig } from \"@x402/next\";\n *\n * export const proxy = paymentProxyFromConfig(\n * routes,\n * myFacilitatorClient,\n * [{ network: \"eip155:8453\", server: evmSchemeServer }],\n * paywallConfig\n * );\n * ```\n */\nexport function paymentProxyFromConfig(\n routes: RoutesConfig,\n facilitatorClients?: FacilitatorClient | FacilitatorClient[],\n schemes?: SchemeRegistration[],\n paywallConfig?: PaywallConfig,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n) {\n const ResourceServer = new x402ResourceServer(facilitatorClients);\n\n if (schemes) {\n schemes.forEach(({ network, server: schemeServer }) => {\n ResourceServer.register(network, schemeServer);\n });\n }\n\n // Use the direct paymentProxy with the configured server\n // Note: paymentProxy handles dynamic bazaar registration\n return paymentProxy(routes, ResourceServer, paywallConfig, paywall, syncFacilitatorOnStart);\n}\n\n/**\n * Wraps a Next.js App Router API route handler with x402 payment protection (HTTP server instance).\n *\n * Use this when you need to configure HTTP-level hooks.\n *\n * @param routeHandler - The API route handler function to wrap\n * @param httpServer - Pre-configured x402HTTPResourceServer instance\n * @param paywallConfig - Optional configuration for the built-in paywall UI\n * @param paywall - Optional custom paywall provider (overrides default)\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)\n * @returns A wrapped Next.js route handler\n *\n * @example\n * ```typescript\n * import { NextRequest, NextResponse } from \"next/server\";\n * import { withX402FromHTTPServer, x402ResourceServer, x402HTTPResourceServer } from \"@x402/next\";\n *\n * const resourceServer = new x402ResourceServer(facilitatorClient)\n * .register(NETWORK, new ExactEvmScheme());\n *\n * const httpServer = new x402HTTPResourceServer(resourceServer, { \"*\": routeConfig })\n * .onProtectedRequest(requestHook);\n *\n * const handler = async (request: NextRequest) => {\n * return NextResponse.json({ data: \"protected content\" });\n * };\n *\n * export const GET = withX402FromHTTPServer(handler, httpServer);\n * ```\n */\nexport function withX402FromHTTPServer<T = unknown>(\n routeHandler: (request: NextRequest) => Promise<NextResponse<T>>,\n httpServer: x402HTTPResourceServer,\n paywallConfig?: PaywallConfig,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n): (request: NextRequest) => Promise<NextResponse<T>> {\n const { init } = prepareHttpServer(httpServer, paywall, syncFacilitatorOnStart);\n\n // Dynamically register bazaar extension if route declares it and not already registered\n // Skip if pre-registered (e.g., in serverless environments where static imports are used)\n let bazaarPromise: Promise<void> | null = null;\n if (checkIfBazaarNeeded(httpServer.routes) && !httpServer.server.hasExtension(\"bazaar\")) {\n bazaarPromise = import(/* webpackIgnore: true */ \"@x402/extensions/bazaar\")\n .then(({ bazaarResourceServerExtension }) => {\n httpServer.server.registerExtension(bazaarResourceServerExtension);\n })\n .catch(err => {\n console.error(\"Failed to load bazaar extension:\", err);\n });\n }\n\n return async (request: NextRequest): Promise<NextResponse<T>> => {\n // Only initialize when processing a protected route\n await init();\n\n // Await bazaar extension loading if needed\n if (bazaarPromise) {\n await bazaarPromise;\n bazaarPromise = null;\n }\n\n const context = createRequestContext(request);\n\n // Process payment requirement check\n const result = await httpServer.processHTTPRequest(context, paywallConfig);\n\n // Handle the different result types\n switch (result.type) {\n case \"no-payment-required\":\n // No payment needed, proceed directly to the route handler\n return routeHandler(request);\n\n case \"payment-error\":\n return handlePaymentError(result.response) as NextResponse<T>;\n\n case \"payment-verified\": {\n // Payment is valid, need to wrap response for settlement\n const { paymentPayload, paymentRequirements, declaredExtensions } = result;\n const handlerResponse = await routeHandler(request);\n return handleSettlement(\n httpServer,\n handlerResponse,\n paymentPayload,\n paymentRequirements,\n declaredExtensions,\n context,\n ) as Promise<NextResponse<T>>;\n }\n }\n };\n}\n\n/**\n * Wraps a Next.js App Router API route handler with x402 payment protection.\n *\n * Unlike `paymentProxy` which works as middleware, `withX402` wraps individual route handlers\n * and guarantees that payment settlement only occurs after the handler returns a successful\n * response (status < 400). This provides more precise control over when payments are settled.\n *\n * @param routeHandler - The API route handler function to wrap\n * @param routeConfig - Payment configuration for this specific route\n * @param server - Pre-configured x402ResourceServer instance\n * @param paywallConfig - Optional configuration for the built-in paywall UI\n * @param paywall - Optional custom paywall provider (overrides default)\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)\n * @returns A wrapped Next.js route handler\n *\n * @example\n * ```typescript\n * import { NextRequest, NextResponse } from \"next/server\";\n * import { withX402 } from \"@x402/next\";\n *\n * const server = new x402ResourceServer(myFacilitatorClient)\n * .register(NETWORK, new ExactEvmScheme());\n *\n * const handler = async (request: NextRequest) => {\n * return NextResponse.json({ data: \"protected content\" });\n * };\n *\n * export const GET = withX402(\n * handler,\n * {\n * accepts: {\n * scheme: \"exact\",\n * payTo: \"0x123...\",\n * price: \"$0.01\",\n * network: \"eip155:84532\",\n * },\n * description: \"Access to protected API\",\n * },\n * server,\n * );\n * ```\n */\nexport function withX402<T = unknown>(\n routeHandler: (request: NextRequest) => Promise<NextResponse<T>>,\n routeConfig: RouteConfig,\n server: x402ResourceServer,\n paywallConfig?: PaywallConfig,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n): (request: NextRequest) => Promise<NextResponse<T>> {\n const routes = { \"*\": routeConfig };\n // Create the x402 HTTP server instance with the resource server\n const httpServer = new x402HTTPResourceServer(server, routes);\n\n return withX402FromHTTPServer(\n routeHandler,\n httpServer,\n paywallConfig,\n paywall,\n syncFacilitatorOnStart,\n );\n}\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 */\nfunction checkIfBazaarNeeded(routes: RoutesConfig): boolean {\n // Handle single route config\n if (\"accepts\" in routes) {\n return !!(routes.extensions && \"bazaar\" in routes.extensions);\n }\n\n // Handle multiple routes\n return Object.values(routes).some(routeConfig => {\n return !!(routeConfig.extensions && \"bazaar\" in routeConfig.extensions);\n });\n}\n\nexport type {\n PaymentRequired,\n PaymentRequirements,\n PaymentPayload,\n Network,\n SchemeNetworkServer,\n} from \"@x402/core/types\";\n\nexport type { PaywallProvider, PaywallConfig, RouteConfig } from \"@x402/core/server\";\n\nexport {\n x402ResourceServer,\n x402HTTPResourceServer,\n RouteConfigurationError,\n} from \"@x402/core/server\";\n\nexport type { RouteValidationError } from \"@x402/core/server\";\n\nexport { NextAdapter } from \"./adapter\";\n","import { NextRequest, NextResponse } from \"next/server\";\nimport {\n HTTPRequestContext,\n HTTPResponseInstructions,\n PaywallProvider,\n x402HTTPResourceServer,\n x402ResourceServer,\n RoutesConfig,\n FacilitatorResponseError,\n getFacilitatorResponseError as getCoreFacilitatorResponseError,\n} from \"@x402/core/server\";\nimport { PaymentPayload, PaymentRequirements } from \"@x402/core/types\";\nimport { NextAdapter } from \"./adapter\";\n\n/**\n * Result of createHttpServer\n */\nexport interface HttpServerInstance {\n httpServer: x402HTTPResourceServer;\n init: () => Promise<void>;\n}\n\nexport const getFacilitatorResponseError = getCoreFacilitatorResponseError;\n\n/**\n * Builds a normalized 502 response for facilitator boundary failures.\n *\n * @param error - The facilitator response error to surface\n * @returns A JSON 502 response\n */\nexport function createFacilitatorErrorResponse(error: FacilitatorResponseError): NextResponse {\n return new NextResponse(JSON.stringify({ error: error.message }), {\n status: 502,\n headers: { \"Content-Type\": \"application/json\" },\n });\n}\n\n/**\n * Prepares an existing x402HTTPResourceServer with initialization logic\n *\n * @param httpServer - Pre-configured x402HTTPResourceServer instance\n * @param paywall - Optional paywall provider for custom payment UI\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on start (defaults to true)\n * @returns The HTTP server instance with initialization function\n */\nexport function prepareHttpServer(\n httpServer: x402HTTPResourceServer,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n): HttpServerInstance {\n // Register custom paywall provider if provided\n if (paywall) {\n httpServer.registerPaywallProvider(paywall);\n }\n\n // Store initialization promise (not the result)\n // httpServer.initialize() fetches facilitator support and validates routes\n let initPromise: Promise<void> | null = syncFacilitatorOnStart ? httpServer.initialize() : null;\n let isInitialized = false;\n\n return {\n httpServer,\n /**\n * Ensures facilitator initialization succeeds once, while allowing retries after failures.\n */\n async init() {\n if (!syncFacilitatorOnStart || isInitialized) {\n return;\n }\n\n if (!initPromise) {\n initPromise = httpServer.initialize();\n }\n\n try {\n await initPromise;\n isInitialized = true;\n } catch (error) {\n initPromise = null;\n throw error;\n }\n },\n };\n}\n\n/**\n * Creates and configures the x402 HTTP server with initialization logic\n *\n * @param routes - The route configuration for the server\n * @param server - The x402 resource server instance\n * @param paywall - Optional paywall provider for custom payment UI\n * @param syncFacilitatorOnStart - Whether to sync with the facilitator on start (defaults to true)\n * @returns The HTTP server instance with initialization function\n */\nexport function createHttpServer(\n routes: RoutesConfig,\n server: x402ResourceServer,\n paywall?: PaywallProvider,\n syncFacilitatorOnStart: boolean = true,\n): HttpServerInstance {\n // Create the x402 HTTP server instance with the resource server\n const httpServer = new x402HTTPResourceServer(server, routes);\n\n return prepareHttpServer(httpServer, paywall, syncFacilitatorOnStart);\n}\n\n/**\n * Creates HTTP request context from a Next.js request\n *\n * @param request - The Next.js request object\n * @returns The HTTP request context for x402 processing\n */\nexport function createRequestContext(request: NextRequest): HTTPRequestContext {\n // Create adapter and context\n const adapter = new NextAdapter(request);\n return {\n adapter,\n path: request.nextUrl.pathname,\n method: request.method,\n paymentHeader: adapter.getHeader(\"payment-signature\") || adapter.getHeader(\"x-payment\"),\n };\n}\n\n/**\n * Handles payment error result by creating a 402 response\n *\n * @param response - The HTTP response instructions from payment verification\n * @returns A Next.js response with the appropriate 402 status and headers\n */\nexport function handlePaymentError(response: HTTPResponseInstructions): NextResponse {\n // Payment required but not provided or invalid\n const headers = new Headers(response.headers);\n if (response.isHtml) {\n headers.set(\"Content-Type\", \"text/html\");\n return new NextResponse(response.body as string, {\n status: response.status,\n headers,\n });\n }\n headers.set(\"Content-Type\", \"application/json\");\n return new NextResponse(JSON.stringify(response.body || {}), {\n status: response.status,\n headers,\n });\n}\n\n/**\n * Handles settlement after a successful response\n *\n * @param httpServer - The x402 HTTP resource server instance\n * @param response - The Next.js response from the protected route\n * @param paymentPayload - The payment payload from the client\n * @param paymentRequirements - The payment requirements for the route\n * @param declaredExtensions - Optional declared extensions (for per-key enrichment)\n * @param httpContext - Optional HTTP request context for extensions\n * @returns The response with settlement headers or an error response if settlement fails\n */\nexport async function handleSettlement(\n httpServer: x402HTTPResourceServer,\n response: NextResponse,\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements,\n declaredExtensions?: Record<string, unknown>,\n httpContext?: HTTPRequestContext,\n): Promise<NextResponse> {\n // If the response from the protected route is >= 400, do not settle payment\n if (response.status >= 400) {\n return response;\n }\n\n try {\n // Get response body for extensions\n const responseBody = Buffer.from(await response.clone().arrayBuffer());\n\n const result = await httpServer.processSettlement(\n paymentPayload,\n paymentRequirements,\n declaredExtensions,\n { request: httpContext, responseBody },\n );\n\n if (!result.success) {\n // Settlement failed - do not return the protected resource\n const { response } = result;\n const body = response.isHtml ? response.body : JSON.stringify(response.body ?? {});\n return new NextResponse(body, {\n status: response.status,\n headers: response.headers,\n });\n }\n\n // Settlement succeeded - add headers and return original response\n Object.entries(result.headers).forEach(([key, value]) => {\n response.headers.set(key, value);\n });\n\n return response;\n } catch (error) {\n if (error instanceof FacilitatorResponseError) {\n return createFacilitatorErrorResponse(error);\n }\n console.error(\"Settlement failed:\", error);\n // If settlement fails, return an error response\n return new NextResponse(JSON.stringify({}), {\n status: 402,\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n}\n","import { HTTPAdapter } from \"@x402/core/server\";\nimport { NextRequest } from \"next/server\";\n\n/**\n * Next.js adapter implementation\n */\nexport class NextAdapter implements HTTPAdapter {\n /**\n * Creates a new NextAdapter instance.\n *\n * @param req - The Next.js request object\n */\n constructor(private req: NextRequest) {}\n\n /**\n * Gets a header value from the request.\n *\n * @param name - The header name\n * @returns The header value or undefined\n */\n getHeader(name: string): string | undefined {\n return this.req.headers.get(name) || undefined;\n }\n\n /**\n * Gets the HTTP method of the request.\n *\n * @returns The HTTP method\n */\n getMethod(): string {\n return this.req.method;\n }\n\n /**\n * Gets the path of the request.\n *\n * @returns The request path\n */\n getPath(): string {\n return this.req.nextUrl.pathname;\n }\n\n /**\n * Gets the full URL of the request.\n *\n * @returns The full request URL\n */\n getUrl(): string {\n return this.req.url;\n }\n\n /**\n * Gets the Accept header from the request.\n *\n * @returns The Accept header value or empty string\n */\n getAcceptHeader(): string {\n return this.req.headers.get(\"Accept\") || \"\";\n }\n\n /**\n * Gets the User-Agent header from the request.\n *\n * @returns The User-Agent header value or empty string\n */\n getUserAgent(): string {\n return this.req.headers.get(\"User-Agent\") || \"\";\n }\n\n /**\n * Gets all query parameters from the request URL.\n *\n * @returns Record of query parameter key-value pairs\n */\n getQueryParams(): Record<string, string | string[]> {\n const params: Record<string, string | string[]> = {};\n this.req.nextUrl.searchParams.forEach((value, key) => {\n const existing = params[key];\n if (existing) {\n if (Array.isArray(existing)) {\n existing.push(value);\n } else {\n params[key] = [existing, value];\n }\n } else {\n params[key] = value;\n }\n });\n return params;\n }\n\n /**\n * Gets 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 const all = this.req.nextUrl.searchParams.getAll(name);\n if (all.length === 0) return undefined;\n if (all.length === 1) return all[0];\n return all;\n }\n\n /**\n * Gets the parsed request body.\n *\n * @returns Promise resolving to the parsed request body\n */\n async getBody(): Promise<unknown> {\n try {\n return await this.req.json();\n } catch {\n return undefined;\n }\n }\n}\n"],"mappings":";AAAA;AAAA,EAGE,sBAAAA;AAAA,EAIA,4BAAAC;AAAA,OACK;AAEP,SAAsB,gBAAAC,qBAAoB;;;ACV1C,SAAsB,oBAAoB;AAC1C;AAAA,EAIE;AAAA,EAGA;AAAA,EACA,+BAA+B;AAAA,OAC1B;;;ACJA,IAAM,cAAN,MAAyC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM9C,YAAoB,KAAkB;AAAlB;AAAA,EAAmB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQvC,UAAU,MAAkC;AAC1C,WAAO,KAAK,IAAI,QAAQ,IAAI,IAAI,KAAK;AAAA,EACvC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,YAAoB;AAClB,WAAO,KAAK,IAAI;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,UAAkB;AAChB,WAAO,KAAK,IAAI,QAAQ;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,SAAiB;AACf,WAAO,KAAK,IAAI;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,kBAA0B;AACxB,WAAO,KAAK,IAAI,QAAQ,IAAI,QAAQ,KAAK;AAAA,EAC3C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,eAAuB;AACrB,WAAO,KAAK,IAAI,QAAQ,IAAI,YAAY,KAAK;AAAA,EAC/C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,iBAAoD;AAClD,UAAM,SAA4C,CAAC;AACnD,SAAK,IAAI,QAAQ,aAAa,QAAQ,CAAC,OAAO,QAAQ;AACpD,YAAM,WAAW,OAAO,GAAG;AAC3B,UAAI,UAAU;AACZ,YAAI,MAAM,QAAQ,QAAQ,GAAG;AAC3B,mBAAS,KA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ResourceServer","FacilitatorResponseError","NextResponse","response","x402HTTPResourceServer","x402ResourceServer","NextResponse","FacilitatorResponseError"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x402/next",
3
- "version": "2.7.0",
3
+ "version": "2.8.0",
4
4
  "main": "./dist/cjs/index.js",
5
5
  "module": "./dist/esm/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -28,12 +28,12 @@
28
28
  },
29
29
  "dependencies": {
30
30
  "zod": "^3.24.2",
31
- "@x402/extensions": "~2.7.0",
32
- "@x402/core": "~2.7.0"
31
+ "@x402/core": "~2.8.0",
32
+ "@x402/extensions": "~2.8.0"
33
33
  },
34
34
  "peerDependencies": {
35
35
  "next": "^16.0.10",
36
- "@x402/paywall": "^2.7.0"
36
+ "@x402/paywall": "^2.8.0"
37
37
  },
38
38
  "peerDependenciesMeta": {
39
39
  "@x402/paywall": {