@x402/next 2.4.0 → 2.5.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.
- package/dist/cjs/index.cjs +8 -4
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/esm/index.js +8 -4
- package/dist/esm/index.js.map +1 -1
- package/package.json +4 -4
package/dist/cjs/index.cjs
CHANGED
|
@@ -194,15 +194,17 @@ function handlePaymentError(response) {
|
|
|
194
194
|
headers
|
|
195
195
|
});
|
|
196
196
|
}
|
|
197
|
-
async function handleSettlement(httpServer, response, paymentPayload, paymentRequirements, declaredExtensions) {
|
|
197
|
+
async function handleSettlement(httpServer, response, paymentPayload, paymentRequirements, declaredExtensions, httpContext) {
|
|
198
198
|
if (response.status >= 400) {
|
|
199
199
|
return response;
|
|
200
200
|
}
|
|
201
201
|
try {
|
|
202
|
+
const responseBody = Buffer.from(await response.clone().arrayBuffer());
|
|
202
203
|
const result = await httpServer.processSettlement(
|
|
203
204
|
paymentPayload,
|
|
204
205
|
paymentRequirements,
|
|
205
|
-
declaredExtensions
|
|
206
|
+
declaredExtensions,
|
|
207
|
+
{ request: httpContext, responseBody }
|
|
206
208
|
);
|
|
207
209
|
if (!result.success) {
|
|
208
210
|
return new import_server.NextResponse(
|
|
@@ -275,7 +277,8 @@ function paymentProxyFromHTTPServer(httpServer, paywallConfig, paywall, syncFaci
|
|
|
275
277
|
nextResponse,
|
|
276
278
|
paymentPayload,
|
|
277
279
|
paymentRequirements,
|
|
278
|
-
declaredExtensions
|
|
280
|
+
declaredExtensions,
|
|
281
|
+
context
|
|
279
282
|
);
|
|
280
283
|
}
|
|
281
284
|
}
|
|
@@ -328,7 +331,8 @@ function withX402FromHTTPServer(routeHandler, httpServer, paywallConfig, paywall
|
|
|
328
331
|
handlerResponse,
|
|
329
332
|
paymentPayload,
|
|
330
333
|
paymentRequirements,
|
|
331
|
-
declaredExtensions
|
|
334
|
+
declaredExtensions,
|
|
335
|
+
context
|
|
332
336
|
);
|
|
333
337
|
}
|
|
334
338
|
}
|
package/dist/cjs/index.cjs.map
CHANGED
|
@@ -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 );\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 ) 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 * @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): 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 const result = await httpServer.processSettlement(\n paymentPayload,\n paymentRequirements,\n declaredExtensions,\n );\n\n if (!result.success) {\n // Settlement failed - do not return the protected resource\n return new NextResponse(\n JSON.stringify({\n error: \"Settlement failed\",\n details: result.errorReason,\n }),\n {\n status: 402,\n headers: { \"Content-Type\": \"application/json\" },\n },\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(\n JSON.stringify({\n error: \"Settlement failed\",\n details: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 402,\n headers: { \"Content-Type\": \"application/json\" },\n },\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,IAA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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","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} 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 return new NextResponse(\n JSON.stringify({\n error: \"Settlement failed\",\n details: result.errorReason,\n }),\n {\n status: 402,\n headers: { \"Content-Type\": \"application/json\" },\n },\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(\n JSON.stringify({\n error: \"Settlement failed\",\n details: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 402,\n headers: { \"Content-Type\": \"application/json\" },\n },\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.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A,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","import_server"]}
|
package/dist/esm/index.js
CHANGED
|
@@ -156,15 +156,17 @@ function handlePaymentError(response) {
|
|
|
156
156
|
headers
|
|
157
157
|
});
|
|
158
158
|
}
|
|
159
|
-
async function handleSettlement(httpServer, response, paymentPayload, paymentRequirements, declaredExtensions) {
|
|
159
|
+
async function handleSettlement(httpServer, response, paymentPayload, paymentRequirements, declaredExtensions, httpContext) {
|
|
160
160
|
if (response.status >= 400) {
|
|
161
161
|
return response;
|
|
162
162
|
}
|
|
163
163
|
try {
|
|
164
|
+
const responseBody = Buffer.from(await response.clone().arrayBuffer());
|
|
164
165
|
const result = await httpServer.processSettlement(
|
|
165
166
|
paymentPayload,
|
|
166
167
|
paymentRequirements,
|
|
167
|
-
declaredExtensions
|
|
168
|
+
declaredExtensions,
|
|
169
|
+
{ request: httpContext, responseBody }
|
|
168
170
|
);
|
|
169
171
|
if (!result.success) {
|
|
170
172
|
return new NextResponse(
|
|
@@ -241,7 +243,8 @@ function paymentProxyFromHTTPServer(httpServer, paywallConfig, paywall, syncFaci
|
|
|
241
243
|
nextResponse,
|
|
242
244
|
paymentPayload,
|
|
243
245
|
paymentRequirements,
|
|
244
|
-
declaredExtensions
|
|
246
|
+
declaredExtensions,
|
|
247
|
+
context
|
|
245
248
|
);
|
|
246
249
|
}
|
|
247
250
|
}
|
|
@@ -294,7 +297,8 @@ function withX402FromHTTPServer(routeHandler, httpServer, paywallConfig, paywall
|
|
|
294
297
|
handlerResponse,
|
|
295
298
|
paymentPayload,
|
|
296
299
|
paymentRequirements,
|
|
297
|
-
declaredExtensions
|
|
300
|
+
declaredExtensions,
|
|
301
|
+
context
|
|
298
302
|
);
|
|
299
303
|
}
|
|
300
304
|
}
|
package/dist/esm/index.js.map
CHANGED
|
@@ -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 );\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 ) 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 * @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): 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 const result = await httpServer.processSettlement(\n paymentPayload,\n paymentRequirements,\n declaredExtensions,\n );\n\n if (!result.success) {\n // Settlement failed - do not return the protected resource\n return new NextResponse(\n JSON.stringify({\n error: \"Settlement failed\",\n details: result.errorReason,\n }),\n {\n status: 402,\n headers: { \"Content-Type\": \"application/json\" },\n },\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(\n JSON.stringify({\n error: \"Settlement failed\",\n details: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 402,\n headers: { \"Content-Type\": \"application/json\" },\n },\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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uB,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","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} 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 return new NextResponse(\n JSON.stringify({\n error: \"Settlement failed\",\n details: result.errorReason,\n }),\n {\n status: 402,\n headers: { \"Content-Type\": \"application/json\" },\n },\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(\n JSON.stringify({\n error: \"Settlement failed\",\n details: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 402,\n headers: { \"Content-Type\": \"application/json\" },\n },\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;AAAA;AAAA,EAOA,iBAAoD;AAClD,UAAM,SAA4C,CAAC;AACnD,SAAK,IAAI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AEvB,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","x402HTTPResourceServer","x402ResourceServer","NextResponse"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@x402/next",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.5.0",
|
|
4
4
|
"main": "./dist/cjs/index.js",
|
|
5
5
|
"module": "./dist/esm/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -29,12 +29,12 @@
|
|
|
29
29
|
"dependencies": {
|
|
30
30
|
"@coinbase/cdp-sdk": "^1.22.0",
|
|
31
31
|
"zod": "^3.24.2",
|
|
32
|
-
"@x402/core": "~2.
|
|
33
|
-
"@x402/extensions": "~2.
|
|
32
|
+
"@x402/core": "~2.5.0",
|
|
33
|
+
"@x402/extensions": "~2.5.0"
|
|
34
34
|
},
|
|
35
35
|
"peerDependencies": {
|
|
36
36
|
"next": "^16.0.10",
|
|
37
|
-
"@x402/paywall": "2.
|
|
37
|
+
"@x402/paywall": "2.5.0"
|
|
38
38
|
},
|
|
39
39
|
"peerDependenciesMeta": {
|
|
40
40
|
"@x402/paywall": {
|