@agent-score/commerce 2.0.2 → 2.1.1
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 +26 -11
- package/dist/_core-kI7FRAiZ.d.mts +10 -0
- package/dist/_core-kI7FRAiZ.d.ts +10 -0
- package/dist/challenge/index.d.mts +3 -3
- package/dist/challenge/index.d.ts +3 -3
- package/dist/challenge/index.js +21 -14
- package/dist/challenge/index.js.map +1 -1
- package/dist/challenge/index.mjs +21 -14
- package/dist/challenge/index.mjs.map +1 -1
- package/dist/{checkout-jNUIql6D.d.mts → checkout-BRw_caGr.d.mts} +13 -33
- package/dist/{checkout-DhSj_h94.d.ts → checkout-CuSNUJFX.d.ts} +13 -33
- package/dist/core.js +1 -1
- package/dist/core.js.map +1 -1
- package/dist/core.mjs +1 -1
- package/dist/core.mjs.map +1 -1
- package/dist/default_rails-C5gKZJMI.d.ts +198 -0
- package/dist/default_rails-XFCuRddA.d.mts +198 -0
- package/dist/discovery/index.d.mts +5 -5
- package/dist/discovery/index.d.ts +5 -5
- package/dist/discovery/index.js +14 -1
- package/dist/discovery/index.js.map +1 -1
- package/dist/discovery/index.mjs +14 -1
- package/dist/discovery/index.mjs.map +1 -1
- package/dist/identity/express.d.mts +7 -3
- package/dist/identity/express.d.ts +7 -3
- package/dist/identity/express.js +39 -96
- package/dist/identity/express.js.map +1 -1
- package/dist/identity/express.mjs +37 -87
- package/dist/identity/express.mjs.map +1 -1
- package/dist/identity/fastify.d.mts +4 -4
- package/dist/identity/fastify.d.ts +4 -4
- package/dist/identity/fastify.js +60 -96
- package/dist/identity/fastify.js.map +1 -1
- package/dist/identity/fastify.mjs +58 -87
- package/dist/identity/fastify.mjs.map +1 -1
- package/dist/identity/hono.d.mts +11 -3
- package/dist/identity/hono.d.ts +11 -3
- package/dist/identity/hono.js +39 -93
- package/dist/identity/hono.js.map +1 -1
- package/dist/identity/hono.mjs +37 -84
- package/dist/identity/hono.mjs.map +1 -1
- package/dist/identity/nextjs.d.mts +10 -3
- package/dist/identity/nextjs.d.ts +10 -3
- package/dist/identity/nextjs.js +49 -93
- package/dist/identity/nextjs.js.map +1 -1
- package/dist/identity/nextjs.mjs +46 -84
- package/dist/identity/nextjs.mjs.map +1 -1
- package/dist/identity/policy.js +22 -23317
- package/dist/identity/policy.js.map +1 -1
- package/dist/identity/policy.mjs +1 -23320
- package/dist/identity/policy.mjs.map +1 -1
- package/dist/identity/web.d.mts +9 -3
- package/dist/identity/web.d.ts +9 -3
- package/dist/identity/web.js +45 -93
- package/dist/identity/web.js.map +1 -1
- package/dist/identity/web.mjs +42 -84
- package/dist/identity/web.mjs.map +1 -1
- package/dist/index.d.mts +621 -90
- package/dist/index.d.ts +621 -90
- package/dist/index.js +1202 -328
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1188 -327
- package/dist/index.mjs.map +1 -1
- package/dist/middleware/express.d.mts +10 -0
- package/dist/middleware/express.d.ts +10 -0
- package/dist/middleware/express.js +128 -0
- package/dist/middleware/express.js.map +1 -0
- package/dist/middleware/express.mjs +91 -0
- package/dist/middleware/express.mjs.map +1 -0
- package/dist/middleware/fastify.d.mts +10 -0
- package/dist/middleware/fastify.d.ts +10 -0
- package/dist/middleware/fastify.js +127 -0
- package/dist/middleware/fastify.js.map +1 -0
- package/dist/middleware/fastify.mjs +90 -0
- package/dist/middleware/fastify.mjs.map +1 -0
- package/dist/middleware/hono.d.mts +10 -0
- package/dist/middleware/hono.d.ts +10 -0
- package/dist/middleware/hono.js +122 -0
- package/dist/middleware/hono.js.map +1 -0
- package/dist/middleware/hono.mjs +85 -0
- package/dist/middleware/hono.mjs.map +1 -0
- package/dist/middleware/nextjs.d.mts +22 -0
- package/dist/middleware/nextjs.d.ts +22 -0
- package/dist/middleware/nextjs.js +143 -0
- package/dist/middleware/nextjs.js.map +1 -0
- package/dist/middleware/nextjs.mjs +105 -0
- package/dist/middleware/nextjs.mjs.map +1 -0
- package/dist/middleware/web.d.mts +25 -0
- package/dist/middleware/web.d.ts +25 -0
- package/dist/middleware/web.js +128 -0
- package/dist/middleware/web.js.map +1 -0
- package/dist/middleware/web.mjs +91 -0
- package/dist/middleware/web.mjs.map +1 -0
- package/dist/payment/index.d.mts +32 -21
- package/dist/payment/index.d.ts +32 -21
- package/dist/payment/index.js +215 -12
- package/dist/payment/index.js.map +1 -1
- package/dist/payment/index.mjs +205 -12
- package/dist/payment/index.mjs.map +1 -1
- package/dist/{pricing-CxzwyiO6.d.mts → pricing-4n5Ota0D.d.mts} +14 -4
- package/dist/{pricing-CQ9DIFaw.d.ts → pricing-DHfH3ogG.d.ts} +14 -4
- package/dist/{rail_spec-XP0wKgJV.d.mts → rail_spec-D6qzh3J0.d.mts} +1 -1
- package/dist/{rail_spec-XP0wKgJV.d.ts → rail_spec-D6qzh3J0.d.ts} +1 -1
- package/dist/stripe-multichain/index.d.mts +150 -47
- package/dist/stripe-multichain/index.d.ts +150 -47
- package/dist/stripe-multichain/index.js +19799 -43
- package/dist/stripe-multichain/index.js.map +1 -1
- package/dist/stripe-multichain/index.mjs +19808 -28
- package/dist/stripe-multichain/index.mjs.map +1 -1
- package/dist/{x402_server-hgQzWQwB.d.mts → x402_server-Ciz2mls2.d.mts} +1 -1
- package/dist/{x402_server-hgQzWQwB.d.ts → x402_server-Ciz2mls2.d.ts} +1 -1
- package/package.json +43 -5
- package/dist/_response-BFYN3b6i.d.mts +0 -142
- package/dist/_response-_iPD5AIj.d.ts +0 -142
- package/dist/solana-Cds87OTu.d.mts +0 -67
- package/dist/solana-Cds87OTu.d.ts +0 -67
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/middleware/web.ts
|
|
31
|
+
var web_exports = {};
|
|
32
|
+
__export(web_exports, {
|
|
33
|
+
createRateLimit: () => createRateLimit
|
|
34
|
+
});
|
|
35
|
+
module.exports = __toCommonJS(web_exports);
|
|
36
|
+
|
|
37
|
+
// src/_redis.ts
|
|
38
|
+
async function tryCreateRedis(opts) {
|
|
39
|
+
const url = opts.url ?? process.env.REDIS_URL;
|
|
40
|
+
if (!url) return null;
|
|
41
|
+
try {
|
|
42
|
+
const mod = await import("ioredis");
|
|
43
|
+
const client = new mod.default(url, {
|
|
44
|
+
connectTimeout: opts.connectTimeout ?? 3e3,
|
|
45
|
+
maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,
|
|
46
|
+
tls: url.startsWith("rediss://") ? {} : void 0
|
|
47
|
+
});
|
|
48
|
+
client.on("error", (err) => console.error(`[${opts.label}] Redis error:`, err.message));
|
|
49
|
+
return client;
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function memoizedRedis(opts) {
|
|
55
|
+
let promise = null;
|
|
56
|
+
return () => {
|
|
57
|
+
if (!promise) promise = tryCreateRedis(opts);
|
|
58
|
+
return promise;
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// src/middleware/_core.ts
|
|
63
|
+
function createRateLimiter(opts = {}) {
|
|
64
|
+
const windowSeconds = opts.windowSeconds ?? 60;
|
|
65
|
+
const maxRequests = opts.maxRequests ?? 60;
|
|
66
|
+
const keyPrefix = opts.keyPrefix ?? "rl:";
|
|
67
|
+
const memMap = /* @__PURE__ */ new Map();
|
|
68
|
+
const getRedis = memoizedRedis({ url: opts.redisUrl, label: "rate-limit" });
|
|
69
|
+
const checkMem = (key) => {
|
|
70
|
+
const now = Date.now();
|
|
71
|
+
const entry = memMap.get(key);
|
|
72
|
+
if (!entry || entry.resetAt < now) {
|
|
73
|
+
memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1e3 });
|
|
74
|
+
return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };
|
|
75
|
+
}
|
|
76
|
+
entry.count++;
|
|
77
|
+
const remaining = Math.max(0, maxRequests - entry.count);
|
|
78
|
+
return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };
|
|
79
|
+
};
|
|
80
|
+
return {
|
|
81
|
+
async check(key) {
|
|
82
|
+
const r = await getRedis();
|
|
83
|
+
if (!r) return checkMem(key);
|
|
84
|
+
try {
|
|
85
|
+
const fullKey = `${keyPrefix}${key}`;
|
|
86
|
+
const count = await r.incr(fullKey);
|
|
87
|
+
if (count === 1) await r.expire(fullKey, windowSeconds);
|
|
88
|
+
const remaining = Math.max(0, maxRequests - count);
|
|
89
|
+
return { allowed: count <= maxRequests, remaining, limit: maxRequests };
|
|
90
|
+
} catch {
|
|
91
|
+
return checkMem(key);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
var RATE_LIMIT_JSON_BODY = {
|
|
97
|
+
error: { code: "rate_limited", message: "Too many requests" }
|
|
98
|
+
};
|
|
99
|
+
function defaultKeyFromForwardedFor(forwardedFor) {
|
|
100
|
+
if (!forwardedFor) return "unknown";
|
|
101
|
+
return forwardedFor.split(",")[0]?.trim() || "unknown";
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// src/middleware/web.ts
|
|
105
|
+
function createRateLimit(opts = {}) {
|
|
106
|
+
const limiter = createRateLimiter(opts);
|
|
107
|
+
const keyResolver = opts.keyResolver ?? ((req) => defaultKeyFromForwardedFor(req.headers.get("x-forwarded-for")));
|
|
108
|
+
return async (req) => {
|
|
109
|
+
const { allowed, remaining, limit } = await limiter.check(keyResolver(req));
|
|
110
|
+
const baseHeaders = {
|
|
111
|
+
"X-RateLimit-Limit": String(limit),
|
|
112
|
+
"X-RateLimit-Remaining": String(remaining)
|
|
113
|
+
};
|
|
114
|
+
if (!allowed) {
|
|
115
|
+
const response = new Response(JSON.stringify(RATE_LIMIT_JSON_BODY), {
|
|
116
|
+
status: 429,
|
|
117
|
+
headers: { ...baseHeaders, "Content-Type": "application/json", "Cache-Control": "no-store" }
|
|
118
|
+
});
|
|
119
|
+
return { allowed: false, remaining, limit, response };
|
|
120
|
+
}
|
|
121
|
+
return { allowed: true, remaining, limit };
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
125
|
+
0 && (module.exports = {
|
|
126
|
+
createRateLimit
|
|
127
|
+
});
|
|
128
|
+
//# sourceMappingURL=web.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/middleware/web.ts","../../src/_redis.ts","../../src/middleware/_core.ts"],"sourcesContent":["import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\n\nexport interface RateLimitWebOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `'unknown'`. */\n keyResolver?: (req: Request) => string;\n}\n\nexport type RateLimitGuardResult =\n | { allowed: true; remaining: number; limit: number; response?: undefined }\n | { allowed: false; remaining: number; limit: number; response: Response };\n\nexport type RateLimitGuard = (req: Request) => Promise<RateLimitGuardResult>;\n\n/**\n * Build a rate-limit guard for Web Fetch–style handlers. Call `guard(req)` at the top\n * of your route. When `allowed === false`, return `result.response` directly.\n */\nexport function createRateLimit(opts: RateLimitWebOptions = {}): RateLimitGuard {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ?? ((req: Request) => defaultKeyFromForwardedFor(req.headers.get('x-forwarded-for')));\n\n return async (req: Request) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n const baseHeaders = {\n 'X-RateLimit-Limit': String(limit),\n 'X-RateLimit-Remaining': String(remaining),\n };\n if (!allowed) {\n const response = new Response(JSON.stringify(RATE_LIMIT_JSON_BODY), {\n status: 429,\n headers: { ...baseHeaders, 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },\n });\n return { allowed: false, remaining, limit, response };\n }\n return { allowed: true, remaining, limit };\n };\n}\n","/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\ninterface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n"],"mappings":"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","names":[]}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// src/_redis.ts
|
|
2
|
+
async function tryCreateRedis(opts) {
|
|
3
|
+
const url = opts.url ?? process.env.REDIS_URL;
|
|
4
|
+
if (!url) return null;
|
|
5
|
+
try {
|
|
6
|
+
const mod = await import("ioredis");
|
|
7
|
+
const client = new mod.default(url, {
|
|
8
|
+
connectTimeout: opts.connectTimeout ?? 3e3,
|
|
9
|
+
maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,
|
|
10
|
+
tls: url.startsWith("rediss://") ? {} : void 0
|
|
11
|
+
});
|
|
12
|
+
client.on("error", (err) => console.error(`[${opts.label}] Redis error:`, err.message));
|
|
13
|
+
return client;
|
|
14
|
+
} catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function memoizedRedis(opts) {
|
|
19
|
+
let promise = null;
|
|
20
|
+
return () => {
|
|
21
|
+
if (!promise) promise = tryCreateRedis(opts);
|
|
22
|
+
return promise;
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// src/middleware/_core.ts
|
|
27
|
+
function createRateLimiter(opts = {}) {
|
|
28
|
+
const windowSeconds = opts.windowSeconds ?? 60;
|
|
29
|
+
const maxRequests = opts.maxRequests ?? 60;
|
|
30
|
+
const keyPrefix = opts.keyPrefix ?? "rl:";
|
|
31
|
+
const memMap = /* @__PURE__ */ new Map();
|
|
32
|
+
const getRedis = memoizedRedis({ url: opts.redisUrl, label: "rate-limit" });
|
|
33
|
+
const checkMem = (key) => {
|
|
34
|
+
const now = Date.now();
|
|
35
|
+
const entry = memMap.get(key);
|
|
36
|
+
if (!entry || entry.resetAt < now) {
|
|
37
|
+
memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1e3 });
|
|
38
|
+
return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };
|
|
39
|
+
}
|
|
40
|
+
entry.count++;
|
|
41
|
+
const remaining = Math.max(0, maxRequests - entry.count);
|
|
42
|
+
return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };
|
|
43
|
+
};
|
|
44
|
+
return {
|
|
45
|
+
async check(key) {
|
|
46
|
+
const r = await getRedis();
|
|
47
|
+
if (!r) return checkMem(key);
|
|
48
|
+
try {
|
|
49
|
+
const fullKey = `${keyPrefix}${key}`;
|
|
50
|
+
const count = await r.incr(fullKey);
|
|
51
|
+
if (count === 1) await r.expire(fullKey, windowSeconds);
|
|
52
|
+
const remaining = Math.max(0, maxRequests - count);
|
|
53
|
+
return { allowed: count <= maxRequests, remaining, limit: maxRequests };
|
|
54
|
+
} catch {
|
|
55
|
+
return checkMem(key);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
var RATE_LIMIT_JSON_BODY = {
|
|
61
|
+
error: { code: "rate_limited", message: "Too many requests" }
|
|
62
|
+
};
|
|
63
|
+
function defaultKeyFromForwardedFor(forwardedFor) {
|
|
64
|
+
if (!forwardedFor) return "unknown";
|
|
65
|
+
return forwardedFor.split(",")[0]?.trim() || "unknown";
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// src/middleware/web.ts
|
|
69
|
+
function createRateLimit(opts = {}) {
|
|
70
|
+
const limiter = createRateLimiter(opts);
|
|
71
|
+
const keyResolver = opts.keyResolver ?? ((req) => defaultKeyFromForwardedFor(req.headers.get("x-forwarded-for")));
|
|
72
|
+
return async (req) => {
|
|
73
|
+
const { allowed, remaining, limit } = await limiter.check(keyResolver(req));
|
|
74
|
+
const baseHeaders = {
|
|
75
|
+
"X-RateLimit-Limit": String(limit),
|
|
76
|
+
"X-RateLimit-Remaining": String(remaining)
|
|
77
|
+
};
|
|
78
|
+
if (!allowed) {
|
|
79
|
+
const response = new Response(JSON.stringify(RATE_LIMIT_JSON_BODY), {
|
|
80
|
+
status: 429,
|
|
81
|
+
headers: { ...baseHeaders, "Content-Type": "application/json", "Cache-Control": "no-store" }
|
|
82
|
+
});
|
|
83
|
+
return { allowed: false, remaining, limit, response };
|
|
84
|
+
}
|
|
85
|
+
return { allowed: true, remaining, limit };
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
export {
|
|
89
|
+
createRateLimit
|
|
90
|
+
};
|
|
91
|
+
//# sourceMappingURL=web.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/_redis.ts","../../src/middleware/_core.ts","../../src/middleware/web.ts"],"sourcesContent":["/** Shared lazy `ioredis` factory. Used by `quote_cache`, `middleware/_core`,\n * and `stripe-multichain/pi-cache` so they don't drift on connect-timeout,\n * TLS handling, or error-logging posture.\n *\n * `ioredis` is an optional peer dep — callers pass `redisUrl` (or rely on\n * `process.env.REDIS_URL`); when unset or the lazy import fails, this returns\n * null and the caller falls back to its in-process `Map`.\n *\n * Not part of the public API.\n */\n\n/** Minimal Redis surface — each caller intersects with its own usage\n * (incr/expire for rate-limit, get/set/del for caches). Returning `unknown`\n * on commands keeps the shape narrow; cast at the call site. */\nexport interface MinimalRedis {\n on(event: 'error', handler: (err: Error) => void): unknown;\n}\n\nexport interface CreateRedisOptions {\n /** Override `process.env.REDIS_URL` for tests. */\n url?: string;\n /** Logging label, e.g. `'quote-cache'` / `'rate-limit'` / `'pi-cache'`. */\n label: string;\n /** Connect timeout in ms. Default `3000`. */\n connectTimeout?: number;\n /** Per-request retry cap. Default `1`. */\n maxRetriesPerRequest?: number;\n}\n\n/** Lazy-import ioredis and construct a client. Returns null when:\n * - no URL is configured (caller falls back to in-memory)\n * - `ioredis` isn't installed (optional peer; caller falls back to in-memory)\n * - the import throws for any other reason\n *\n * `rediss://` URLs auto-enable TLS. The error handler logs with the caller's\n * label so multi-cache deployments can tell which subsystem complained. */\nasync function tryCreateRedis<T extends MinimalRedis>(opts: CreateRedisOptions): Promise<T | null> {\n const url = opts.url ?? process.env.REDIS_URL;\n if (!url) return null;\n try {\n const mod = (await import('ioredis')) as unknown as { default: new (url: string, opts?: unknown) => T };\n const client = new mod.default(url, {\n connectTimeout: opts.connectTimeout ?? 3000,\n maxRetriesPerRequest: opts.maxRetriesPerRequest ?? 1,\n tls: url.startsWith('rediss://') ? {} : undefined,\n });\n client.on('error', (err) => console.error(`[${opts.label}] Redis error:`, err.message));\n return client;\n } catch {\n return null;\n }\n}\n\n/** Memoized-promise variant: call once per caller; subsequent calls return the\n * same promise. Pairs with the pattern `let p: Promise<T|null> | null = null;\n * const getRedis = () => (p ??= tryCreateRedis(...))` in callers that want\n * per-call promise caching without managing the closure themselves. */\nexport function memoizedRedis<T extends MinimalRedis>(opts: CreateRedisOptions): () => Promise<T | null> {\n let promise: Promise<T | null> | null = null;\n return () => {\n if (!promise) promise = tryCreateRedis<T>(opts);\n return promise;\n };\n}\n","import { memoizedRedis, type MinimalRedis } from '../_redis';\n\nexport interface RateLimitCoreOptions {\n windowSeconds?: number;\n maxRequests?: number;\n /** Redis connection URL. Default: `process.env.REDIS_URL`. Falls back to in-memory when unset or the lazy `ioredis` import fails. */\n redisUrl?: string;\n /** Per-instance key prefix so multiple limiters sharing a Redis don't collide. */\n keyPrefix?: string;\n}\n\ninterface RateLimitDecision {\n allowed: boolean;\n remaining: number;\n limit: number;\n}\n\nexport interface RateLimiter {\n check(key: string): Promise<RateLimitDecision>;\n}\n\ninterface RedisLike extends MinimalRedis {\n incr(key: string): Promise<number>;\n expire(key: string, seconds: number): Promise<unknown>;\n}\n\n/** Framework-agnostic rate limiter. Hono / Express / Fastify / Next.js / Web adapters\n * share one core. Each `createRateLimiter` call owns its own memory map + redis\n * connection, so multiple instances in the same process don't share state unless\n * they share a Redis with the same `keyPrefix`. */\nexport function createRateLimiter(opts: RateLimitCoreOptions = {}): RateLimiter {\n const windowSeconds = opts.windowSeconds ?? 60;\n const maxRequests = opts.maxRequests ?? 60;\n const keyPrefix = opts.keyPrefix ?? 'rl:';\n\n const memMap = new Map<string, { count: number; resetAt: number }>();\n const getRedis = memoizedRedis<RedisLike>({ url: opts.redisUrl, label: 'rate-limit' });\n\n const checkMem = (key: string): RateLimitDecision => {\n const now = Date.now();\n const entry = memMap.get(key);\n if (!entry || entry.resetAt < now) {\n memMap.set(key, { count: 1, resetAt: now + windowSeconds * 1000 });\n return { allowed: true, remaining: maxRequests - 1, limit: maxRequests };\n }\n entry.count++;\n const remaining = Math.max(0, maxRequests - entry.count);\n return { allowed: entry.count <= maxRequests, remaining, limit: maxRequests };\n };\n\n return {\n async check(key: string): Promise<RateLimitDecision> {\n const r = await getRedis();\n if (!r) return checkMem(key);\n try {\n const fullKey = `${keyPrefix}${key}`;\n const count = await r.incr(fullKey);\n if (count === 1) await r.expire(fullKey, windowSeconds);\n const remaining = Math.max(0, maxRequests - count);\n return { allowed: count <= maxRequests, remaining, limit: maxRequests };\n } catch {\n return checkMem(key);\n }\n },\n };\n}\n\nexport const RATE_LIMIT_JSON_BODY = {\n error: { code: 'rate_limited', message: 'Too many requests' },\n} as const;\n\n/** Default key resolver: first hop of `x-forwarded-for`, else `'unknown'`. Works on any\n * framework's request once you adapt the header read. */\nexport function defaultKeyFromForwardedFor(forwardedFor: string | null | undefined): string {\n if (!forwardedFor) return 'unknown';\n return forwardedFor.split(',')[0]?.trim() || 'unknown';\n}\n","import {\n RATE_LIMIT_JSON_BODY,\n createRateLimiter,\n defaultKeyFromForwardedFor,\n type RateLimitCoreOptions,\n} from './_core';\n\nexport interface RateLimitWebOptions extends RateLimitCoreOptions {\n /** Bucket key resolver. Default: first hop of `x-forwarded-for`, else `'unknown'`. */\n keyResolver?: (req: Request) => string;\n}\n\nexport type RateLimitGuardResult =\n | { allowed: true; remaining: number; limit: number; response?: undefined }\n | { allowed: false; remaining: number; limit: number; response: Response };\n\nexport type RateLimitGuard = (req: Request) => Promise<RateLimitGuardResult>;\n\n/**\n * Build a rate-limit guard for Web Fetch–style handlers. Call `guard(req)` at the top\n * of your route. When `allowed === false`, return `result.response` directly.\n */\nexport function createRateLimit(opts: RateLimitWebOptions = {}): RateLimitGuard {\n const limiter = createRateLimiter(opts);\n const keyResolver =\n opts.keyResolver ?? ((req: Request) => defaultKeyFromForwardedFor(req.headers.get('x-forwarded-for')));\n\n return async (req: Request) => {\n const { allowed, remaining, limit } = await limiter.check(keyResolver(req));\n const baseHeaders = {\n 'X-RateLimit-Limit': String(limit),\n 'X-RateLimit-Remaining': String(remaining),\n };\n if (!allowed) {\n const response = new Response(JSON.stringify(RATE_LIMIT_JSON_BODY), {\n status: 429,\n headers: { ...baseHeaders, 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },\n });\n return { allowed: false, remaining, limit, response };\n }\n return { allowed: true, remaining, limit };\n };\n}\n"],"mappings":";AAoCA,eAAe,eAAuC,MAA6C;AACjG,QAAM,MAAM,KAAK,OAAO,QAAQ,IAAI;AACpC,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,SAAS;AACnC,UAAM,SAAS,IAAI,IAAI,QAAQ,KAAK;AAAA,MAClC,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,sBAAsB,KAAK,wBAAwB;AAAA,MACnD,KAAK,IAAI,WAAW,WAAW,IAAI,CAAC,IAAI;AAAA,IAC1C,CAAC;AACD,WAAO,GAAG,SAAS,CAAC,QAAQ,QAAQ,MAAM,IAAI,KAAK,KAAK,kBAAkB,IAAI,OAAO,CAAC;AACtF,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMO,SAAS,cAAsC,MAAmD;AACvG,MAAI,UAAoC;AACxC,SAAO,MAAM;AACX,QAAI,CAAC,QAAS,WAAU,eAAkB,IAAI;AAC9C,WAAO;AAAA,EACT;AACF;;;ACjCO,SAAS,kBAAkB,OAA6B,CAAC,GAAgB;AAC9E,QAAM,gBAAgB,KAAK,iBAAiB;AAC5C,QAAM,cAAc,KAAK,eAAe;AACxC,QAAM,YAAY,KAAK,aAAa;AAEpC,QAAM,SAAS,oBAAI,IAAgD;AACnE,QAAM,WAAW,cAAyB,EAAE,KAAK,KAAK,UAAU,OAAO,aAAa,CAAC;AAErF,QAAM,WAAW,CAAC,QAAmC;AACnD,UAAM,MAAM,KAAK,IAAI;AACrB,UAAM,QAAQ,OAAO,IAAI,GAAG;AAC5B,QAAI,CAAC,SAAS,MAAM,UAAU,KAAK;AACjC,aAAO,IAAI,KAAK,EAAE,OAAO,GAAG,SAAS,MAAM,gBAAgB,IAAK,CAAC;AACjE,aAAO,EAAE,SAAS,MAAM,WAAW,cAAc,GAAG,OAAO,YAAY;AAAA,IACzE;AACA,UAAM;AACN,UAAM,YAAY,KAAK,IAAI,GAAG,cAAc,MAAM,KAAK;AACvD,WAAO,EAAE,SAAS,MAAM,SAAS,aAAa,WAAW,OAAO,YAAY;AAAA,EAC9E;AAEA,SAAO;AAAA,IACL,MAAM,MAAM,KAAyC;AACnD,YAAM,IAAI,MAAM,SAAS;AACzB,UAAI,CAAC,EAAG,QAAO,SAAS,GAAG;AAC3B,UAAI;AACF,cAAM,UAAU,GAAG,SAAS,GAAG,GAAG;AAClC,cAAM,QAAQ,MAAM,EAAE,KAAK,OAAO;AAClC,YAAI,UAAU,EAAG,OAAM,EAAE,OAAO,SAAS,aAAa;AACtD,cAAM,YAAY,KAAK,IAAI,GAAG,cAAc,KAAK;AACjD,eAAO,EAAE,SAAS,SAAS,aAAa,WAAW,OAAO,YAAY;AAAA,MACxE,QAAQ;AACN,eAAO,SAAS,GAAG;AAAA,MACrB;AAAA,IACF;AAAA,EACF;AACF;AAEO,IAAM,uBAAuB;AAAA,EAClC,OAAO,EAAE,MAAM,gBAAgB,SAAS,oBAAoB;AAC9D;AAIO,SAAS,2BAA2B,cAAiD;AAC1F,MAAI,CAAC,aAAc,QAAO;AAC1B,SAAO,aAAa,MAAM,GAAG,EAAE,CAAC,GAAG,KAAK,KAAK;AAC/C;;;ACtDO,SAAS,gBAAgB,OAA4B,CAAC,GAAmB;AAC9E,QAAM,UAAU,kBAAkB,IAAI;AACtC,QAAM,cACJ,KAAK,gBAAgB,CAAC,QAAiB,2BAA2B,IAAI,QAAQ,IAAI,iBAAiB,CAAC;AAEtG,SAAO,OAAO,QAAiB;AAC7B,UAAM,EAAE,SAAS,WAAW,MAAM,IAAI,MAAM,QAAQ,MAAM,YAAY,GAAG,CAAC;AAC1E,UAAM,cAAc;AAAA,MAClB,qBAAqB,OAAO,KAAK;AAAA,MACjC,yBAAyB,OAAO,SAAS;AAAA,IAC3C;AACA,QAAI,CAAC,SAAS;AACZ,YAAM,WAAW,IAAI,SAAS,KAAK,UAAU,oBAAoB,GAAG;AAAA,QAClE,QAAQ;AAAA,QACR,SAAS,EAAE,GAAG,aAAa,gBAAgB,oBAAoB,iBAAiB,WAAW;AAAA,MAC7F,CAAC;AACD,aAAO,EAAE,SAAS,OAAO,WAAW,OAAO,SAAS;AAAA,IACtD;AACA,WAAO,EAAE,SAAS,MAAM,WAAW,MAAM;AAAA,EAC3C;AACF;","names":[]}
|
package/dist/payment/index.d.mts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { T as TempoRailSpec, S as SolanaMppRailSpec,
|
|
2
|
-
export { R as RAIL_SPEC_DEFAULTS,
|
|
3
|
-
import {
|
|
4
|
-
export { B as BuildX402AcceptsForOptions, C as CreateX402ServerOptions,
|
|
1
|
+
import { T as TempoRailSpec, S as SolanaMppRailSpec, c as TempoSessionRailSpec, b as StripeRailSpec, X as X402BaseRailSpec } from '../rail_spec-D6qzh3J0.mjs';
|
|
2
|
+
export { R as RAIL_SPEC_DEFAULTS, a as RecipientLike, r as resolveRecipient } from '../rail_spec-D6qzh3J0.mjs';
|
|
3
|
+
import { a as X402Server } from '../x402_server-Ciz2mls2.mjs';
|
|
4
|
+
export { B as BuildX402AcceptsForOptions, C as CreateX402ServerOptions, X as X402FacilitatorChoice, b as X402SymbolicRail, c as buildX402AcceptsFor402, d as createX402Server } from '../x402_server-Ciz2mls2.mjs';
|
|
5
5
|
export { a as aliasAmountFields, p as paymentRequiredHeader, w as wwwAuthenticateHeader } from '../wwwauthenticate-D_FMnPgU.mjs';
|
|
6
6
|
import { S as SignerNetwork } from '../signer-3FAit11j.mjs';
|
|
7
7
|
export { P as PaymentSigner, e as extractPaymentSigner, a as extractPaymentSignerFromAuth, b as extractSignerForPrecheck, r as readX402PaymentHeader } from '../signer-3FAit11j.mjs';
|
|
8
|
-
export { f as formatUsdCents, l as loadSolanaFeePayer, u as usdToAtomic } from '../
|
|
8
|
+
export { B as BuildDefaultCheckoutRailsOptions, a as BuildMppxComposeRailsOptions, H as HeadersLike, b as asHeaders, c as buildDefaultCheckoutRails, d as buildMppxComposeRails, f as formatUsdCents, h as hasMppxHeader, e as hasPaymentHeader, g as hasX402Header, l as loadSolanaFeePayer, r as readHeader, u as usdToAtomic } from '../default_rails-XFCuRddA.mjs';
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* Build the base64-encoded `request` blob for an MPP Payment directive (per the
|
|
@@ -569,21 +569,17 @@ type MppxComposeResult = {
|
|
|
569
569
|
challenge: Response;
|
|
570
570
|
[k: string]: unknown;
|
|
571
571
|
};
|
|
572
|
-
/**
|
|
573
|
-
*
|
|
574
|
-
* `
|
|
575
|
-
*
|
|
576
|
-
*
|
|
577
|
-
*
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
* if (result.status === 402) return { status: 402, headers: mppxChallengeHeaders(result) };
|
|
584
|
-
* return { status: 200, raw: result };
|
|
585
|
-
* ```
|
|
586
|
-
*/
|
|
572
|
+
/** Run `fn` inside an async context that captures the inner mppx
|
|
573
|
+
* verification error (when one fires). Returns the function's result
|
|
574
|
+
* plus the captured `failureReason` string (null if no error fired or
|
|
575
|
+
* no console.error hit during this scope). Used by `Checkout.handleMppx`
|
|
576
|
+
* to surface typed error codes (`tempo_key_not_registered`, etc.) on
|
|
577
|
+
* the 402 path without changing the per-merchant `composeMppx` API.
|
|
578
|
+
*/
|
|
579
|
+
declare function runWithMppxFailureCapture<T>(fn: () => Promise<T>): Promise<{
|
|
580
|
+
result: T;
|
|
581
|
+
failureReason: string | null;
|
|
582
|
+
}>;
|
|
587
583
|
declare function composeMppxRequest(mppx: unknown, intents: readonly unknown[], request: Request): Promise<MppxComposeResult>;
|
|
588
584
|
/**
|
|
589
585
|
* Extract the 402 challenge response's headers as a plain `Record<string, string>`,
|
|
@@ -879,4 +875,19 @@ declare function lazyMppxServer(opts: {
|
|
|
879
875
|
secretKey: string;
|
|
880
876
|
}): () => Promise<unknown>;
|
|
881
877
|
|
|
882
|
-
|
|
878
|
+
/** CAIP-2 prefix discriminators. Replaces the ad-hoc `startsWith('eip155:')` /
|
|
879
|
+
* `startsWith('solana:')` calls scattered across `checkout`, `checkout_compute_first`,
|
|
880
|
+
* `payment/lazy`, and `identity/ucp` so the prefix strings live in one place.
|
|
881
|
+
*
|
|
882
|
+
* Accepts the bare network spec `'eip155:8453'` or a rail-spec object with a
|
|
883
|
+
* `network` field. Pure functions; no peer-dep imports.
|
|
884
|
+
*/
|
|
885
|
+
type NetworkLike = string | object | null | undefined;
|
|
886
|
+
/** True when the network is a CAIP-2 EVM chain (`eip155:<chainId>`). */
|
|
887
|
+
declare function isEvmNetwork(input: NetworkLike): boolean;
|
|
888
|
+
/** True when the network is a CAIP-2 Solana chain (`solana:<genesis-hash>`).
|
|
889
|
+
* Note: `'solana'` bare (no `:`) is the mppx-internal label, NOT a CAIP-2
|
|
890
|
+
* network spec — this helper treats it as false. */
|
|
891
|
+
declare function isSolanaNetwork(input: NetworkLike): boolean;
|
|
892
|
+
|
|
893
|
+
export { type ClassifiedX402Error, type MppxComposeResult, type MppxRailSpec, type NetworkFamily, type PaymentHeadersRail, type PaymentHeadersResult, type ProcessX402SettleResult, type RailDefinition, type RailName, SETTLEMENT_OVERRIDES_HEADER, type SettlementHandlers, type SettlementOverrides, type SettlementPayloadLike, SignerNetwork, SolanaMppRailSpec, StripeRailSpec, TempoRailSpec, TempoSessionRailSpec, USDC, type VerifyX402RequestResult, X402BaseRailSpec, X402Server, type X402ServerLike, X402_SUPPORTED_BASE_NETWORKS, type ZeroSettleRail, type ZeroSettleResult, buildIdempotencyKey, buildPaymentDirective, buildPaymentHeaders, buildPaymentRequestBlob, classifyOrchestrationError, classifyX402SettleResult, composeMppxRequest, createMppxServer, detectRailFromHeaders, dispatchSettlementByNetwork, isEvmNetwork, isSolanaNetwork, lazyMppxServer, lazyX402Server, lookupRail, mppxChallengeHeaders, networkFamily, networks, paymentDirective, processX402Settle, rails, registerX402SchemesV1V2, runWithMppxFailureCapture, settlementOverrideHeader, validateX402NetworkConfig, verifyX402Request, wrapSolanaChargeWithFinalizedBlockhash, zeroAmountCarveOut };
|
package/dist/payment/index.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { T as TempoRailSpec, S as SolanaMppRailSpec,
|
|
2
|
-
export { R as RAIL_SPEC_DEFAULTS,
|
|
3
|
-
import {
|
|
4
|
-
export { B as BuildX402AcceptsForOptions, C as CreateX402ServerOptions,
|
|
1
|
+
import { T as TempoRailSpec, S as SolanaMppRailSpec, c as TempoSessionRailSpec, b as StripeRailSpec, X as X402BaseRailSpec } from '../rail_spec-D6qzh3J0.js';
|
|
2
|
+
export { R as RAIL_SPEC_DEFAULTS, a as RecipientLike, r as resolveRecipient } from '../rail_spec-D6qzh3J0.js';
|
|
3
|
+
import { a as X402Server } from '../x402_server-Ciz2mls2.js';
|
|
4
|
+
export { B as BuildX402AcceptsForOptions, C as CreateX402ServerOptions, X as X402FacilitatorChoice, b as X402SymbolicRail, c as buildX402AcceptsFor402, d as createX402Server } from '../x402_server-Ciz2mls2.js';
|
|
5
5
|
export { a as aliasAmountFields, p as paymentRequiredHeader, w as wwwAuthenticateHeader } from '../wwwauthenticate-D_FMnPgU.js';
|
|
6
6
|
import { S as SignerNetwork } from '../signer-3FAit11j.js';
|
|
7
7
|
export { P as PaymentSigner, e as extractPaymentSigner, a as extractPaymentSignerFromAuth, b as extractSignerForPrecheck, r as readX402PaymentHeader } from '../signer-3FAit11j.js';
|
|
8
|
-
export { f as formatUsdCents, l as loadSolanaFeePayer, u as usdToAtomic } from '../
|
|
8
|
+
export { B as BuildDefaultCheckoutRailsOptions, a as BuildMppxComposeRailsOptions, H as HeadersLike, b as asHeaders, c as buildDefaultCheckoutRails, d as buildMppxComposeRails, f as formatUsdCents, h as hasMppxHeader, e as hasPaymentHeader, g as hasX402Header, l as loadSolanaFeePayer, r as readHeader, u as usdToAtomic } from '../default_rails-C5gKZJMI.js';
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* Build the base64-encoded `request` blob for an MPP Payment directive (per the
|
|
@@ -569,21 +569,17 @@ type MppxComposeResult = {
|
|
|
569
569
|
challenge: Response;
|
|
570
570
|
[k: string]: unknown;
|
|
571
571
|
};
|
|
572
|
-
/**
|
|
573
|
-
*
|
|
574
|
-
* `
|
|
575
|
-
*
|
|
576
|
-
*
|
|
577
|
-
*
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
* if (result.status === 402) return { status: 402, headers: mppxChallengeHeaders(result) };
|
|
584
|
-
* return { status: 200, raw: result };
|
|
585
|
-
* ```
|
|
586
|
-
*/
|
|
572
|
+
/** Run `fn` inside an async context that captures the inner mppx
|
|
573
|
+
* verification error (when one fires). Returns the function's result
|
|
574
|
+
* plus the captured `failureReason` string (null if no error fired or
|
|
575
|
+
* no console.error hit during this scope). Used by `Checkout.handleMppx`
|
|
576
|
+
* to surface typed error codes (`tempo_key_not_registered`, etc.) on
|
|
577
|
+
* the 402 path without changing the per-merchant `composeMppx` API.
|
|
578
|
+
*/
|
|
579
|
+
declare function runWithMppxFailureCapture<T>(fn: () => Promise<T>): Promise<{
|
|
580
|
+
result: T;
|
|
581
|
+
failureReason: string | null;
|
|
582
|
+
}>;
|
|
587
583
|
declare function composeMppxRequest(mppx: unknown, intents: readonly unknown[], request: Request): Promise<MppxComposeResult>;
|
|
588
584
|
/**
|
|
589
585
|
* Extract the 402 challenge response's headers as a plain `Record<string, string>`,
|
|
@@ -879,4 +875,19 @@ declare function lazyMppxServer(opts: {
|
|
|
879
875
|
secretKey: string;
|
|
880
876
|
}): () => Promise<unknown>;
|
|
881
877
|
|
|
882
|
-
|
|
878
|
+
/** CAIP-2 prefix discriminators. Replaces the ad-hoc `startsWith('eip155:')` /
|
|
879
|
+
* `startsWith('solana:')` calls scattered across `checkout`, `checkout_compute_first`,
|
|
880
|
+
* `payment/lazy`, and `identity/ucp` so the prefix strings live in one place.
|
|
881
|
+
*
|
|
882
|
+
* Accepts the bare network spec `'eip155:8453'` or a rail-spec object with a
|
|
883
|
+
* `network` field. Pure functions; no peer-dep imports.
|
|
884
|
+
*/
|
|
885
|
+
type NetworkLike = string | object | null | undefined;
|
|
886
|
+
/** True when the network is a CAIP-2 EVM chain (`eip155:<chainId>`). */
|
|
887
|
+
declare function isEvmNetwork(input: NetworkLike): boolean;
|
|
888
|
+
/** True when the network is a CAIP-2 Solana chain (`solana:<genesis-hash>`).
|
|
889
|
+
* Note: `'solana'` bare (no `:`) is the mppx-internal label, NOT a CAIP-2
|
|
890
|
+
* network spec — this helper treats it as false. */
|
|
891
|
+
declare function isSolanaNetwork(input: NetworkLike): boolean;
|
|
892
|
+
|
|
893
|
+
export { type ClassifiedX402Error, type MppxComposeResult, type MppxRailSpec, type NetworkFamily, type PaymentHeadersRail, type PaymentHeadersResult, type ProcessX402SettleResult, type RailDefinition, type RailName, SETTLEMENT_OVERRIDES_HEADER, type SettlementHandlers, type SettlementOverrides, type SettlementPayloadLike, SignerNetwork, SolanaMppRailSpec, StripeRailSpec, TempoRailSpec, TempoSessionRailSpec, USDC, type VerifyX402RequestResult, X402BaseRailSpec, X402Server, type X402ServerLike, X402_SUPPORTED_BASE_NETWORKS, type ZeroSettleRail, type ZeroSettleResult, buildIdempotencyKey, buildPaymentDirective, buildPaymentHeaders, buildPaymentRequestBlob, classifyOrchestrationError, classifyX402SettleResult, composeMppxRequest, createMppxServer, detectRailFromHeaders, dispatchSettlementByNetwork, isEvmNetwork, isSolanaNetwork, lazyMppxServer, lazyX402Server, lookupRail, mppxChallengeHeaders, networkFamily, networks, paymentDirective, processX402Settle, rails, registerX402SchemesV1V2, runWithMppxFailureCapture, settlementOverrideHeader, validateX402NetworkConfig, verifyX402Request, wrapSolanaChargeWithFinalizedBlockhash, zeroAmountCarveOut };
|