@bankofai/x402-core 1.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +294 -0
- package/dist/cjs/client/index.d.ts +149 -0
- package/dist/cjs/client/index.js +909 -0
- package/dist/cjs/client/index.js.map +1 -0
- package/dist/cjs/facilitator/index.d.ts +206 -0
- package/dist/cjs/facilitator/index.js +431 -0
- package/dist/cjs/facilitator/index.js.map +1 -0
- package/dist/cjs/http/index.d.ts +50 -0
- package/dist/cjs/http/index.js +1452 -0
- package/dist/cjs/http/index.js.map +1 -0
- package/dist/cjs/index.d.ts +3 -0
- package/dist/cjs/index.js +31 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/schemas/index.d.ts +891 -0
- package/dist/cjs/schemas/index.js +216 -0
- package/dist/cjs/schemas/index.js.map +1 -0
- package/dist/cjs/server/index.d.ts +79 -0
- package/dist/cjs/server/index.js +2568 -0
- package/dist/cjs/server/index.js.map +1 -0
- package/dist/cjs/types/index.d.ts +1 -0
- package/dist/cjs/types/index.js +97 -0
- package/dist/cjs/types/index.js.map +1 -0
- package/dist/cjs/types/v1/index.d.ts +1 -0
- package/dist/cjs/types/v1/index.js +19 -0
- package/dist/cjs/types/v1/index.js.map +1 -0
- package/dist/cjs/utils/index.d.ts +77 -0
- package/dist/cjs/utils/index.js +179 -0
- package/dist/cjs/utils/index.js.map +1 -0
- package/dist/cjs/x402Client-BgegfQgE.d.ts +1807 -0
- package/dist/cjs/x402Client-TQHctrG7.d.ts +1807 -0
- package/dist/esm/chunk-ABS7D6VX.mjs +145 -0
- package/dist/esm/chunk-ABS7D6VX.mjs.map +1 -0
- package/dist/esm/chunk-AGOUMC4P.mjs +68 -0
- package/dist/esm/chunk-AGOUMC4P.mjs.map +1 -0
- package/dist/esm/chunk-BJTO5JO5.mjs +11 -0
- package/dist/esm/chunk-BJTO5JO5.mjs.map +1 -0
- package/dist/esm/chunk-FPXAE3OS.mjs +161 -0
- package/dist/esm/chunk-FPXAE3OS.mjs.map +1 -0
- package/dist/esm/chunk-IL77TMJL.mjs +1275 -0
- package/dist/esm/chunk-IL77TMJL.mjs.map +1 -0
- package/dist/esm/chunk-VE37GDG2.mjs +7 -0
- package/dist/esm/chunk-VE37GDG2.mjs.map +1 -0
- package/dist/esm/client/index.d.mts +149 -0
- package/dist/esm/client/index.mjs +504 -0
- package/dist/esm/client/index.mjs.map +1 -0
- package/dist/esm/facilitator/index.d.mts +206 -0
- package/dist/esm/facilitator/index.mjs +399 -0
- package/dist/esm/facilitator/index.mjs.map +1 -0
- package/dist/esm/http/index.d.mts +50 -0
- package/dist/esm/http/index.mjs +35 -0
- package/dist/esm/http/index.mjs.map +1 -0
- package/dist/esm/index.d.mts +3 -0
- package/dist/esm/index.mjs +8 -0
- package/dist/esm/index.mjs.map +1 -0
- package/dist/esm/schemas/index.d.mts +891 -0
- package/dist/esm/schemas/index.mjs +70 -0
- package/dist/esm/schemas/index.mjs.map +1 -0
- package/dist/esm/server/index.d.mts +79 -0
- package/dist/esm/server/index.mjs +1318 -0
- package/dist/esm/server/index.mjs.map +1 -0
- package/dist/esm/types/index.d.mts +1 -0
- package/dist/esm/types/index.mjs +14 -0
- package/dist/esm/types/index.mjs.map +1 -0
- package/dist/esm/types/v1/index.d.mts +1 -0
- package/dist/esm/types/v1/index.mjs +1 -0
- package/dist/esm/types/v1/index.mjs.map +1 -0
- package/dist/esm/utils/index.d.mts +77 -0
- package/dist/esm/utils/index.mjs +28 -0
- package/dist/esm/utils/index.mjs.map +1 -0
- package/dist/esm/x402Client-BgegfQgE.d.mts +1807 -0
- package/dist/esm/x402Client-TQHctrG7.d.mts +1807 -0
- package/package.json +142 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/server/hookPolicy.ts","../../../src/server/x402ResourceServer.ts"],"sourcesContent":["import type { SettleResponse } from \"../types/facilitator\";\nimport type { PaymentRequirements } from \"../types/payments\";\nimport { deepEqual } from \"../utils\";\n\n/**\n * True when a string field is treated as unset and may be filled by `enrichPaymentRequiredResponse`.\n *\n * @param value - Candidate string from `PaymentRequirements` (e.g. `payTo`, `amount`, `asset`)\n * @returns Whether the field counts as vacant (empty or whitespace-only)\n */\nexport function isVacantStringField(value: string): boolean {\n return value.trim() === \"\";\n}\n\n/**\n * Deep snapshot of `accepts` entries before any `enrichPaymentRequiredResponse` runs.\n *\n * @param requirements - Payment requirement rows to clone\n * @returns Cloned requirements suitable as an immutable baseline for policy checks\n */\nexport function snapshotPaymentRequirementsList(\n requirements: PaymentRequirements[],\n): PaymentRequirements[] {\n return requirements.map(req => ({\n ...req,\n extra: structuredClone(req.extra),\n }));\n}\n\n/**\n * After extension enrichment, each `accepts[i]` must still match the baseline except that\n * **`payTo`**, **`amount`**, and **`asset`** may change only when the baseline value is vacant\n * (whitespace-only string). **`scheme`**, **`network`**, and **`maxTimeoutSeconds`** are never\n * writable by extensions. **`extra`** may gain new keys; values for keys present in the baseline\n * must be unchanged (deep-equal).\n *\n * @param baseline - Snapshot taken before any enrich hooks for this response\n * @param current - Live `accepts` entries after an extension enrich step\n * @param extensionKey - Registered extension key (for error messages)\n * @returns Nothing; throws if the policy is violated\n */\nexport function assertAcceptsAllowlistedAfterExtensionEnrich(\n baseline: PaymentRequirements[],\n current: PaymentRequirements[],\n extensionKey: string,\n): void {\n if (baseline.length !== current.length) {\n throw new Error(\n `[x402] extension \"${extensionKey}\" violated accepts mutation policy: accepts length changed (${baseline.length} → ${current.length})`,\n );\n }\n\n for (let i = 0; i < baseline.length; i++) {\n const b = baseline[i];\n const c = current[i];\n\n if (b.scheme !== c.scheme || b.network !== c.network) {\n throw new Error(\n `[x402] extension \"${extensionKey}\" violated accepts mutation policy: scheme/network are immutable (index ${i})`,\n );\n }\n if (b.maxTimeoutSeconds !== c.maxTimeoutSeconds) {\n throw new Error(\n `[x402] extension \"${extensionKey}\" violated accepts mutation policy: maxTimeoutSeconds is immutable (index ${i})`,\n );\n }\n\n for (const field of [\"payTo\", \"amount\", \"asset\"] as const) {\n const bv = b[field];\n const cv = c[field];\n if (!isVacantStringField(bv) && cv !== bv) {\n throw new Error(\n `[x402] extension \"${extensionKey}\" violated accepts mutation policy: \"${field}\" may only be set when the resource left it vacant (\"\"); non-vacant values are immutable (index ${i})`,\n );\n }\n }\n\n for (const key of Object.keys(b.extra)) {\n if (!Object.prototype.hasOwnProperty.call(c.extra, key)) {\n throw new Error(\n `[x402] extension \"${extensionKey}\" violated accepts mutation policy: extra[\"${key}\"] was removed (index ${i})`,\n );\n }\n if (!deepEqual(c.extra[key], b.extra[key])) {\n throw new Error(\n `[x402] extension \"${extensionKey}\" violated accepts mutation policy: extra[\"${key}\"] may not be changed (index ${i})`,\n );\n }\n }\n }\n}\n\n/**\n * Ensures scheme 402 enrichment only adds `extra` keys to matching accepts.\n *\n * @param baseline - Snapshot before the scheme enrich step\n * @param current - Live `accepts` entries after scheme enrichment\n * @param scheme - Scheme whose hook was invoked\n * @param network - Network whose hook was invoked\n */\nexport function assertAcceptsAdditiveExtraAfterSchemeEnrich(\n baseline: PaymentRequirements[],\n current: PaymentRequirements[],\n scheme: string,\n network: string,\n): void {\n if (baseline.length !== current.length) {\n throw new Error(\n `[x402] scheme \"${scheme}\" violated accepts mutation policy: accepts length changed (${baseline.length} → ${current.length})`,\n );\n }\n\n for (let i = 0; i < baseline.length; i++) {\n const b = baseline[i];\n const c = current[i];\n const isMatchingAccept = b.scheme === scheme && b.network === network;\n\n if (b.scheme !== c.scheme || b.network !== c.network) {\n throw new Error(\n `[x402] scheme \"${scheme}\" violated accepts mutation policy: scheme/network are immutable (index ${i})`,\n );\n }\n if (\n b.maxTimeoutSeconds !== c.maxTimeoutSeconds ||\n b.payTo !== c.payTo ||\n b.amount !== c.amount ||\n b.asset !== c.asset\n ) {\n throw new Error(\n `[x402] scheme \"${scheme}\" violated accepts mutation policy: payment terms are immutable (index ${i})`,\n );\n }\n\n for (const key of Object.keys(b.extra)) {\n if (!Object.prototype.hasOwnProperty.call(c.extra, key)) {\n throw new Error(\n `[x402] scheme \"${scheme}\" violated accepts mutation policy: extra[\"${key}\"] was removed (index ${i})`,\n );\n }\n if (!deepEqual(c.extra[key], b.extra[key])) {\n throw new Error(\n `[x402] scheme \"${scheme}\" violated accepts mutation policy: extra[\"${key}\"] may not be changed (index ${i})`,\n );\n }\n }\n\n if (!isMatchingAccept && Object.keys(c.extra).length !== Object.keys(b.extra).length) {\n throw new Error(\n `[x402] scheme \"${scheme}\" violated accepts mutation policy: only matching accepts may receive new extra fields (index ${i})`,\n );\n }\n }\n}\n\n/**\n * Immutable subset of {@link SettleResponse} compared across settlement extension enrich.\n */\nexport type SettleResponseCoreSnapshot = Pick<\n SettleResponse,\n \"success\" | \"transaction\" | \"network\" | \"amount\" | \"payer\" | \"errorReason\" | \"errorMessage\"\n>;\n\n/**\n * Captures facilitator-settled fields that extensions must not rewrite.\n *\n * @param result - Settlement response from the facilitator\n * @returns Plain snapshot of core fields for later comparison\n */\nexport function snapshotSettleResponseCore(result: SettleResponse): SettleResponseCoreSnapshot {\n return {\n success: result.success,\n transaction: result.transaction,\n network: result.network,\n amount: result.amount,\n payer: result.payer,\n errorReason: result.errorReason,\n errorMessage: result.errorMessage,\n };\n}\n\n/**\n * Ensures `enrichSettlementResponse` did not rewrite facilitator outcome fields; only\n * `extensions` may be populated via the merger (in addition to in-place adds on `extensions`).\n *\n * @param before - Snapshot taken before extension settlement enrich\n * @param after - Live settlement result after an extension enrich step\n * @param extensionKey - Registered extension key (for error messages)\n * @returns Nothing; throws if a core field changed\n */\nexport function assertSettleResponseCoreUnchanged(\n before: SettleResponseCoreSnapshot,\n after: SettleResponse,\n extensionKey: string,\n): void {\n const keys: (keyof SettleResponseCoreSnapshot)[] = [\n \"success\",\n \"transaction\",\n \"network\",\n \"amount\",\n \"payer\",\n \"errorReason\",\n \"errorMessage\",\n ];\n for (const k of keys) {\n if (!deepEqual(after[k], before[k])) {\n throw new Error(\n `[x402] extension \"${extensionKey}\" violated settlement mutation policy: field \"${String(k)}\" is immutable after facilitator settle`,\n );\n }\n }\n}\n\n/**\n * Ensures scheme settlement-payload enrichment only adds server-owned fields.\n *\n * @param payload - Existing scheme payload before enrichment\n * @param enrichment - Fields returned by the scheme enrichment hook\n * @param callerLabel - Hook source label used in policy error messages\n */\nexport function assertAdditivePayloadEnrichment(\n payload: Record<string, unknown>,\n enrichment: Record<string, unknown>,\n callerLabel: string,\n): void {\n for (const key of Object.keys(enrichment)) {\n if (!Object.prototype.hasOwnProperty.call(payload, key)) continue;\n\n throw new Error(\n `[x402] ${callerLabel} violated settlement payload enrichment policy: \"${key}\" already exists on the client payload`,\n );\n }\n}\n\n/**\n * Whether `value` is a plain object record (not null or an array).\n *\n * @param value - Value to inspect\n * @returns True when `value` is a non-null object and not an array\n */\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Ensures scheme response enrichment only adds new `extra` fields, including nested fields\n * below existing objects.\n *\n * @param extra - Existing settlement extra fields\n * @param enrichment - Fields returned by the scheme response enrichment hook\n * @param callerLabel - Hook label used in policy error messages\n */\nexport function assertAdditiveSettlementExtra(\n extra: Record<string, unknown>,\n enrichment: Record<string, unknown>,\n callerLabel: string,\n): void {\n assertAdditiveRecord(extra, enrichment, callerLabel, \"extra\");\n}\n\n/**\n * Merges server-owned settlement response fields after additive policy validation.\n *\n * @param extra - Existing settlement extra fields\n * @param enrichment - Additive fields returned by the scheme response enrichment hook\n * @returns A merged extra object\n */\nexport function mergeAdditiveSettlementExtra(\n extra: Record<string, unknown>,\n enrichment: Record<string, unknown>,\n): Record<string, unknown> {\n return mergeAdditiveRecord(extra, enrichment);\n}\n\n/**\n * Throws if enrichment would overwrite or collide with keys already present on `target`,\n * recursively for nested plain objects.\n *\n * @param target - Existing record fields before enrichment\n * @param enrichment - Fields proposed by the hook to merge into `target`\n * @param callerLabel - Hook label used in policy error messages\n * @param path - Dot-style path segment for nested keys (for error messages)\n */\nfunction assertAdditiveRecord(\n target: Record<string, unknown>,\n enrichment: Record<string, unknown>,\n callerLabel: string,\n path: string,\n): void {\n for (const [key, enrichmentValue] of Object.entries(enrichment)) {\n const nextPath = `${path}[\"${key}\"]`;\n if (!Object.prototype.hasOwnProperty.call(target, key)) continue;\n\n const targetValue = target[key];\n if (isPlainRecord(targetValue) && isPlainRecord(enrichmentValue)) {\n assertAdditiveRecord(targetValue, enrichmentValue, callerLabel, nextPath);\n continue;\n }\n\n throw new Error(\n `[x402] ${callerLabel} violated settlement response enrichment policy: ${nextPath} already exists on the settlement result`,\n );\n }\n}\n\n/**\n * Deep-merges `enrichment` into `target`, recursively merging nested plain objects.\n *\n * @param target - Base record to merge into\n * @param enrichment - Additive fields to merge (caller must enforce additive policy first)\n * @returns Shallow copy of `target` with `enrichment` applied\n */\nfunction mergeAdditiveRecord(\n target: Record<string, unknown>,\n enrichment: Record<string, unknown>,\n): Record<string, unknown> {\n const merged = { ...target };\n for (const [key, enrichmentValue] of Object.entries(enrichment)) {\n const targetValue = merged[key];\n if (isPlainRecord(targetValue) && isPlainRecord(enrichmentValue)) {\n merged[key] = mergeAdditiveRecord(targetValue, enrichmentValue);\n continue;\n }\n merged[key] = enrichmentValue;\n }\n return merged;\n}\n","import {\n SettleError,\n SettleResponse,\n VerifyResponse,\n SupportedResponse,\n SupportedKind,\n} from \"../types/facilitator\";\nimport {\n PaymentPayload,\n PaymentRequirements,\n PaymentRequired,\n ResourceInfo,\n} from \"../types/payments\";\nimport { SchemeNetworkServer, SchemePaymentRequiredContext } from \"../types/mechanisms\";\nimport { Price, Network, ResourceServerExtension, ResourceServerExtensionHooks } from \"../types\";\nimport type { DeepReadonly } from \"../types/readonly\";\nimport { deepEqual, findByNetworkAndScheme } from \"../utils\";\nimport {\n assertAcceptsAllowlistedAfterExtensionEnrich,\n assertAcceptsAdditiveExtraAfterSchemeEnrich,\n assertAdditivePayloadEnrichment,\n assertAdditiveSettlementExtra,\n assertSettleResponseCoreUnchanged,\n mergeAdditiveSettlementExtra,\n snapshotPaymentRequirementsList,\n snapshotSettleResponseCore,\n} from \"./hookPolicy\";\nimport { FacilitatorClient, HTTPFacilitatorClient } from \"../http/httpFacilitatorClient\";\nimport { x402Version } from \"..\";\n\n/**\n * Configuration for a protected resource\n * Only contains payment-specific configuration, not resource metadata\n */\nexport interface ResourceConfig {\n scheme: string;\n /**\n * Payment recipient. Use a **vacant** value (`\"\"` or whitespace-only) when an extension must\n * fill `payTo` during `enrichPaymentRequiredResponse`; non-vacant values are **immutable** there\n * so extensions cannot redirect funds to an arbitrary address.\n */\n payTo: string;\n price: Price;\n network: Network;\n maxTimeoutSeconds?: number;\n extra?: Record<string, unknown>; // Scheme-specific additional data\n}\n\n/**\n * Context for `enrichPaymentRequiredResponse`. Extensions may merge extension payload via the\n * return value. In-place edits to `paymentRequiredResponse.accepts` are **allowlisted** only\n * (see {@link assertAcceptsAllowlistedAfterExtensionEnrich}): `scheme`, `network`, and\n * `maxTimeoutSeconds` are immutable; `payTo`, `amount`, and `asset` may change only when the\n * baseline value was vacant; `extra` may add keys but must not change or remove baseline keys.\n */\nexport interface PaymentRequiredContext {\n requirements: PaymentRequirements[];\n resourceInfo: ResourceInfo;\n error?: string;\n paymentRequiredResponse: PaymentRequired;\n transportContext?: unknown;\n}\n\n/**\n * Verify / settle lifecycle hook context: treat as **read-only** for core protocol fields.\n * Control flow uses **abort** / **recover** return values only, not in-place mutation.\n */\nexport interface VerifyContext {\n paymentPayload: DeepReadonly<PaymentPayload>;\n requirements: DeepReadonly<PaymentRequirements>;\n declaredExtensions: DeepReadonly<Record<string, unknown>>;\n transportContext?: unknown;\n}\n\nexport interface VerifyResultContext extends VerifyContext {\n result: DeepReadonly<VerifyResponse>;\n}\n\n/**\n * Optional acknowledgement body returned to the caller when an `AfterVerifyHook`\n * requests that the resource handler be skipped for a self-contained operation\n * (e.g. cooperative refund). Travels in-process only — never on the facilitator wire.\n */\nexport interface SkipHandlerDirective {\n contentType?: string;\n body?: unknown;\n}\n\nexport type ResourceVerifyRespone = VerifyResponse & {\n skipHandler?: SkipHandlerDirective;\n};\n\nexport interface VerifyFailureContext extends VerifyContext {\n error: Error;\n}\n\nexport interface SettleContext {\n paymentPayload: DeepReadonly<PaymentPayload>;\n requirements: DeepReadonly<PaymentRequirements>;\n declaredExtensions: DeepReadonly<Record<string, unknown>>;\n transportContext?: unknown;\n}\n\nexport interface SettleResultContext extends SettleContext {\n result: DeepReadonly<SettleResponse>;\n}\n\nexport interface SettleFailureContext extends SettleContext {\n error: Error;\n}\n\nexport type VerifiedPaymentCancellationReason = \"handler_threw\" | \"handler_failed\";\n\nexport interface VerifiedPaymentCanceledContext extends SettleContext {\n reason: VerifiedPaymentCancellationReason;\n error?: unknown;\n responseStatus?: number;\n}\n\nexport interface VerifiedPaymentCancelOptions {\n reason: VerifiedPaymentCancellationReason;\n error?: unknown;\n responseStatus?: number;\n}\n\nexport interface PaymentCancellationDispatcher {\n cancel(options: VerifiedPaymentCancelOptions): Promise<void>;\n}\n\nexport type BeforeVerifyHook = (\n context: VerifyContext,\n) => Promise<\n void | { abort: true; reason: string; message?: string } | { skip: true; result: VerifyResponse }\n>;\n\nexport type AfterVerifyHook = (\n context: VerifyResultContext,\n) => Promise<void | { skipHandler: true; response?: SkipHandlerDirective }>;\n\nexport type OnVerifyFailureHook = (\n context: VerifyFailureContext,\n) => Promise<void | { recovered: true; result: VerifyResponse }>;\n\nexport type BeforeSettleHook = (\n context: SettleContext,\n) => Promise<\n void | { abort: true; reason: string; message?: string } | { skip: true; result: SettleResponse }\n>;\n\nexport type AfterSettleHook = (context: SettleResultContext) => Promise<void>;\n\nexport type OnSettleFailureHook = (\n context: SettleFailureContext,\n) => Promise<void | { recovered: true; result: SettleResponse }>;\n\nexport type OnVerifiedPaymentCanceledHook = (\n context: VerifiedPaymentCanceledContext,\n) => Promise<void>;\n\n/**\n * Optional overrides for settlement parameters.\n * Used to support partial settlement (e.g., upto scheme billing by actual usage).\n *\n * Note: Overriding the amount to a value different from the agreed-upon\n * `PaymentRequirements.amount` is only valid in schemes that explicitly support\n * partial settlement, such as the `upto` scheme. Using this with standard\n * x402 schemes (e.g., `exact`) will likely cause settlement verification to fail.\n */\nexport type ExtensionValidationResult =\n | { valid: true }\n | { valid: false; invalidReason: \"extension_echo_mismatch\"; extensionKey: string };\n\nexport interface SettlementOverrides {\n /**\n * Amount to settle. Supports three formats:\n *\n * - **Raw atomic units** — e.g., `\"1000\"` settles exactly 1000 atomic units.\n * - **Percent** — e.g., `\"50%\"` settles 50% of `PaymentRequirements.amount`.\n * Supports up to two decimal places (e.g., `\"33.33%\"`). The result is floored\n * to the nearest atomic unit.\n * - **Dollar price** — e.g., `\"$0.05\"` converts a USD-denominated price to\n * atomic units. Decimals are determined from the registered scheme's\n * `getAssetDecimals` method, falling back to 6 (standard for USDC stablecoins).\n * The result is rounded to the nearest atomic unit.\n *\n * The resolved amount must be <= the authorized maximum in `PaymentRequirements`.\n *\n * Note: Setting this to an amount other than `PaymentRequirements.amount` is\n * only valid in schemes that support partial settlement, such as `upto`.\n */\n amount?: string;\n}\n\n/**\n * Resolves a settlement override amount string to a final atomic-unit string.\n *\n * Supports three input formats (see {@link SettlementOverrides.amount}):\n * - Raw atomic units: `\"1000\"`\n * - Percent of `PaymentRequirements.amount`: `\"50%\"`\n * - Dollar price: `\"$0.05\"` (converted using the provided decimals)\n *\n * @param rawAmount - The override amount string (e.g., `\"1000\"`, `\"50%\"`, `\"$0.05\"`)\n * @param requirements - The payment requirements containing the base amount\n * @param decimals - Decimal precision to use for dollar-format conversion (default 6)\n * @returns The resolved amount as an atomic-unit string\n */\nexport function resolveSettlementOverrideAmount(\n rawAmount: string,\n requirements: PaymentRequirements,\n decimals: number = 6,\n): string {\n // Percent format: \"50%\" or \"33.33%\"\n const percentMatch = rawAmount.match(/^(\\d+(?:\\.\\d{0,2})?)%$/);\n if (percentMatch) {\n const [intPart, decPart = \"\"] = percentMatch[1].split(\".\");\n const scaledPercent = BigInt(intPart) * 100n + BigInt(decPart.padEnd(2, \"0\").slice(0, 2));\n const base = BigInt(requirements.amount);\n return ((base * scaledPercent) / 10000n).toString();\n }\n\n // Dollar price format: \"$0.05\"\n const dollarMatch = rawAmount.match(/^\\$(\\d+(?:\\.\\d+)?)$/);\n if (dollarMatch) {\n const dollars = parseFloat(dollarMatch[1]);\n return Math.round(dollars * 10 ** decimals).toString();\n }\n\n // Raw atomic units (existing behavior)\n return rawAmount;\n}\n\ntype HookAdapterHandles = {\n beforeVerify?: BeforeVerifyHook;\n afterVerify?: AfterVerifyHook;\n onVerifyFailure?: OnVerifyFailureHook;\n beforeSettle?: BeforeSettleHook;\n afterSettle?: AfterSettleHook;\n onSettleFailure?: OnSettleFailureHook;\n onVerifiedPaymentCanceled?: OnVerifiedPaymentCanceledHook;\n};\n\ntype ExtensionAdapterHandles = HookAdapterHandles;\ntype SchemeAdapterHandles = HookAdapterHandles;\n\n/** Keys shared by adapter handles and manual `*Hooks` arrays on the server. */\ntype ResourceServerHookPhase = keyof HookAdapterHandles;\n\ntype ResourceServerManualHookArrayKey = `${ResourceServerHookPhase}Hooks`;\n\n/**\n * Core x402 protocol server for resource protection\n * Transport-agnostic implementation of the x402 payment protocol\n */\nexport class x402ResourceServer {\n private facilitatorClients: FacilitatorClient[];\n private registeredServerSchemes: Map<string, Map<string, SchemeNetworkServer>> = new Map();\n private schemeHookAdapters: Map<string, Map<string, SchemeAdapterHandles>> = new Map();\n private supportedResponsesMap: Map<number, Map<string, Map<string, SupportedResponse>>> =\n new Map();\n private facilitatorClientsMap: Map<number, Map<string, Map<string, FacilitatorClient>>> =\n new Map();\n private registeredExtensions: Map<string, ResourceServerExtension> = new Map();\n private extensionHookAdapters = new Map<string, ExtensionAdapterHandles>();\n\n private beforeVerifyHooks: BeforeVerifyHook[] = [];\n private afterVerifyHooks: AfterVerifyHook[] = [];\n private onVerifyFailureHooks: OnVerifyFailureHook[] = [];\n private beforeSettleHooks: BeforeSettleHook[] = [];\n private afterSettleHooks: AfterSettleHook[] = [];\n private onSettleFailureHooks: OnSettleFailureHook[] = [];\n private onVerifiedPaymentCanceledHooks: OnVerifiedPaymentCanceledHook[] = [];\n\n /**\n * Creates a new x402ResourceServer instance.\n *\n * @param facilitatorClients - Optional facilitator client(s) for payment processing\n */\n constructor(facilitatorClients?: FacilitatorClient | FacilitatorClient[]) {\n // Normalize facilitator clients to array\n if (!facilitatorClients) {\n // No clients provided, create a default HTTP client\n this.facilitatorClients = [new HTTPFacilitatorClient()];\n } else if (Array.isArray(facilitatorClients)) {\n // Array of clients provided\n this.facilitatorClients =\n facilitatorClients.length > 0 ? facilitatorClients : [new HTTPFacilitatorClient()];\n } else {\n // Single client provided\n this.facilitatorClients = [facilitatorClients];\n }\n }\n\n /**\n * Register a scheme/network server implementation.\n *\n * @param network - The network identifier\n * @param server - The scheme/network server implementation\n * @returns The x402ResourceServer instance for chaining\n */\n register(network: Network, server: SchemeNetworkServer): x402ResourceServer {\n if (!this.registeredServerSchemes.has(network)) {\n this.registeredServerSchemes.set(network, new Map());\n }\n\n const serverByScheme = this.registeredServerSchemes.get(network)!;\n serverByScheme.set(server.scheme, server);\n\n if (!this.schemeHookAdapters.has(network)) {\n this.schemeHookAdapters.set(network, new Map());\n }\n\n const hooksByScheme = this.schemeHookAdapters.get(network)!;\n const hooks = server.schemeHooks;\n if (!hooks) {\n hooksByScheme.delete(server.scheme);\n return this;\n }\n\n const handles: SchemeAdapterHandles = {};\n if (hooks.onBeforeVerify) handles.beforeVerify = hooks.onBeforeVerify;\n if (hooks.onAfterVerify) handles.afterVerify = hooks.onAfterVerify;\n if (hooks.onVerifyFailure) handles.onVerifyFailure = hooks.onVerifyFailure;\n if (hooks.onBeforeSettle) handles.beforeSettle = hooks.onBeforeSettle;\n if (hooks.onAfterSettle) handles.afterSettle = hooks.onAfterSettle;\n if (hooks.onSettleFailure) handles.onSettleFailure = hooks.onSettleFailure;\n if (hooks.onVerifiedPaymentCanceled) {\n handles.onVerifiedPaymentCanceled = hooks.onVerifiedPaymentCanceled;\n }\n\n if (Object.keys(handles).length > 0) {\n hooksByScheme.set(server.scheme, handles);\n } else {\n hooksByScheme.delete(server.scheme);\n }\n\n return this;\n }\n\n /**\n * Check if a scheme is registered for a given network.\n *\n * @param network - The network identifier\n * @param scheme - The payment scheme name\n * @returns True if the scheme is registered for the network, false otherwise\n */\n hasRegisteredScheme(network: Network, scheme: string): boolean {\n return !!findByNetworkAndScheme(this.registeredServerSchemes, scheme, network);\n }\n\n /**\n * Returns the decimal precision for the asset specified in the given payment requirements.\n * Looks up the registered scheme for the network and delegates to its getAssetDecimals\n * method if available. Falls back to 6 (standard for USDC stablecoins) when the scheme\n * does not implement getAssetDecimals or is not registered.\n *\n * @param requirements - The payment requirements containing scheme, network, and asset\n * @returns The number of decimal places for the asset\n */\n getAssetDecimalsForRequirements(requirements: PaymentRequirements): number {\n const scheme = findByNetworkAndScheme(\n this.registeredServerSchemes,\n requirements.scheme,\n requirements.network as Network,\n );\n return (\n scheme?.getAssetDecimals?.(requirements.asset ?? \"\", requirements.network as Network) ?? 6\n );\n }\n\n /**\n * Registers a resource server extension (enrichment and optional verify/settle hooks).\n * Re-registering the same key overwrites; omitting `hooks` removes adapter handles for that key.\n *\n * @param extension - Extension definition including `key` and optional `hooks`\n * @returns This server instance for chaining\n */\n registerExtension(extension: ResourceServerExtension): this {\n this.registeredExtensions.set(extension.key, extension);\n const extensionKey = extension.key;\n const extensionHooks = extension.hooks;\n if (!extensionHooks) {\n this.extensionHookAdapters.delete(extensionKey);\n return this;\n }\n const handles: ExtensionAdapterHandles = {};\n\n const bindExtensionHookAdapter = <\n ExtKey extends keyof ResourceServerExtensionHooks,\n Phase extends ResourceServerHookPhase,\n >(\n extensionHookKey: ExtKey,\n adapterPhase: Phase,\n ): void => {\n const impl = extensionHooks[extensionHookKey];\n if (!impl) return;\n\n type AdapterContext = Parameters<NonNullable<ExtensionAdapterHandles[Phase]>>[0];\n\n handles[adapterPhase] = (async (ctx: AdapterContext) => {\n if (ctx.declaredExtensions[extensionKey] === undefined) return;\n return (impl as (declaration: unknown, context: AdapterContext) => Promise<unknown>)(\n ctx.declaredExtensions[extensionKey],\n ctx,\n );\n }) as ExtensionAdapterHandles[Phase];\n };\n\n bindExtensionHookAdapter(\"onBeforeVerify\", \"beforeVerify\");\n bindExtensionHookAdapter(\"onAfterVerify\", \"afterVerify\");\n bindExtensionHookAdapter(\"onVerifyFailure\", \"onVerifyFailure\");\n bindExtensionHookAdapter(\"onBeforeSettle\", \"beforeSettle\");\n bindExtensionHookAdapter(\"onAfterSettle\", \"afterSettle\");\n bindExtensionHookAdapter(\"onSettleFailure\", \"onSettleFailure\");\n bindExtensionHookAdapter(\"onVerifiedPaymentCanceled\", \"onVerifiedPaymentCanceled\");\n if (Object.keys(handles).length > 0) {\n this.extensionHookAdapters.set(extensionKey, handles);\n } else {\n this.extensionHookAdapters.delete(extensionKey);\n }\n return this;\n }\n\n /**\n * Check if an extension is registered.\n *\n * @param key - The extension key\n * @returns True if the extension is registered\n */\n hasExtension(key: string): boolean {\n return this.registeredExtensions.has(key);\n }\n\n /**\n * Get all registered extensions.\n *\n * @returns Array of registered extensions\n */\n getExtensions(): ResourceServerExtension[] {\n return Array.from(this.registeredExtensions.values());\n }\n\n /**\n * Enriches declared extensions using registered extension hooks.\n *\n * @param declaredExtensions - Extensions declared on the route\n * @param transportContext - Transport-specific context (HTTP, A2A, MCP, etc.)\n * @returns Enriched extensions map\n */\n enrichExtensions(\n declaredExtensions: Record<string, unknown>,\n transportContext: unknown,\n ): Record<string, unknown> {\n const enriched: Record<string, unknown> = {};\n\n for (const [key, declaration] of Object.entries(declaredExtensions)) {\n const extension = this.registeredExtensions.get(key);\n\n if (extension?.enrichDeclaration) {\n try {\n enriched[key] = extension.enrichDeclaration(declaration, transportContext);\n } catch (error) {\n this.warnExtensionHookFailure(key, \"enrichDeclaration\", error);\n enriched[key] = declaration;\n }\n } else {\n enriched[key] = declaration;\n }\n }\n\n return enriched;\n }\n\n /**\n * Register a hook to execute before payment verification.\n * Can abort verification by returning { abort: true, reason: string }\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onBeforeVerify(hook: BeforeVerifyHook): x402ResourceServer {\n this.beforeVerifyHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute after successful payment verification.\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onAfterVerify(hook: AfterVerifyHook): x402ResourceServer {\n this.afterVerifyHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute when payment verification fails.\n * Can recover from failure by returning { recovered: true, result: VerifyResponse }\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onVerifyFailure(hook: OnVerifyFailureHook): x402ResourceServer {\n this.onVerifyFailureHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute before payment settlement.\n * Can abort settlement by returning { abort: true, reason: string }\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onBeforeSettle(hook: BeforeSettleHook): x402ResourceServer {\n this.beforeSettleHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute after successful payment settlement.\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onAfterSettle(hook: AfterSettleHook): x402ResourceServer {\n this.afterSettleHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute when payment settlement fails.\n * Can recover from failure by returning { recovered: true, result: SettleResponse }\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onSettleFailure(hook: OnSettleFailureHook): x402ResourceServer {\n this.onSettleFailureHooks.push(hook);\n return this;\n }\n\n /**\n * Register a hook to execute when verified payment work is canceled before settlement.\n *\n * @param hook - The hook function to register\n * @returns The x402ResourceServer instance for chaining\n */\n onVerifiedPaymentCanceled(hook: OnVerifiedPaymentCanceledHook): x402ResourceServer {\n this.onVerifiedPaymentCanceledHooks.push(hook);\n return this;\n }\n\n /**\n * Initialize by fetching supported kinds from all facilitators\n * Creates mappings for supported responses and facilitator clients\n * Earlier facilitators in the array get precedence\n */\n async initialize(): Promise<void> {\n // Clear existing mappings\n this.supportedResponsesMap.clear();\n this.facilitatorClientsMap.clear();\n let lastError: Error | undefined;\n\n // Fetch supported kinds from all facilitator clients\n // Process in order to give precedence to earlier facilitators\n for (const facilitatorClient of this.facilitatorClients) {\n try {\n const supported = await facilitatorClient.getSupported();\n\n // Process each supported kind (now flat array with version in each element)\n for (const kind of supported.kinds) {\n const x402Version = kind.x402Version;\n\n // Get or create version map for supported responses\n if (!this.supportedResponsesMap.has(x402Version)) {\n this.supportedResponsesMap.set(x402Version, new Map());\n }\n const responseVersionMap = this.supportedResponsesMap.get(x402Version)!;\n\n // Get or create version map for facilitator clients\n if (!this.facilitatorClientsMap.has(x402Version)) {\n this.facilitatorClientsMap.set(x402Version, new Map());\n }\n const clientVersionMap = this.facilitatorClientsMap.get(x402Version)!;\n\n // Get or create network map for responses\n if (!responseVersionMap.has(kind.network)) {\n responseVersionMap.set(kind.network, new Map());\n }\n const responseNetworkMap = responseVersionMap.get(kind.network)!;\n\n // Get or create network map for clients\n if (!clientVersionMap.has(kind.network)) {\n clientVersionMap.set(kind.network, new Map());\n }\n const clientNetworkMap = clientVersionMap.get(kind.network)!;\n\n // Only store if not already present (gives precedence to earlier facilitators)\n if (!responseNetworkMap.has(kind.scheme)) {\n responseNetworkMap.set(kind.scheme, supported);\n clientNetworkMap.set(kind.scheme, facilitatorClient);\n }\n }\n } catch (error) {\n lastError = error as Error;\n // Log error but continue with other facilitators\n console.warn(`Failed to fetch supported kinds from facilitator: ${error}`);\n }\n }\n\n if (this.supportedResponsesMap.size === 0) {\n throw lastError\n ? new Error(\n \"Failed to initialize: no supported payment kinds loaded from any facilitator.\",\n {\n cause: lastError,\n },\n )\n : new Error(\n \"Failed to initialize: no supported payment kinds loaded from any facilitator.\",\n );\n }\n }\n\n /**\n * Get supported kind for a specific version, network, and scheme\n *\n * @param x402Version - The x402 version\n * @param network - The network identifier\n * @param scheme - The payment scheme\n * @returns The supported kind or undefined if not found\n */\n getSupportedKind(\n x402Version: number,\n network: Network,\n scheme: string,\n ): SupportedKind | undefined {\n const versionMap = this.supportedResponsesMap.get(x402Version);\n if (!versionMap) return undefined;\n\n const supportedResponse = findByNetworkAndScheme(versionMap, scheme, network);\n if (!supportedResponse) return undefined;\n\n // Find the specific kind from the response (kinds are flat array with version in each element)\n return supportedResponse.kinds.find(\n kind =>\n kind.x402Version === x402Version && kind.network === network && kind.scheme === scheme,\n );\n }\n\n /**\n * Get facilitator extensions for a specific version, network, and scheme\n *\n * @param x402Version - The x402 version\n * @param network - The network identifier\n * @param scheme - The payment scheme\n * @returns The facilitator extensions or empty array if not found\n */\n getFacilitatorExtensions(x402Version: number, network: Network, scheme: string): string[] {\n const versionMap = this.supportedResponsesMap.get(x402Version);\n if (!versionMap) return [];\n\n const supportedResponse = findByNetworkAndScheme(versionMap, scheme, network);\n return supportedResponse?.extensions || [];\n }\n\n /**\n * Build payment requirements for a protected resource\n *\n * @param resourceConfig - Configuration for the protected resource\n * @returns Array of payment requirements\n */\n async buildPaymentRequirements(resourceConfig: ResourceConfig): Promise<PaymentRequirements[]> {\n const requirements: PaymentRequirements[] = [];\n\n // Find the matching server implementation\n const scheme = resourceConfig.scheme;\n const SchemeNetworkServer = findByNetworkAndScheme(\n this.registeredServerSchemes,\n scheme,\n resourceConfig.network,\n );\n\n if (!SchemeNetworkServer) {\n // Fallback to placeholder implementation if no server registered\n // TODO: Remove this fallback once implementations are registered\n console.warn(\n `No server implementation registered for scheme: ${scheme}, network: ${resourceConfig.network}`,\n );\n return requirements;\n }\n\n // Find the matching supported kind from facilitator\n const supportedKind = this.getSupportedKind(\n x402Version,\n resourceConfig.network,\n SchemeNetworkServer.scheme,\n );\n\n if (!supportedKind) {\n throw new Error(\n `Facilitator does not support ${SchemeNetworkServer.scheme} on ${resourceConfig.network}. ` +\n `Make sure to call initialize() to fetch supported kinds from facilitators.`,\n );\n }\n\n // Get facilitator extensions for this combination\n const facilitatorExtensions = this.getFacilitatorExtensions(\n x402Version,\n resourceConfig.network,\n SchemeNetworkServer.scheme,\n );\n\n // Parse the price using the scheme's price parser\n const parsedPrice = await SchemeNetworkServer.parsePrice(\n resourceConfig.price,\n resourceConfig.network,\n );\n\n // Build base payment requirements from resource config\n const baseRequirements: PaymentRequirements = {\n scheme: SchemeNetworkServer.scheme,\n network: resourceConfig.network,\n amount: parsedPrice.amount,\n asset: parsedPrice.asset,\n payTo: resourceConfig.payTo,\n maxTimeoutSeconds: resourceConfig.maxTimeoutSeconds || 300, // Default 5 minutes\n extra: {\n ...parsedPrice.extra,\n ...resourceConfig.extra, // Merge user-provided extra\n },\n };\n\n // Delegate to the implementation for scheme-specific enhancements\n const requirement = await SchemeNetworkServer.enhancePaymentRequirements(\n baseRequirements,\n supportedKind,\n facilitatorExtensions,\n );\n\n requirements.push(requirement);\n return requirements;\n }\n\n /**\n * Build payment requirements from multiple payment options\n * This method handles resolving dynamic payTo/price functions and builds requirements for each option\n *\n * @param paymentOptions - Array of payment options to convert\n * @param context - HTTP request context for resolving dynamic functions\n * @returns Array of payment requirements (one per option)\n */\n async buildPaymentRequirementsFromOptions<TContext = unknown>(\n paymentOptions: Array<{\n scheme: string;\n payTo: string | ((context: TContext) => string | Promise<string>);\n price: Price | ((context: TContext) => Price | Promise<Price>);\n network: Network;\n maxTimeoutSeconds?: number;\n extra?: Record<string, unknown>;\n }>,\n context: TContext,\n ): Promise<PaymentRequirements[]> {\n const allRequirements: PaymentRequirements[] = [];\n\n for (const option of paymentOptions) {\n // Resolve dynamic payTo and price if they are functions\n const resolvedPayTo =\n typeof option.payTo === \"function\" ? await option.payTo(context) : option.payTo;\n const resolvedPrice =\n typeof option.price === \"function\" ? await option.price(context) : option.price;\n\n const resourceConfig: ResourceConfig = {\n scheme: option.scheme,\n payTo: resolvedPayTo,\n price: resolvedPrice,\n network: option.network,\n maxTimeoutSeconds: option.maxTimeoutSeconds,\n extra: option.extra,\n };\n\n // Use existing buildPaymentRequirements for each option\n const requirements = await this.buildPaymentRequirements(resourceConfig);\n allRequirements.push(...requirements);\n }\n\n return allRequirements;\n }\n\n /**\n * Create a payment required response\n *\n * @param requirements - Payment requirements\n * @param resourceInfo - Resource information\n * @param error - Error message\n * @param extensions - Optional declared extensions (for per-key enrichment)\n * @param transportContext - Optional transport-specific context (e.g., HTTP request, MCP tool context)\n * @param paymentPayload - Optional failed payment payload for response-time scheme enrichment\n * @returns Payment required response object\n */\n async createPaymentRequiredResponse(\n requirements: PaymentRequirements[],\n resourceInfo: ResourceInfo,\n error?: string,\n extensions?: Record<string, unknown>,\n transportContext?: unknown,\n paymentPayload?: PaymentPayload,\n ): Promise<PaymentRequired> {\n const acceptsClone = requirements.map(req => ({\n ...req,\n extra: structuredClone(req.extra),\n }));\n let workingAccepts = acceptsClone;\n let baselineAccepts = snapshotPaymentRequirementsList(workingAccepts);\n\n // V2 response with resource at top level\n let response: PaymentRequired = {\n x402Version: 2,\n error,\n resource: resourceInfo,\n accepts: workingAccepts,\n };\n\n // Add extensions if provided\n if (extensions && Object.keys(extensions).length > 0) {\n response.extensions = extensions;\n }\n\n for (let i = 0; i < workingAccepts.length; i++) {\n const accept = workingAccepts[i];\n const scheme = findByNetworkAndScheme(\n this.registeredServerSchemes,\n accept.scheme,\n accept.network as Network,\n );\n if (!scheme?.enrichPaymentRequiredResponse) {\n continue;\n }\n\n const context: SchemePaymentRequiredContext = {\n requirements: workingAccepts,\n paymentPayload,\n resourceInfo,\n error,\n paymentRequiredResponse: response,\n transportContext,\n };\n const enrichedAccepts = await scheme.enrichPaymentRequiredResponse(context);\n if (enrichedAccepts !== undefined) {\n workingAccepts = enrichedAccepts;\n response.accepts = workingAccepts;\n }\n assertAcceptsAdditiveExtraAfterSchemeEnrich(\n baselineAccepts,\n response.accepts,\n accept.scheme,\n accept.network,\n );\n baselineAccepts = snapshotPaymentRequirementsList(response.accepts);\n }\n\n // Let declared extensions add data to PaymentRequired response\n if (extensions) {\n for (const [key, declaration] of Object.entries(extensions)) {\n const extension = this.registeredExtensions.get(key);\n if (extension?.enrichPaymentRequiredResponse) {\n try {\n const context: PaymentRequiredContext = {\n requirements: workingAccepts,\n resourceInfo,\n error,\n paymentRequiredResponse: response,\n transportContext,\n };\n const extensionData = await extension.enrichPaymentRequiredResponse(\n declaration,\n context,\n );\n if (extensionData !== undefined) {\n if (!response.extensions) {\n response.extensions = {};\n }\n response.extensions[key] = extensionData;\n }\n } catch (error) {\n this.warnExtensionHookFailure(key, \"enrichPaymentRequiredResponse\", error);\n }\n assertAcceptsAllowlistedAfterExtensionEnrich(baselineAccepts, workingAccepts, key);\n baselineAccepts = snapshotPaymentRequirementsList(workingAccepts);\n }\n }\n }\n\n return response;\n }\n\n /**\n * Verifies a payment against requirements, running manual and in-use extension hooks.\n *\n * @param paymentPayload - Signed payment payload from the client\n * @param requirements - Requirements matched to the payload\n * @param declaredExtensions - Optional per-extension declarations for the request\n * @param transportContext - Optional transport-specific context (e.g. HTTP, MCP)\n * @returns Facilitator verify outcome (optionally carrying a `skipHandler` directive),\n * or abort/recovery as driven by hooks\n */\n async verifyPayment(\n paymentPayload: PaymentPayload,\n requirements: PaymentRequirements,\n declaredExtensions?: Record<string, unknown>,\n transportContext?: unknown,\n ): Promise<ResourceVerifyRespone> {\n const resolvedDeclaredExtensions = declaredExtensions ?? {};\n const extensionKeysInUse = Object.keys(resolvedDeclaredExtensions);\n const matchedScheme = {\n network: requirements.network as Network,\n scheme: requirements.scheme,\n };\n\n const context: VerifyContext = {\n paymentPayload,\n requirements,\n declaredExtensions: resolvedDeclaredExtensions,\n transportContext,\n };\n\n for (const { label, hook } of this.getLabeledHooks(\n \"beforeVerify\",\n extensionKeysInUse,\n matchedScheme,\n )) {\n try {\n const result = await hook(context);\n if (result && \"abort\" in result && result.abort) {\n return {\n isValid: false,\n invalidReason: result.reason,\n invalidMessage: result.message,\n };\n }\n if (result && \"skip\" in result && result.skip) {\n return this.runAfterVerifyHooks(\n result.result,\n context,\n extensionKeysInUse,\n matchedScheme,\n );\n }\n } catch (error) {\n this.warnResourceServerHookFailure(\"beforeVerify\", label, error);\n }\n }\n\n try {\n // Find the facilitator that supports this payment type\n const facilitatorClient = this.getFacilitatorClient(\n paymentPayload.x402Version,\n requirements.network,\n requirements.scheme,\n );\n\n let verifyResult: VerifyResponse;\n\n if (!facilitatorClient) {\n // Fallback: try all facilitators if no specific support found\n let lastError: Error | undefined;\n\n for (const client of this.facilitatorClients) {\n try {\n verifyResult = await client.verify(paymentPayload, requirements);\n break;\n } catch (error) {\n lastError = error as Error;\n }\n }\n\n if (!verifyResult!) {\n throw (\n lastError ||\n new Error(\n `No facilitator supports ${requirements.scheme} on ${requirements.network} for v${paymentPayload.x402Version}`,\n )\n );\n }\n } else {\n // Use the specific facilitator that supports this payment\n verifyResult = await facilitatorClient.verify(paymentPayload, requirements);\n }\n\n return this.runAfterVerifyHooks(verifyResult, context, extensionKeysInUse, matchedScheme);\n } catch (error) {\n const failureContext: VerifyFailureContext = {\n ...context,\n error: error as Error,\n };\n\n for (const { label, hook } of this.getLabeledHooks(\n \"onVerifyFailure\",\n extensionKeysInUse,\n matchedScheme,\n )) {\n try {\n const result = await hook(failureContext);\n if (result && \"recovered\" in result && result.recovered) {\n return result.result;\n }\n } catch (error) {\n this.warnResourceServerHookFailure(\"onVerifyFailure\", label, error);\n }\n }\n\n throw error;\n }\n }\n\n /**\n * Create cancellation controls for a verified payment attempt.\n *\n * @param paymentPayload - Signed payment payload from the client\n * @param requirements - Requirements matched to the payload\n * @param declaredExtensions - Optional per-extension declarations for the request\n * @param transportContext - Optional transport-specific context\n * @returns Cancellation controls for the verified payment attempt\n */\n createPaymentCancellationDispatcher(\n paymentPayload: PaymentPayload,\n requirements: PaymentRequirements,\n declaredExtensions?: Record<string, unknown>,\n transportContext?: unknown,\n ): PaymentCancellationDispatcher {\n const resolvedDeclaredExtensions = declaredExtensions ?? {};\n let cancelPromise: Promise<void> | undefined;\n\n return {\n cancel: (options: VerifiedPaymentCancelOptions) => {\n if (!cancelPromise) {\n cancelPromise = this.dispatchVerifiedPaymentCanceled(\n paymentPayload,\n requirements,\n resolvedDeclaredExtensions,\n options,\n transportContext,\n );\n }\n return cancelPromise;\n },\n };\n }\n\n /**\n * Settle a verified payment\n *\n * @param paymentPayload - The payment payload to settle\n * @param requirements - The payment requirements\n * @param declaredExtensions - Optional declared extensions (for per-key enrichment)\n * @param transportContext - Optional transport-specific context (e.g., HTTP request/response, MCP tool context)\n * @param settlementOverrides - Optional overrides for settlement parameters (e.g., partial settlement amount)\n * @returns Settlement response\n */\n async settlePayment(\n paymentPayload: PaymentPayload,\n requirements: PaymentRequirements,\n declaredExtensions?: Record<string, unknown>,\n transportContext?: unknown,\n settlementOverrides?: SettlementOverrides,\n ): Promise<SettleResponse> {\n const resolvedDeclaredExtensions = declaredExtensions ?? {};\n const extensionKeysInUse = Object.keys(resolvedDeclaredExtensions);\n\n // Apply settlement overrides (e.g., partial settlement for upto scheme)\n let effectiveRequirements = requirements;\n if (settlementOverrides?.amount !== undefined) {\n const scheme = findByNetworkAndScheme(\n this.registeredServerSchemes,\n requirements.scheme,\n requirements.network as Network,\n );\n const decimals =\n scheme?.getAssetDecimals?.(requirements.asset ?? \"\", requirements.network as Network) ?? 6;\n effectiveRequirements = {\n ...requirements,\n amount: resolveSettlementOverrideAmount(settlementOverrides.amount, requirements, decimals),\n };\n }\n\n const context: SettleContext = {\n paymentPayload,\n requirements: effectiveRequirements,\n declaredExtensions: resolvedDeclaredExtensions,\n transportContext,\n };\n const matchedScheme = {\n network: effectiveRequirements.network as Network,\n scheme: effectiveRequirements.scheme,\n };\n\n for (const { label, hook } of this.getLabeledHooks(\n \"beforeSettle\",\n extensionKeysInUse,\n matchedScheme,\n )) {\n try {\n const result = await hook(context);\n if (result && \"abort\" in result && result.abort) {\n throw new SettleError(400, {\n success: false,\n errorReason: result.reason,\n errorMessage: result.message,\n transaction: \"\",\n network: requirements.network,\n });\n }\n if (result && \"skip\" in result && result.skip) {\n const settleResult = result.result;\n const skipResultContext: SettleResultContext = {\n ...context,\n result: settleResult,\n transportContext,\n };\n for (const { label, hook } of this.getLabeledHooks(\n \"afterSettle\",\n extensionKeysInUse,\n matchedScheme,\n )) {\n try {\n await hook(skipResultContext);\n } catch (error) {\n this.warnResourceServerHookFailure(\"afterSettle\", label, error);\n }\n }\n await this.enrichSettlementResponse(\n settleResult,\n skipResultContext,\n resolvedDeclaredExtensions,\n matchedScheme,\n );\n return settleResult;\n }\n } catch (error) {\n if (error instanceof SettleError) {\n throw error;\n }\n this.warnResourceServerHookFailure(\"beforeSettle\", label, error);\n }\n }\n\n try {\n const scheme = findByNetworkAndScheme(\n this.registeredServerSchemes,\n matchedScheme.scheme,\n matchedScheme.network,\n );\n const payloadEnrichmentHook = scheme?.enrichSettlementPayload;\n if (payloadEnrichmentHook) {\n const label = `scheme \"${matchedScheme.scheme}\" enrichSettlementPayload`;\n const enrichment = await payloadEnrichmentHook(context);\n if (enrichment !== undefined) {\n assertAdditivePayloadEnrichment(paymentPayload.payload, enrichment, label);\n paymentPayload.payload = { ...paymentPayload.payload, ...enrichment };\n }\n }\n\n // Find the facilitator that supports this payment type\n const facilitatorClient = this.getFacilitatorClient(\n paymentPayload.x402Version,\n effectiveRequirements.network,\n effectiveRequirements.scheme,\n );\n\n let settleResult: SettleResponse;\n\n if (!facilitatorClient) {\n // Fallback: try all facilitators if no specific support found\n let lastError: Error | undefined;\n\n for (const client of this.facilitatorClients) {\n try {\n settleResult = await client.settle(paymentPayload, effectiveRequirements);\n break;\n } catch (error) {\n lastError = error as Error;\n }\n }\n\n if (!settleResult!) {\n throw (\n lastError ||\n new Error(\n `No facilitator supports ${effectiveRequirements.scheme} on ${effectiveRequirements.network} for v${paymentPayload.x402Version}`,\n )\n );\n }\n } else {\n // Use the specific facilitator that supports this payment\n settleResult = await facilitatorClient.settle(paymentPayload, effectiveRequirements);\n }\n\n // Execute afterSettle hooks\n const resultContext: SettleResultContext = {\n ...context,\n result: settleResult,\n };\n\n for (const { label, hook } of this.getLabeledHooks(\n \"afterSettle\",\n extensionKeysInUse,\n matchedScheme,\n )) {\n try {\n await hook(resultContext);\n } catch (error) {\n this.warnResourceServerHookFailure(\"afterSettle\", label, error);\n }\n }\n\n await this.enrichSettlementResponse(\n settleResult,\n resultContext,\n resolvedDeclaredExtensions,\n matchedScheme,\n );\n\n return settleResult;\n } catch (error) {\n const failureContext: SettleFailureContext = {\n ...context,\n error: error as Error,\n };\n\n for (const { label, hook } of this.getLabeledHooks(\n \"onSettleFailure\",\n extensionKeysInUse,\n matchedScheme,\n )) {\n try {\n const result = await hook(failureContext);\n if (result && \"recovered\" in result && result.recovered) {\n return result.result;\n }\n } catch (error) {\n this.warnResourceServerHookFailure(\"onSettleFailure\", label, error);\n }\n }\n\n throw error;\n }\n }\n\n /**\n * Find matching payment requirements for a payment\n *\n * @param availableRequirements - Array of available payment requirements\n * @param paymentPayload - The payment payload\n * @returns Matching payment requirements or undefined\n */\n /**\n * Validates optional client extension echoes against server-advertised extension info.\n * When the client omits extensions entirely, validation passes.\n *\n * @param paymentRequired - Server payment required response used for matching\n * @param paymentPayload - Client payment payload\n * @returns Whether echoed extension info preserves server-advertised values\n */\n validateExtensions(\n paymentRequired: PaymentRequired,\n paymentPayload: PaymentPayload,\n ): ExtensionValidationResult {\n if (paymentPayload.x402Version !== 2) {\n return { valid: true };\n }\n\n const serverExtensions = paymentRequired.extensions;\n if (!serverExtensions || Object.keys(serverExtensions).length === 0) {\n return { valid: true };\n }\n\n const clientExtensions = paymentPayload.extensions;\n if (!clientExtensions || Object.keys(clientExtensions).length === 0) {\n return { valid: true };\n }\n\n for (const [key, echoedValue] of Object.entries(clientExtensions)) {\n if (!Object.prototype.hasOwnProperty.call(serverExtensions, key)) {\n continue;\n }\n\n const advertisedInfo = getExtensionInfo(serverExtensions[key]);\n const echoedInfo = getExtensionInfo(echoedValue);\n if (!extensionInfoMatchesAdvertised(advertisedInfo, echoedInfo)) {\n return {\n valid: false,\n invalidReason: \"extension_echo_mismatch\",\n extensionKey: key,\n };\n }\n }\n\n return { valid: true };\n }\n\n /**\n * Finds the server-advertised requirement that matches a client payment payload.\n *\n * @param availableRequirements - Payment requirements advertised for the resource.\n * @param paymentPayload - Signed payment payload from the client.\n * @returns The matching requirement, or undefined when none match.\n */\n findMatchingRequirements(\n availableRequirements: PaymentRequirements[],\n paymentPayload: PaymentPayload,\n ): PaymentRequirements | undefined {\n switch (paymentPayload.x402Version) {\n case 2:\n // For v2, all server-declared requirements must match.\n // The client may include additive scheme-specific metadata under `accepted.extra`.\n return availableRequirements.find(paymentRequirements =>\n paymentRequirementsMatchAccepted(paymentRequirements, paymentPayload.accepted),\n );\n case 1:\n // For v1, match by scheme and network\n return availableRequirements.find(\n req =>\n req.scheme === paymentPayload.accepted.scheme &&\n req.network === paymentPayload.accepted.network,\n );\n default:\n throw new Error(\n `Unsupported x402 version: ${(paymentPayload as PaymentPayload).x402Version}`,\n );\n }\n }\n\n /**\n * Logs a warning when a manual or extension adapter lifecycle hook throws.\n *\n * @param phase - Lifecycle phase name (e.g. `beforeVerify`)\n * @param label - Hook source label from {@link getLabeledHooks} (manual index or extension key)\n * @param error - Thrown value or rejection reason\n */\n private warnResourceServerHookFailure(phase: string, label: string, error: unknown): void {\n const detail = error instanceof Error ? error.message : String(error);\n console.warn(`[x402] Resource server ${phase} hook threw (${label}): ${detail}`);\n }\n\n /**\n * Logs a warning when a registered extension enrichment hook throws.\n *\n * @param extensionKey - Registered extension identifier\n * @param hookName - Hook method name (e.g. `enrichDeclaration`)\n * @param error - Thrown value or rejection reason\n */\n private warnExtensionHookFailure(extensionKey: string, hookName: string, error: unknown): void {\n const detail = error instanceof Error ? error.message : String(error);\n console.warn(`[x402] extension \"${extensionKey}\" ${hookName} threw: ${detail}`);\n }\n\n /**\n * Executes after-verify hooks for facilitator and hook-provided verify results.\n *\n * @param verifyResult - Verify response passed to after-verify hooks.\n * @param context - Verify context shared with before-verify hooks.\n * @param extensionKeysInUse - Declared extension keys for this request.\n * @param matchedScheme - Scheme/network selected for this payment.\n * @param matchedScheme.network - Matched payment network.\n * @param matchedScheme.scheme - Matched payment scheme.\n * @returns Verify response with any in-process skip handler directive.\n */\n private async runAfterVerifyHooks(\n verifyResult: VerifyResponse,\n context: VerifyContext,\n extensionKeysInUse: readonly string[],\n matchedScheme: { network: Network; scheme: string },\n ): Promise<ResourceVerifyRespone> {\n const resultContext: VerifyResultContext = {\n ...context,\n result: verifyResult,\n };\n\n let skipHandler: SkipHandlerDirective | undefined;\n for (const { label, hook } of this.getLabeledHooks(\n \"afterVerify\",\n extensionKeysInUse,\n matchedScheme,\n )) {\n try {\n const directive = await hook(resultContext);\n if (directive && \"skipHandler\" in directive && directive.skipHandler) {\n skipHandler = directive.response ?? {};\n }\n } catch (error) {\n this.warnResourceServerHookFailure(\"afterVerify\", label, error);\n }\n }\n\n return skipHandler ? { ...verifyResult, skipHandler } : verifyResult;\n }\n\n /**\n * Runs response enrichment after settlement lifecycle hooks complete.\n *\n * @param settleResult - Mutable settlement result being returned to the caller\n * @param context - Read-only hook context for enrichment callbacks\n * @param declaredExtensions - Extension declarations present on this payment\n * @param matchedScheme - Scheme/network selected for this settlement\n * @param matchedScheme.network - Matched payment network\n * @param matchedScheme.scheme - Matched payment scheme\n */\n private async enrichSettlementResponse(\n settleResult: SettleResponse,\n context: SettleResultContext,\n declaredExtensions: Record<string, unknown>,\n matchedScheme: { network: Network; scheme: string },\n ): Promise<void> {\n if (Object.keys(declaredExtensions).length > 0) {\n const settleCoreSnapshot = snapshotSettleResponseCore(settleResult);\n for (const [key, declaration] of Object.entries(declaredExtensions)) {\n const extension = this.registeredExtensions.get(key);\n if (!extension?.enrichSettlementResponse) continue;\n\n try {\n const extensionData = await extension.enrichSettlementResponse(declaration, context);\n if (extensionData !== undefined) {\n if (!settleResult.extensions) {\n settleResult.extensions = {};\n }\n settleResult.extensions[key] = extensionData;\n }\n } catch (error) {\n this.warnExtensionHookFailure(key, \"enrichSettlementResponse\", error);\n }\n assertSettleResponseCoreUnchanged(settleCoreSnapshot, settleResult, key);\n }\n }\n\n const scheme = findByNetworkAndScheme(\n this.registeredServerSchemes,\n matchedScheme.scheme,\n matchedScheme.network,\n );\n const hook = scheme?.enrichSettlementResponse;\n if (!hook) return;\n\n const label = `scheme \"${matchedScheme.scheme}\" enrichSettlementResponse`;\n try {\n const enrichment = await hook(context);\n if (enrichment === undefined) return;\n\n assertAdditiveSettlementExtra(settleResult.extra ?? {}, enrichment, label);\n settleResult.extra = mergeAdditiveSettlementExtra(settleResult.extra ?? {}, enrichment);\n } catch (error) {\n this.warnResourceServerHookFailure(\"enrichSettlementResponse\", label, error);\n }\n }\n\n /**\n * Notify hooks that verified work ended before settlement.\n *\n * @param paymentPayload - Signed payment payload from the client\n * @param requirements - Requirements matched to the payload\n * @param declaredExtensions - Optional per-extension declarations for the request\n * @param options - Cancellation reason and optional diagnostics\n * @param fallbackTransportContext - Optional transport-specific context\n */\n private async dispatchVerifiedPaymentCanceled(\n paymentPayload: PaymentPayload,\n requirements: PaymentRequirements,\n declaredExtensions: Record<string, unknown>,\n options: VerifiedPaymentCancelOptions,\n fallbackTransportContext?: unknown,\n ): Promise<void> {\n const extensionKeysInUse = Object.keys(declaredExtensions);\n const matchedScheme = {\n network: requirements.network as Network,\n scheme: requirements.scheme,\n };\n const context: VerifiedPaymentCanceledContext = {\n paymentPayload,\n requirements,\n declaredExtensions,\n transportContext: fallbackTransportContext,\n reason: options.reason,\n error: options.error,\n responseStatus: options.responseStatus,\n };\n\n for (const { label, hook } of this.getLabeledHooks(\n \"onVerifiedPaymentCanceled\",\n extensionKeysInUse,\n matchedScheme,\n )) {\n try {\n await hook(context);\n } catch (error) {\n this.warnResourceServerHookFailure(\"onVerifiedPaymentCanceled\", label, error);\n }\n }\n }\n\n /**\n * Manual hooks first, then the matched scheme adapter, then extension adapters for keys in use.\n * Each entry carries a stable label for logging when a hook throws.\n *\n * @param phase - Hook slot (e.g. `beforeVerify`)\n * @param extensionKeysInUse - Declared extension keys for this request\n * @param matchedScheme - Scheme/network selected for this payment\n * @param matchedScheme.network - Matched payment network\n * @param matchedScheme.scheme - Matched payment scheme\n * @returns Hooks in invocation order with source labels\n */\n private getLabeledHooks<P extends ResourceServerHookPhase>(\n phase: P,\n extensionKeysInUse: readonly string[],\n matchedScheme?: { network: Network; scheme: string },\n ): Array<{\n label: string;\n hook: NonNullable<ExtensionAdapterHandles[P]>;\n }> {\n type HookFn = NonNullable<ExtensionAdapterHandles[P]>;\n const manualKey = `${phase}Hooks` as ResourceServerManualHookArrayKey;\n const manual = (this as Record<ResourceServerManualHookArrayKey, HookFn[]>)[manualKey];\n\n const out: Array<{ label: string; hook: HookFn }> = [];\n manual.forEach((hook, index) => {\n out.push({ label: `manual ${phase} hook #${index}`, hook });\n });\n\n if (matchedScheme) {\n const schemeHandles = findByNetworkAndScheme(\n this.schemeHookAdapters,\n matchedScheme.scheme,\n matchedScheme.network,\n );\n const hook = schemeHandles?.[phase];\n if (hook !== undefined) {\n out.push({\n label: `scheme \"${matchedScheme.scheme}\" ${phase}`,\n hook,\n });\n }\n }\n\n const inUse = new Set(extensionKeysInUse);\n for (const [extensionKey, adapterHandles] of this.extensionHookAdapters.entries()) {\n if (!inUse.has(extensionKey)) continue;\n const hook = adapterHandles[phase];\n if (hook !== undefined) {\n out.push({ label: `extension \"${extensionKey}\" ${phase}`, hook });\n }\n }\n\n return out;\n }\n\n /**\n * Get facilitator client for a specific version, network, and scheme\n *\n * @param x402Version - The x402 version\n * @param network - The network identifier\n * @param scheme - The payment scheme\n * @returns The facilitator client or undefined if not found\n */\n private getFacilitatorClient(\n x402Version: number,\n network: Network,\n scheme: string,\n ): FacilitatorClient | undefined {\n const versionMap = this.facilitatorClientsMap.get(x402Version);\n if (!versionMap) return undefined;\n\n // Use findByNetworkAndScheme for pattern matching\n return findByNetworkAndScheme(versionMap, scheme, network);\n }\n}\n\n/**\n * Normalizes an extension declaration or echo to its comparable `info` payload.\n *\n * @param value - Extension value that may wrap its payload under `info`.\n * @returns The nested `info` value when present; otherwise `value` unchanged.\n */\nfunction getExtensionInfo(value: unknown): unknown {\n if (\n value !== null &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n Object.prototype.hasOwnProperty.call(value, \"info\")\n ) {\n return (value as Record<string, unknown>).info;\n }\n return value;\n}\n\n/**\n * Returns whether a client-echoed extension payload preserves the server advertisement.\n *\n * @param advertised - Extension info advertised by the server.\n * @param echoed - Extension info echoed back by the client.\n * @returns True when `echoed` contains every field from `advertised`.\n */\nfunction extensionInfoMatchesAdvertised(advertised: unknown, echoed: unknown): boolean {\n return objectContainsSubset(advertised, echoed);\n}\n\n/**\n * Returns whether a client-selected requirement satisfies a server-advertised requirement.\n *\n * Core payment terms and all server-declared `extra` fields must match exactly,\n * but clients may include additive scheme-specific metadata under `accepted.extra`.\n *\n * @param required - Server-advertised payment requirement.\n * @param accepted - Client-selected payment requirement from the payment payload.\n * @returns True when `accepted` preserves every server-declared requirement.\n */\nfunction paymentRequirementsMatchAccepted(\n required: PaymentRequirements,\n accepted: PaymentRequirements,\n): boolean {\n const { extra: requiredExtra, ...requiredCore } = required;\n const { extra: acceptedExtra, ...acceptedCore } = accepted;\n\n if (!deepEqual(requiredCore, acceptedCore)) {\n return false;\n }\n\n if (requiredExtra === undefined) {\n return true;\n }\n\n return objectContainsSubset(requiredExtra, acceptedExtra);\n}\n\n/**\n * Recursively checks that `actual` contains every field and value from `expected`.\n * Object values may contain additional fields; arrays and primitives must match exactly.\n *\n * @param expected - Required subset.\n * @param actual - Candidate object.\n * @returns True when `actual` contains `expected`.\n */\nfunction objectContainsSubset(expected: unknown, actual: unknown): boolean {\n if (expected === null || typeof expected !== \"object\" || Array.isArray(expected)) {\n return deepEqual(expected, actual);\n }\n\n if (actual === null || typeof actual !== \"object\" || Array.isArray(actual)) {\n return false;\n }\n\n const actualRecord = actual as Record<string, unknown>;\n return Object.entries(expected as Record<string, unknown>).every(([key, value]) => {\n const hasActualKey = Object.prototype.hasOwnProperty.call(actualRecord, key);\n if (!hasActualKey) {\n return value === undefined;\n }\n return objectContainsSubset(value, actualRecord[key]);\n });\n}\n\nexport default x402ResourceServer;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAUO,SAAS,oBAAoB,OAAwB;AAC1D,SAAO,MAAM,KAAK,MAAM;AAC1B;AAQO,SAAS,gCACd,cACuB;AACvB,SAAO,aAAa,IAAI,UAAQ;AAAA,IAC9B,GAAG;AAAA,IACH,OAAO,gBAAgB,IAAI,KAAK;AAAA,EAClC,EAAE;AACJ;AAcO,SAAS,6CACd,UACA,SACA,cACM;AACN,MAAI,SAAS,WAAW,QAAQ,QAAQ;AACtC,UAAM,IAAI;AAAA,MACR,qBAAqB,YAAY,+DAA+D,SAAS,MAAM,WAAM,QAAQ,MAAM;AAAA,IACrI;AAAA,EACF;AAEA,WAAS,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;AACxC,UAAM,IAAI,SAAS,CAAC;AACpB,UAAM,IAAI,QAAQ,CAAC;AAEnB,QAAI,EAAE,WAAW,EAAE,UAAU,EAAE,YAAY,EAAE,SAAS;AACpD,YAAM,IAAI;AAAA,QACR,qBAAqB,YAAY,2EAA2E,CAAC;AAAA,MAC/G;AAAA,IACF;AACA,QAAI,EAAE,sBAAsB,EAAE,mBAAmB;AAC/C,YAAM,IAAI;AAAA,QACR,qBAAqB,YAAY,6EAA6E,CAAC;AAAA,MACjH;AAAA,IACF;AAEA,eAAW,SAAS,CAAC,SAAS,UAAU,OAAO,GAAY;AACzD,YAAM,KAAK,EAAE,KAAK;AAClB,YAAM,KAAK,EAAE,KAAK;AAClB,UAAI,CAAC,oBAAoB,EAAE,KAAK,OAAO,IAAI;AACzC,cAAM,IAAI;AAAA,UACR,qBAAqB,YAAY,wCAAwC,KAAK,mGAAmG,CAAC;AAAA,QACpL;AAAA,MACF;AAAA,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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { aC as AssetAmount, aV as DeepReadonly, aS as FacilitatorContext, F as FacilitatorExtension, A as FacilitatorResponseError, u as HTTPResourceServerExtensionHooks, aB as Money, aP as MoneyParser, N as Network, P as PaymentPayload, aR as PaymentPayloadContext, aQ as PaymentPayloadResult, aw as PaymentPayloadV1, c as PaymentRequired, I as PaymentRequiredContext, av as PaymentRequiredV1, a as PaymentRequirements, au as PaymentRequirementsV1, aD as Price, aK as ResourceInfo, aT as ResourceServerExtension, aU as ResourceServerExtensionHooks, v as ResourceServerTransportExtensionHooks, aM as SchemeClientHooks, a8 as SchemeEnrichPaymentRequiredResponseHook, aL as SchemeNetworkClient, b as SchemeNetworkFacilitator, aN as SchemeNetworkServer, a9 as SchemePaymentRequiredContext, aO as SchemeServerHooks, M as SettleContext, aJ as SettleError, Q as SettleFailureContext, aF as SettleRequest, S as SettleResponse, O as SettleResultContext, aH as SupportedKind, aG as SupportedResponse, T as VerifiedPaymentCanceledContext, J as VerifyContext, aI as VerifyError, L as VerifyFailureContext, aE as VerifyRequest, V as VerifyResponse, K as VerifyResultContext, B as getFacilitatorResponseError } from '../x402Client-TQHctrG7.mjs';
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import {
|
|
2
|
+
FacilitatorResponseError,
|
|
3
|
+
SettleError,
|
|
4
|
+
VerifyError,
|
|
5
|
+
getFacilitatorResponseError
|
|
6
|
+
} from "../chunk-AGOUMC4P.mjs";
|
|
7
|
+
import "../chunk-BJTO5JO5.mjs";
|
|
8
|
+
export {
|
|
9
|
+
FacilitatorResponseError,
|
|
10
|
+
SettleError,
|
|
11
|
+
VerifyError,
|
|
12
|
+
getFacilitatorResponseError
|
|
13
|
+
};
|
|
14
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { aw as PaymentPayloadV1, av as PaymentRequiredV1, au as PaymentRequirementsV1, ay as SettleRequestV1, az as SettleResponseV1, aA as SupportedResponseV1, ax as VerifyRequestV1 } from '../../x402Client-TQHctrG7.mjs';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { N as Network } from '../x402Client-TQHctrG7.mjs';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Converts a JavaScript number to a plain decimal string, expanding scientific notation
|
|
5
|
+
* via string manipulation rather than parseFloat round-tripping.
|
|
6
|
+
*
|
|
7
|
+
* e.g. 1e-7 → "0.0000001", 4.02 → "4.02"
|
|
8
|
+
*
|
|
9
|
+
* @param n - The number to convert
|
|
10
|
+
* @returns A plain decimal string representation with no scientific notation
|
|
11
|
+
*/
|
|
12
|
+
declare function numberToDecimalString(n: number): string;
|
|
13
|
+
/**
|
|
14
|
+
* Parses a money string into a finite, non-negative decimal number.
|
|
15
|
+
* Accepts plain decimal strings with an optional leading dollar sign.
|
|
16
|
+
*
|
|
17
|
+
* @param money - The money string to parse
|
|
18
|
+
* @returns Decimal number
|
|
19
|
+
*/
|
|
20
|
+
declare function parseMoneyString(money: string): number;
|
|
21
|
+
/**
|
|
22
|
+
* Convert a decimal amount to token smallest units.
|
|
23
|
+
* Accepts only plain decimal strings — scientific notation is not allowed.
|
|
24
|
+
* Throws if the amount is non-zero but too small to represent with the given decimal precision.
|
|
25
|
+
*
|
|
26
|
+
* @param decimalAmount - The decimal amount as a plain string (e.g., "0.10")
|
|
27
|
+
* @param decimals - The number of decimals for the token (e.g., 6 for USDC)
|
|
28
|
+
* @returns The amount in smallest units as a string
|
|
29
|
+
*/
|
|
30
|
+
declare function convertToTokenAmount(decimalAmount: string, decimals: number): string;
|
|
31
|
+
/**
|
|
32
|
+
* Scheme data structure for facilitator storage
|
|
33
|
+
*/
|
|
34
|
+
interface SchemeData<T> {
|
|
35
|
+
facilitator: T;
|
|
36
|
+
networks: Set<Network>;
|
|
37
|
+
pattern: Network;
|
|
38
|
+
}
|
|
39
|
+
declare const networkMatchesPattern: (pattern: Network, network: Network) => boolean;
|
|
40
|
+
declare const findSchemesByNetwork: <T>(map: Map<string, Map<string, T>>, network: Network) => Map<string, T> | undefined;
|
|
41
|
+
declare const findByNetworkAndScheme: <T>(map: Map<string, Map<string, T>>, scheme: string, network: Network) => T | undefined;
|
|
42
|
+
/**
|
|
43
|
+
* Finds a facilitator by scheme and network using pattern matching.
|
|
44
|
+
* Works with new SchemeData storage structure.
|
|
45
|
+
*
|
|
46
|
+
* @param schemeMap - Map of scheme names to SchemeData
|
|
47
|
+
* @param scheme - The scheme to find
|
|
48
|
+
* @param network - The network to match against
|
|
49
|
+
* @returns The facilitator if found, undefined otherwise
|
|
50
|
+
*/
|
|
51
|
+
declare const findFacilitatorBySchemeAndNetwork: <T>(schemeMap: Map<string, SchemeData<T>>, scheme: string, network: Network) => T | undefined;
|
|
52
|
+
declare const Base64EncodedRegex: RegExp;
|
|
53
|
+
/**
|
|
54
|
+
* Encodes a string to base64 format
|
|
55
|
+
*
|
|
56
|
+
* @param data - The string to be encoded to base64
|
|
57
|
+
* @returns The base64 encoded string
|
|
58
|
+
*/
|
|
59
|
+
declare function safeBase64Encode(data: string): string;
|
|
60
|
+
/**
|
|
61
|
+
* Decodes a base64 string back to its original format
|
|
62
|
+
*
|
|
63
|
+
* @param data - The base64 encoded string to be decoded
|
|
64
|
+
* @returns The decoded string in UTF-8 format
|
|
65
|
+
*/
|
|
66
|
+
declare function safeBase64Decode(data: string): string;
|
|
67
|
+
/**
|
|
68
|
+
* Deep equality comparison for payment requirements
|
|
69
|
+
* Uses a normalized JSON.stringify for consistent comparison
|
|
70
|
+
*
|
|
71
|
+
* @param obj1 - First object to compare
|
|
72
|
+
* @param obj2 - Second object to compare
|
|
73
|
+
* @returns True if objects are deeply equal
|
|
74
|
+
*/
|
|
75
|
+
declare function deepEqual(obj1: unknown, obj2: unknown): boolean;
|
|
76
|
+
|
|
77
|
+
export { Base64EncodedRegex, type SchemeData, convertToTokenAmount, deepEqual, findByNetworkAndScheme, findFacilitatorBySchemeAndNetwork, findSchemesByNetwork, networkMatchesPattern, numberToDecimalString, parseMoneyString, safeBase64Decode, safeBase64Encode };
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import {
|
|
2
|
+
Base64EncodedRegex,
|
|
3
|
+
convertToTokenAmount,
|
|
4
|
+
deepEqual,
|
|
5
|
+
findByNetworkAndScheme,
|
|
6
|
+
findFacilitatorBySchemeAndNetwork,
|
|
7
|
+
findSchemesByNetwork,
|
|
8
|
+
networkMatchesPattern,
|
|
9
|
+
numberToDecimalString,
|
|
10
|
+
parseMoneyString,
|
|
11
|
+
safeBase64Decode,
|
|
12
|
+
safeBase64Encode
|
|
13
|
+
} from "../chunk-ABS7D6VX.mjs";
|
|
14
|
+
import "../chunk-BJTO5JO5.mjs";
|
|
15
|
+
export {
|
|
16
|
+
Base64EncodedRegex,
|
|
17
|
+
convertToTokenAmount,
|
|
18
|
+
deepEqual,
|
|
19
|
+
findByNetworkAndScheme,
|
|
20
|
+
findFacilitatorBySchemeAndNetwork,
|
|
21
|
+
findSchemesByNetwork,
|
|
22
|
+
networkMatchesPattern,
|
|
23
|
+
numberToDecimalString,
|
|
24
|
+
parseMoneyString,
|
|
25
|
+
safeBase64Decode,
|
|
26
|
+
safeBase64Encode
|
|
27
|
+
};
|
|
28
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|