@ar-agents/mercadopago 0.8.0 → 0.10.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/CHANGELOG.md +100 -0
- package/README.md +99 -1
- package/dist/index.cjs +1093 -69
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +963 -4
- package/dist/index.d.ts +963 -4
- package/dist/index.js +1074 -70
- package/dist/index.js.map +1 -1
- package/dist/otel.cjs +102 -0
- package/dist/otel.cjs.map +1 -0
- package/dist/otel.d.cts +90 -0
- package/dist/otel.d.ts +90 -0
- package/dist/otel.js +100 -0
- package/dist/otel.js.map +1 -0
- package/package.json +28 -4
- package/tools.manifest.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,6 +1,75 @@
|
|
|
1
1
|
import { tool } from 'ai';
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __esm = (fn, res) => function __init() {
|
|
7
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
8
|
+
};
|
|
9
|
+
var __export = (target, all) => {
|
|
10
|
+
for (var name in all)
|
|
11
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
// src/crypto.ts
|
|
15
|
+
var crypto_exports = {};
|
|
16
|
+
__export(crypto_exports, {
|
|
17
|
+
hmacSha256Hex: () => hmacSha256Hex,
|
|
18
|
+
sha256Hex: () => sha256Hex,
|
|
19
|
+
timingSafeEqualHex: () => timingSafeEqualHex
|
|
20
|
+
});
|
|
21
|
+
async function hmacSha256Hex(secret, message) {
|
|
22
|
+
const keyMaterial = await subtle.importKey(
|
|
23
|
+
"raw",
|
|
24
|
+
encoder.encode(secret),
|
|
25
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
26
|
+
false,
|
|
27
|
+
["sign"]
|
|
28
|
+
);
|
|
29
|
+
const sigBuf = await subtle.sign(
|
|
30
|
+
"HMAC",
|
|
31
|
+
keyMaterial,
|
|
32
|
+
encoder.encode(message)
|
|
33
|
+
);
|
|
34
|
+
return bufferToHex(sigBuf);
|
|
35
|
+
}
|
|
36
|
+
async function sha256Hex(input) {
|
|
37
|
+
const digest = await subtle.digest("SHA-256", encoder.encode(input));
|
|
38
|
+
return bufferToHex(digest);
|
|
39
|
+
}
|
|
40
|
+
function timingSafeEqualHex(a, b) {
|
|
41
|
+
if (a.length !== b.length) return false;
|
|
42
|
+
let diff = 0;
|
|
43
|
+
for (let i = 0; i < a.length; i++) {
|
|
44
|
+
diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
45
|
+
}
|
|
46
|
+
return diff === 0;
|
|
47
|
+
}
|
|
48
|
+
function bufferToHex(buf) {
|
|
49
|
+
const bytes = new Uint8Array(buf);
|
|
50
|
+
let hex = "";
|
|
51
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
52
|
+
const b = bytes[i];
|
|
53
|
+
hex += (b < 16 ? "0" : "") + b.toString(16);
|
|
54
|
+
}
|
|
55
|
+
return hex;
|
|
56
|
+
}
|
|
57
|
+
var subtle, encoder;
|
|
58
|
+
var init_crypto = __esm({
|
|
59
|
+
"src/crypto.ts"() {
|
|
60
|
+
subtle = (() => {
|
|
61
|
+
const c = globalThis.crypto;
|
|
62
|
+
if (!c?.subtle) {
|
|
63
|
+
throw new Error(
|
|
64
|
+
"@ar-agents/mercadopago: Web Crypto API is not available in this runtime. Use Node 18+, Vercel Edge Runtime, Cloudflare Workers, or any modern browser."
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
return c.subtle;
|
|
68
|
+
})();
|
|
69
|
+
encoder = new TextEncoder();
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
|
|
4
73
|
// src/errors.ts
|
|
5
74
|
var MercadoPagoError = class extends Error {
|
|
6
75
|
constructor(message, status, endpoint, mpResponse) {
|
|
@@ -164,6 +233,8 @@ var MercadoPagoClient = class {
|
|
|
164
233
|
requestTimeoutMs;
|
|
165
234
|
maxRetries;
|
|
166
235
|
onCall;
|
|
236
|
+
circuitBreaker;
|
|
237
|
+
traceContext;
|
|
167
238
|
constructor(options) {
|
|
168
239
|
if (!options.accessToken) {
|
|
169
240
|
throw new Error(
|
|
@@ -176,8 +247,24 @@ var MercadoPagoClient = class {
|
|
|
176
247
|
this.requestTimeoutMs = options.requestTimeoutMs ?? 3e4;
|
|
177
248
|
this.maxRetries = Math.max(0, options.maxRetries ?? 1);
|
|
178
249
|
this.onCall = options.onCall;
|
|
250
|
+
this.circuitBreaker = options.circuitBreaker;
|
|
251
|
+
this.traceContext = options.traceContext;
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* v0.9 — Inspect the circuit breaker state (when configured). Returns
|
|
255
|
+
* `null` when no circuit breaker is wired. Useful for health checks.
|
|
256
|
+
*/
|
|
257
|
+
getCircuitState() {
|
|
258
|
+
return this.circuitBreaker?.getStats() ?? null;
|
|
179
259
|
}
|
|
180
260
|
async request(method, path, body, options) {
|
|
261
|
+
const exec = () => this.requestUnprotected(method, path, body, options);
|
|
262
|
+
if (this.circuitBreaker) {
|
|
263
|
+
return this.circuitBreaker.execute(exec);
|
|
264
|
+
}
|
|
265
|
+
return exec();
|
|
266
|
+
}
|
|
267
|
+
async requestUnprotected(method, path, body, options) {
|
|
181
268
|
const headers = {
|
|
182
269
|
Authorization: `Bearer ${this.accessToken}`,
|
|
183
270
|
"Content-Type": "application/json"
|
|
@@ -185,6 +272,11 @@ var MercadoPagoClient = class {
|
|
|
185
272
|
if (options?.idempotencyKey) {
|
|
186
273
|
headers["X-Idempotency-Key"] = options.idempotencyKey;
|
|
187
274
|
}
|
|
275
|
+
const trace = this.traceContext?.();
|
|
276
|
+
if (trace?.traceId && trace?.spanId) {
|
|
277
|
+
const flags = (trace.traceFlags ?? 1).toString(16).padStart(2, "0");
|
|
278
|
+
headers["traceparent"] = `00-${trace.traceId}-${trace.spanId}-${flags}`;
|
|
279
|
+
}
|
|
188
280
|
let url = `${this.baseUrl}${path}`;
|
|
189
281
|
if (options?.query) {
|
|
190
282
|
const search = new URLSearchParams();
|
|
@@ -201,24 +293,54 @@ var MercadoPagoClient = class {
|
|
|
201
293
|
let attempt = 0;
|
|
202
294
|
let lastError;
|
|
203
295
|
let lastStatus = null;
|
|
296
|
+
const fireOnCall = (event) => {
|
|
297
|
+
const traceCtx = trace?.traceId ? {
|
|
298
|
+
traceId: trace.traceId,
|
|
299
|
+
...trace.spanId !== void 0 ? { spanId: trace.spanId } : {}
|
|
300
|
+
} : void 0;
|
|
301
|
+
this.onCall?.({
|
|
302
|
+
method,
|
|
303
|
+
path,
|
|
304
|
+
durationMs: Date.now() - t0,
|
|
305
|
+
...event,
|
|
306
|
+
...this.circuitBreaker ? { circuitState: this.circuitBreaker.getState() } : {},
|
|
307
|
+
...traceCtx ? { traceContext: traceCtx } : {}
|
|
308
|
+
});
|
|
309
|
+
};
|
|
204
310
|
while (attempt <= this.maxRetries) {
|
|
205
311
|
const controller = new AbortController();
|
|
206
312
|
const timer = setTimeout(() => controller.abort(), this.requestTimeoutMs);
|
|
313
|
+
const parentSignal = options?.signal;
|
|
314
|
+
const onParentAbort = () => controller.abort();
|
|
315
|
+
if (parentSignal) {
|
|
316
|
+
if (parentSignal.aborted) {
|
|
317
|
+
clearTimeout(timer);
|
|
318
|
+
throw new MercadoPagoTimeoutError(path, 0);
|
|
319
|
+
}
|
|
320
|
+
parentSignal.addEventListener("abort", onParentAbort, { once: true });
|
|
321
|
+
}
|
|
207
322
|
const init = { method, headers, signal: controller.signal };
|
|
208
323
|
if (body !== void 0) init.body = JSON.stringify(body);
|
|
209
324
|
try {
|
|
210
325
|
const res = await fetchFn(url, init);
|
|
211
326
|
clearTimeout(timer);
|
|
327
|
+
if (parentSignal) parentSignal.removeEventListener("abort", onParentAbort);
|
|
212
328
|
lastStatus = res.status;
|
|
329
|
+
const requestId = res.headers.get("x-request-id");
|
|
330
|
+
const rlRemaining = res.headers.get("x-rate-limit-remaining");
|
|
331
|
+
const rlReset = res.headers.get("x-rate-limit-reset");
|
|
332
|
+
const rateLimit = {
|
|
333
|
+
remaining: rlRemaining !== null ? Number(rlRemaining) : null,
|
|
334
|
+
resetSeconds: rlReset !== null ? Number(rlReset) : null
|
|
335
|
+
};
|
|
213
336
|
if (res.ok) {
|
|
214
337
|
const text2 = await res.text();
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
path,
|
|
218
|
-
durationMs: Date.now() - t0,
|
|
338
|
+
fireOnCall({
|
|
339
|
+
success: true,
|
|
219
340
|
httpStatus: res.status,
|
|
220
341
|
retried: attempt,
|
|
221
|
-
|
|
342
|
+
requestId,
|
|
343
|
+
rateLimit
|
|
222
344
|
});
|
|
223
345
|
if (!text2) return void 0;
|
|
224
346
|
return JSON.parse(text2);
|
|
@@ -233,13 +355,12 @@ var MercadoPagoClient = class {
|
|
|
233
355
|
}
|
|
234
356
|
const contentType = res.headers.get("content-type") ?? "";
|
|
235
357
|
if (res.status >= 500 && !contentType.includes("application/json")) {
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
path,
|
|
239
|
-
durationMs: Date.now() - t0,
|
|
358
|
+
fireOnCall({
|
|
359
|
+
success: false,
|
|
240
360
|
httpStatus: res.status,
|
|
241
361
|
retried: attempt,
|
|
242
|
-
|
|
362
|
+
requestId,
|
|
363
|
+
rateLimit
|
|
243
364
|
});
|
|
244
365
|
throw new MercadoPagoOverloadedError(path, res.status);
|
|
245
366
|
}
|
|
@@ -251,33 +372,33 @@ var MercadoPagoClient = class {
|
|
|
251
372
|
parsed = text;
|
|
252
373
|
}
|
|
253
374
|
const err = classifyError(res.status, path, parsed, options?.classifyContext);
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
path,
|
|
257
|
-
durationMs: Date.now() - t0,
|
|
375
|
+
fireOnCall({
|
|
376
|
+
success: false,
|
|
258
377
|
httpStatus: res.status,
|
|
259
378
|
retried: attempt,
|
|
260
|
-
|
|
379
|
+
requestId,
|
|
380
|
+
rateLimit
|
|
261
381
|
});
|
|
262
382
|
throw err;
|
|
263
383
|
} catch (err) {
|
|
264
384
|
clearTimeout(timer);
|
|
385
|
+
if (parentSignal) parentSignal.removeEventListener("abort", onParentAbort);
|
|
265
386
|
if (err instanceof MercadoPagoError) throw err;
|
|
266
387
|
const isAbort = err instanceof Error && err.name === "AbortError";
|
|
388
|
+
const isParentAbort = parentSignal?.aborted ?? false;
|
|
267
389
|
const isNetwork = !lastStatus && !isAbort;
|
|
268
|
-
if ((isNetwork || isAbort) && attempt < this.maxRetries) {
|
|
390
|
+
if ((isNetwork || isAbort && !isParentAbort) && attempt < this.maxRetries) {
|
|
269
391
|
lastError = err;
|
|
270
392
|
attempt++;
|
|
271
393
|
await sleep(250 * Math.pow(2, attempt - 1));
|
|
272
394
|
continue;
|
|
273
395
|
}
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
path,
|
|
277
|
-
durationMs: Date.now() - t0,
|
|
396
|
+
fireOnCall({
|
|
397
|
+
success: false,
|
|
278
398
|
httpStatus: lastStatus,
|
|
279
399
|
retried: attempt,
|
|
280
|
-
|
|
400
|
+
requestId: null,
|
|
401
|
+
rateLimit: { remaining: null, resetSeconds: null }
|
|
281
402
|
});
|
|
282
403
|
if (isAbort) {
|
|
283
404
|
throw new MercadoPagoTimeoutError(path, this.requestTimeoutMs);
|
|
@@ -1231,55 +1352,57 @@ var MercadoPagoClient = class {
|
|
|
1231
1352
|
);
|
|
1232
1353
|
return { id: intentId, canceled: true };
|
|
1233
1354
|
}
|
|
1355
|
+
// ──────────────────────────────────────────────────────────────────────────
|
|
1356
|
+
// v0.9 — Health check
|
|
1357
|
+
//
|
|
1358
|
+
// No dedicated ping endpoint exists in MP's public API. We use `getMe()`
|
|
1359
|
+
// (`/users/me`) as a lightweight liveness probe — it requires only a valid
|
|
1360
|
+
// accessToken, returns ~200 bytes of JSON, and is the same call MP's own
|
|
1361
|
+
// dashboard makes on startup. A successful response proves: (a) network
|
|
1362
|
+
// path to MP is up, (b) accessToken is valid, (c) MP is responding.
|
|
1363
|
+
// ──────────────────────────────────────────────────────────────────────────
|
|
1364
|
+
/**
|
|
1365
|
+
* Liveness probe against MP. Returns latency + circuit-breaker state.
|
|
1366
|
+
* Use as a /health endpoint for k8s, Vercel cron, or status-page checks.
|
|
1367
|
+
*
|
|
1368
|
+
* Returns `{ ok: false, ... }` instead of throwing — designed for
|
|
1369
|
+
* monitoring loops that want to keep running.
|
|
1370
|
+
*
|
|
1371
|
+
* @param signal Optional AbortSignal to cap wait time (e.g., 2s for
|
|
1372
|
+
* status-page polling).
|
|
1373
|
+
*/
|
|
1374
|
+
async healthCheck(signal) {
|
|
1375
|
+
const t0 = Date.now();
|
|
1376
|
+
const circuitBefore = this.circuitBreaker?.getStats() ?? null;
|
|
1377
|
+
try {
|
|
1378
|
+
const me = await this.request(
|
|
1379
|
+
"GET",
|
|
1380
|
+
"/users/me",
|
|
1381
|
+
void 0,
|
|
1382
|
+
signal ? { signal } : {}
|
|
1383
|
+
);
|
|
1384
|
+
return {
|
|
1385
|
+
ok: true,
|
|
1386
|
+
latencyMs: Date.now() - t0,
|
|
1387
|
+
userId: String(me.id),
|
|
1388
|
+
error: null,
|
|
1389
|
+
circuit: this.circuitBreaker?.getStats() ?? null
|
|
1390
|
+
};
|
|
1391
|
+
} catch (err) {
|
|
1392
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1393
|
+
return {
|
|
1394
|
+
ok: false,
|
|
1395
|
+
latencyMs: Date.now() - t0,
|
|
1396
|
+
userId: null,
|
|
1397
|
+
error: message,
|
|
1398
|
+
circuit: this.circuitBreaker?.getStats() ?? circuitBefore
|
|
1399
|
+
};
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1234
1402
|
};
|
|
1235
1403
|
|
|
1236
|
-
// src/
|
|
1237
|
-
|
|
1238
|
-
const c = globalThis.crypto;
|
|
1239
|
-
if (!c?.subtle) {
|
|
1240
|
-
throw new Error(
|
|
1241
|
-
"@ar-agents/mercadopago: Web Crypto API is not available in this runtime. Use Node 18+, Vercel Edge Runtime, Cloudflare Workers, or any modern browser."
|
|
1242
|
-
);
|
|
1243
|
-
}
|
|
1244
|
-
return c.subtle;
|
|
1245
|
-
})();
|
|
1246
|
-
var encoder = new TextEncoder();
|
|
1247
|
-
async function hmacSha256Hex(secret, message) {
|
|
1248
|
-
const keyMaterial = await subtle.importKey(
|
|
1249
|
-
"raw",
|
|
1250
|
-
encoder.encode(secret),
|
|
1251
|
-
{ name: "HMAC", hash: "SHA-256" },
|
|
1252
|
-
false,
|
|
1253
|
-
["sign"]
|
|
1254
|
-
);
|
|
1255
|
-
const sigBuf = await subtle.sign(
|
|
1256
|
-
"HMAC",
|
|
1257
|
-
keyMaterial,
|
|
1258
|
-
encoder.encode(message)
|
|
1259
|
-
);
|
|
1260
|
-
return bufferToHex(sigBuf);
|
|
1261
|
-
}
|
|
1262
|
-
async function sha256Hex(input) {
|
|
1263
|
-
const digest = await subtle.digest("SHA-256", encoder.encode(input));
|
|
1264
|
-
return bufferToHex(digest);
|
|
1265
|
-
}
|
|
1266
|
-
function timingSafeEqualHex(a, b) {
|
|
1267
|
-
if (a.length !== b.length) return false;
|
|
1268
|
-
let diff = 0;
|
|
1269
|
-
for (let i = 0; i < a.length; i++) {
|
|
1270
|
-
diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
1271
|
-
}
|
|
1272
|
-
return diff === 0;
|
|
1273
|
-
}
|
|
1274
|
-
function bufferToHex(buf) {
|
|
1275
|
-
const bytes = new Uint8Array(buf);
|
|
1276
|
-
let hex = "";
|
|
1277
|
-
for (let i = 0; i < bytes.length; i++) {
|
|
1278
|
-
const b = bytes[i];
|
|
1279
|
-
hex += (b < 16 ? "0" : "") + b.toString(16);
|
|
1280
|
-
}
|
|
1281
|
-
return hex;
|
|
1282
|
-
}
|
|
1404
|
+
// src/tools.ts
|
|
1405
|
+
init_crypto();
|
|
1283
1406
|
z.enum(["MLA", "MLB", "MLM", "MCO", "MLC", "MLU"]);
|
|
1284
1407
|
var CurrencyIdSchema = z.enum(["ARS", "USD", "BRL", "MXN"]);
|
|
1285
1408
|
var FrequencyTypeSchema = z.enum(["months", "days"]);
|
|
@@ -1783,6 +1906,180 @@ function isExpiringSoon(expirationMs, skewSeconds = 300) {
|
|
|
1783
1906
|
return Date.now() + skewSeconds * 1e3 >= expirationMs;
|
|
1784
1907
|
}
|
|
1785
1908
|
|
|
1909
|
+
// src/ar-issuer-promos.ts
|
|
1910
|
+
var AHORA_PROGRAM_PROMOS = [
|
|
1911
|
+
{
|
|
1912
|
+
issuer: "*",
|
|
1913
|
+
// any AR-resident card
|
|
1914
|
+
paymentMethodId: "*",
|
|
1915
|
+
installments: 3,
|
|
1916
|
+
description: "Ahora 3 \u2014 3 cuotas sin inter\xE9s (programa nacional)",
|
|
1917
|
+
categories: ["electronics", "appliances", "clothing", "general"]
|
|
1918
|
+
},
|
|
1919
|
+
{
|
|
1920
|
+
issuer: "*",
|
|
1921
|
+
paymentMethodId: "*",
|
|
1922
|
+
installments: 6,
|
|
1923
|
+
description: "Ahora 6 \u2014 6 cuotas sin inter\xE9s (programa nacional, electrodom\xE9sticos l\xEDnea blanca)",
|
|
1924
|
+
categories: ["appliances"]
|
|
1925
|
+
},
|
|
1926
|
+
{
|
|
1927
|
+
issuer: "*",
|
|
1928
|
+
paymentMethodId: "*",
|
|
1929
|
+
installments: 12,
|
|
1930
|
+
description: "Ahora 12 \u2014 12 cuotas sin inter\xE9s (programa nacional)",
|
|
1931
|
+
categories: ["electronics", "appliances", "clothing"]
|
|
1932
|
+
},
|
|
1933
|
+
{
|
|
1934
|
+
issuer: "*",
|
|
1935
|
+
paymentMethodId: "*",
|
|
1936
|
+
installments: 18,
|
|
1937
|
+
description: "Ahora 18 \u2014 18 cuotas sin inter\xE9s (turismo nacional + electrodom\xE9sticos)",
|
|
1938
|
+
categories: ["appliances", "travel"]
|
|
1939
|
+
},
|
|
1940
|
+
{
|
|
1941
|
+
issuer: "*",
|
|
1942
|
+
paymentMethodId: "*",
|
|
1943
|
+
installments: 24,
|
|
1944
|
+
description: "Ahora 24 \u2014 24 cuotas sin inter\xE9s (electrodom\xE9sticos l\xEDnea blanca premium)",
|
|
1945
|
+
categories: ["appliances"]
|
|
1946
|
+
}
|
|
1947
|
+
];
|
|
1948
|
+
var AR_ISSUER_PROMOS = [
|
|
1949
|
+
// Naranja X
|
|
1950
|
+
{
|
|
1951
|
+
issuer: "Naranja X",
|
|
1952
|
+
paymentMethodId: "naranja",
|
|
1953
|
+
installments: 3,
|
|
1954
|
+
description: "Naranja Z (Plan Z) \u2014 3 cuotas con CFT promocional, todos los rubros"
|
|
1955
|
+
},
|
|
1956
|
+
{
|
|
1957
|
+
issuer: "Naranja X",
|
|
1958
|
+
paymentMethodId: "naranja",
|
|
1959
|
+
installments: 6,
|
|
1960
|
+
description: "Naranja \u2014 6 cuotas sin inter\xE9s con comercios adheridos (electro/indumentaria)",
|
|
1961
|
+
daysOfWeek: ["thu"],
|
|
1962
|
+
categories: ["electronics", "appliances", "clothing"]
|
|
1963
|
+
},
|
|
1964
|
+
// Galicia
|
|
1965
|
+
{
|
|
1966
|
+
issuer: "Banco Galicia",
|
|
1967
|
+
paymentMethodId: "visa",
|
|
1968
|
+
installments: 12,
|
|
1969
|
+
description: "Galicia Eminent / Quiero! \u2014 12 cuotas sin inter\xE9s en supermercados (jueves)",
|
|
1970
|
+
daysOfWeek: ["thu"],
|
|
1971
|
+
categories: ["supermarket"]
|
|
1972
|
+
},
|
|
1973
|
+
{
|
|
1974
|
+
issuer: "Banco Galicia",
|
|
1975
|
+
paymentMethodId: "master",
|
|
1976
|
+
installments: 6,
|
|
1977
|
+
description: "Galicia \u2014 6 cuotas sin inter\xE9s en gastronom\xEDa (viernes y s\xE1bados)",
|
|
1978
|
+
daysOfWeek: ["fri", "sat"]
|
|
1979
|
+
},
|
|
1980
|
+
// Santander
|
|
1981
|
+
{
|
|
1982
|
+
issuer: "Banco Santander",
|
|
1983
|
+
paymentMethodId: "visa",
|
|
1984
|
+
installments: 6,
|
|
1985
|
+
description: "Santander Black / Platinum \u2014 6 cuotas sin inter\xE9s en cines + viajes",
|
|
1986
|
+
categories: ["travel"]
|
|
1987
|
+
},
|
|
1988
|
+
{
|
|
1989
|
+
issuer: "Banco Santander",
|
|
1990
|
+
paymentMethodId: "amex",
|
|
1991
|
+
installments: 9,
|
|
1992
|
+
description: "Santander American Express \u2014 9 cuotas sin inter\xE9s en supermercados (martes y mi\xE9rcoles)",
|
|
1993
|
+
daysOfWeek: ["tue", "wed"],
|
|
1994
|
+
categories: ["supermarket"]
|
|
1995
|
+
},
|
|
1996
|
+
// Macro
|
|
1997
|
+
{
|
|
1998
|
+
issuer: "Banco Macro",
|
|
1999
|
+
paymentMethodId: "visa",
|
|
2000
|
+
installments: 6,
|
|
2001
|
+
description: "Macro Selecta / Premia \u2014 6 cuotas sin inter\xE9s en farmacias y librer\xEDas",
|
|
2002
|
+
categories: ["health", "education"]
|
|
2003
|
+
},
|
|
2004
|
+
// BBVA
|
|
2005
|
+
{
|
|
2006
|
+
issuer: "BBVA Banco Franc\xE9s",
|
|
2007
|
+
paymentMethodId: "visa",
|
|
2008
|
+
installments: 3,
|
|
2009
|
+
description: "BBVA Lat / Black \u2014 3 cuotas sin inter\xE9s en restaurantes (lunes a mi\xE9rcoles)",
|
|
2010
|
+
daysOfWeek: ["mon", "tue", "wed"]
|
|
2011
|
+
},
|
|
2012
|
+
// ICBC
|
|
2013
|
+
{
|
|
2014
|
+
issuer: "ICBC",
|
|
2015
|
+
paymentMethodId: "visa",
|
|
2016
|
+
installments: 6,
|
|
2017
|
+
description: "ICBC Cuenta Corriente \u2014 6 cuotas sin inter\xE9s en electro y indumentaria",
|
|
2018
|
+
categories: ["electronics", "appliances", "clothing"]
|
|
2019
|
+
},
|
|
2020
|
+
// Patagonia
|
|
2021
|
+
{
|
|
2022
|
+
issuer: "Banco Patagonia",
|
|
2023
|
+
paymentMethodId: "visa",
|
|
2024
|
+
installments: 3,
|
|
2025
|
+
description: "Patagonia 365 / Eminent \u2014 3 cuotas sin inter\xE9s en supermercados (s\xE1bados)",
|
|
2026
|
+
daysOfWeek: ["sat"],
|
|
2027
|
+
categories: ["supermarket"]
|
|
2028
|
+
},
|
|
2029
|
+
// Banco Nación
|
|
2030
|
+
{
|
|
2031
|
+
issuer: "Banco de la Naci\xF3n Argentina",
|
|
2032
|
+
paymentMethodId: "visa",
|
|
2033
|
+
installments: 12,
|
|
2034
|
+
description: "BNA \u2014 12 cuotas sin inter\xE9s con plan 'Ahora 12' del programa nacional",
|
|
2035
|
+
categories: ["electronics", "appliances", "clothing"]
|
|
2036
|
+
},
|
|
2037
|
+
// Banco Provincia
|
|
2038
|
+
{
|
|
2039
|
+
issuer: "Banco de la Provincia de Buenos Aires",
|
|
2040
|
+
paymentMethodId: "visa",
|
|
2041
|
+
installments: 6,
|
|
2042
|
+
description: "Cuenta DNI \u2014 6 cuotas sin inter\xE9s (mensual cap aplica)",
|
|
2043
|
+
maxAmountArs: 2e5
|
|
2044
|
+
},
|
|
2045
|
+
// Banco Ciudad
|
|
2046
|
+
{
|
|
2047
|
+
issuer: "Banco de la Ciudad de Buenos Aires",
|
|
2048
|
+
paymentMethodId: "visa",
|
|
2049
|
+
installments: 12,
|
|
2050
|
+
description: "Banco Ciudad \u2014 12 cuotas sin inter\xE9s en electrodom\xE9sticos (Plan Sue\xF1os)",
|
|
2051
|
+
categories: ["appliances"]
|
|
2052
|
+
}
|
|
2053
|
+
];
|
|
2054
|
+
function findApplicablePromos(args) {
|
|
2055
|
+
const date = args.date ?? /* @__PURE__ */ new Date();
|
|
2056
|
+
const dayOfWeek = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"][date.getDay()];
|
|
2057
|
+
const candidates = [
|
|
2058
|
+
...args.includeAhoraProgram !== false ? AHORA_PROGRAM_PROMOS : [],
|
|
2059
|
+
...AR_ISSUER_PROMOS
|
|
2060
|
+
];
|
|
2061
|
+
return candidates.filter((promo) => {
|
|
2062
|
+
if (args.issuer !== void 0 && promo.issuer !== "*" && promo.issuer !== args.issuer) {
|
|
2063
|
+
return false;
|
|
2064
|
+
}
|
|
2065
|
+
if (args.paymentMethodId !== void 0 && promo.paymentMethodId !== "*" && promo.paymentMethodId !== args.paymentMethodId) {
|
|
2066
|
+
return false;
|
|
2067
|
+
}
|
|
2068
|
+
if (promo.daysOfWeek && promo.daysOfWeek.length > 0 && !promo.daysOfWeek.includes(dayOfWeek)) {
|
|
2069
|
+
return false;
|
|
2070
|
+
}
|
|
2071
|
+
if (args.category !== void 0 && promo.categories && promo.categories.length > 0 && !promo.categories.includes(args.category)) {
|
|
2072
|
+
return false;
|
|
2073
|
+
}
|
|
2074
|
+
if (args.amountArs !== void 0 && promo.minAmountArs !== void 0 && args.amountArs < promo.minAmountArs) {
|
|
2075
|
+
return false;
|
|
2076
|
+
}
|
|
2077
|
+
if (promo.startDate && date < new Date(promo.startDate)) return false;
|
|
2078
|
+
if (promo.endDate && date > new Date(promo.endDate)) return false;
|
|
2079
|
+
return true;
|
|
2080
|
+
});
|
|
2081
|
+
}
|
|
2082
|
+
|
|
1786
2083
|
// src/helpers.ts
|
|
1787
2084
|
function computeMarketplaceFee(amountArs, rule) {
|
|
1788
2085
|
if (amountArs <= 0) return 0;
|
|
@@ -2020,6 +2317,116 @@ function explainPaymentStatus(payment) {
|
|
|
2020
2317
|
}
|
|
2021
2318
|
}
|
|
2022
2319
|
|
|
2320
|
+
// src/pagination.ts
|
|
2321
|
+
async function* paginate(fetchPage, opts) {
|
|
2322
|
+
const pageSize = opts.pageSize ?? 100;
|
|
2323
|
+
const concurrency = Math.max(1, opts.concurrency ?? 1);
|
|
2324
|
+
let yielded = 0;
|
|
2325
|
+
let offset = 0;
|
|
2326
|
+
let knownTotal = void 0;
|
|
2327
|
+
while (true) {
|
|
2328
|
+
if (opts.maxItems !== void 0 && yielded >= opts.maxItems) return;
|
|
2329
|
+
const inFlight = [];
|
|
2330
|
+
for (let i = 0; i < concurrency; i++) {
|
|
2331
|
+
const pageOffset = offset + i * pageSize;
|
|
2332
|
+
if (knownTotal !== void 0 && pageOffset >= knownTotal) break;
|
|
2333
|
+
inFlight.push(fetchPage(pageOffset, pageSize));
|
|
2334
|
+
}
|
|
2335
|
+
if (inFlight.length === 0) return;
|
|
2336
|
+
const pages = await Promise.all(inFlight);
|
|
2337
|
+
let allEmpty = true;
|
|
2338
|
+
for (const page of pages) {
|
|
2339
|
+
const items = opts.extractItems(page);
|
|
2340
|
+
const total = opts.extractTotal?.(page);
|
|
2341
|
+
if (total !== void 0) knownTotal = total;
|
|
2342
|
+
if (items.length > 0) allEmpty = false;
|
|
2343
|
+
for (const item of items) {
|
|
2344
|
+
if (opts.maxItems !== void 0 && yielded >= opts.maxItems) return;
|
|
2345
|
+
yield item;
|
|
2346
|
+
yielded++;
|
|
2347
|
+
}
|
|
2348
|
+
}
|
|
2349
|
+
if (allEmpty) return;
|
|
2350
|
+
offset += pages.length * pageSize;
|
|
2351
|
+
if (knownTotal !== void 0 && offset >= knownTotal) return;
|
|
2352
|
+
}
|
|
2353
|
+
}
|
|
2354
|
+
async function collect(iter) {
|
|
2355
|
+
const out = [];
|
|
2356
|
+
for await (const item of iter) out.push(item);
|
|
2357
|
+
return out;
|
|
2358
|
+
}
|
|
2359
|
+
function paginatePayments(client, filter = {}, opts = {}) {
|
|
2360
|
+
return paginate(
|
|
2361
|
+
(offset, limit) => client.searchPayments({ ...filter, offset, limit }),
|
|
2362
|
+
{
|
|
2363
|
+
extractItems: (p) => p.results ?? [],
|
|
2364
|
+
extractTotal: (p) => p.paging?.total,
|
|
2365
|
+
...opts
|
|
2366
|
+
}
|
|
2367
|
+
);
|
|
2368
|
+
}
|
|
2369
|
+
function paginateSubscriptions(client, filter = {}, opts = {}) {
|
|
2370
|
+
return paginate(
|
|
2371
|
+
(offset, limit) => client.searchPreapprovals({ ...filter, offset, limit }),
|
|
2372
|
+
{
|
|
2373
|
+
extractItems: (p) => p.results,
|
|
2374
|
+
extractTotal: (p) => p.paging.total,
|
|
2375
|
+
...opts
|
|
2376
|
+
}
|
|
2377
|
+
);
|
|
2378
|
+
}
|
|
2379
|
+
function paginateAccountMovements(client, filter = {}, opts = {}) {
|
|
2380
|
+
return paginate(
|
|
2381
|
+
(offset, limit) => client.listAccountMovements({ ...filter, offset, limit }),
|
|
2382
|
+
{
|
|
2383
|
+
extractItems: (p) => p.movements,
|
|
2384
|
+
extractTotal: (p) => p.paging.total,
|
|
2385
|
+
...opts
|
|
2386
|
+
}
|
|
2387
|
+
);
|
|
2388
|
+
}
|
|
2389
|
+
function paginateSettlements(client, filter = {}, opts = {}) {
|
|
2390
|
+
return paginate(
|
|
2391
|
+
(offset, limit) => client.listSettlements({ ...filter, offset, limit }),
|
|
2392
|
+
{
|
|
2393
|
+
extractItems: (p) => p.settlements,
|
|
2394
|
+
extractTotal: (p) => p.paging.total,
|
|
2395
|
+
...opts
|
|
2396
|
+
}
|
|
2397
|
+
);
|
|
2398
|
+
}
|
|
2399
|
+
function paginateMerchantOrders(client, filter = {}, opts = {}) {
|
|
2400
|
+
return paginate(
|
|
2401
|
+
(offset, limit) => client.searchMerchantOrders({ ...filter, offset, limit }),
|
|
2402
|
+
{
|
|
2403
|
+
extractItems: (p) => p.elements,
|
|
2404
|
+
extractTotal: (p) => p.paging.total,
|
|
2405
|
+
...opts
|
|
2406
|
+
}
|
|
2407
|
+
);
|
|
2408
|
+
}
|
|
2409
|
+
function paginateSubscriptionPlans(client, filter = {}, opts = {}) {
|
|
2410
|
+
return paginate(
|
|
2411
|
+
(offset, limit) => client.listSubscriptionPlans({ ...filter, offset, limit }),
|
|
2412
|
+
{
|
|
2413
|
+
extractItems: (p) => p.results,
|
|
2414
|
+
extractTotal: (p) => p.paging.total,
|
|
2415
|
+
...opts
|
|
2416
|
+
}
|
|
2417
|
+
);
|
|
2418
|
+
}
|
|
2419
|
+
function paginateSubscriptionPayments(client, preapprovalId, opts = {}) {
|
|
2420
|
+
return paginate(
|
|
2421
|
+
(offset, limit) => client.listSubscriptionPayments(preapprovalId, { offset, limit }),
|
|
2422
|
+
{
|
|
2423
|
+
extractItems: (p) => p.results,
|
|
2424
|
+
extractTotal: (p) => p.paging.total,
|
|
2425
|
+
...opts
|
|
2426
|
+
}
|
|
2427
|
+
);
|
|
2428
|
+
}
|
|
2429
|
+
|
|
2023
2430
|
// src/test-cards.ts
|
|
2024
2431
|
var TEST_CARDS_AR = {
|
|
2025
2432
|
VISA_CREDIT: {
|
|
@@ -2147,8 +2554,40 @@ function analyze3DS(payment) {
|
|
|
2147
2554
|
description: "No se pudo determinar el estado 3DS \u2014 revisar payment.three_d_secure_mode + payment.status_detail manualmente."
|
|
2148
2555
|
};
|
|
2149
2556
|
}
|
|
2557
|
+
async function confirmChallengeAndPoll(client, paymentId, options = {}) {
|
|
2558
|
+
const maxAttempts = options.maxAttempts ?? 5;
|
|
2559
|
+
const interval = options.pollIntervalMs ?? 1e3;
|
|
2560
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
2561
|
+
if (options.signal?.aborted) {
|
|
2562
|
+
const payment3 = await client.getPayment(paymentId);
|
|
2563
|
+
return { payment: payment3, threeDs: analyze3DS(payment3), resolved: false, attempts: attempt };
|
|
2564
|
+
}
|
|
2565
|
+
const payment2 = await client.getPayment(paymentId);
|
|
2566
|
+
const threeDs = analyze3DS(payment2);
|
|
2567
|
+
const stillWaiting = threeDs.status === "challenge_required" || payment2.status === "pending" || payment2.status === "in_process";
|
|
2568
|
+
if (!stillWaiting) {
|
|
2569
|
+
return { payment: payment2, threeDs, resolved: true, attempts: attempt };
|
|
2570
|
+
}
|
|
2571
|
+
if (attempt < maxAttempts) {
|
|
2572
|
+
await new Promise((resolve) => {
|
|
2573
|
+
const timer = setTimeout(resolve, interval);
|
|
2574
|
+
options.signal?.addEventListener(
|
|
2575
|
+
"abort",
|
|
2576
|
+
() => {
|
|
2577
|
+
clearTimeout(timer);
|
|
2578
|
+
resolve(void 0);
|
|
2579
|
+
},
|
|
2580
|
+
{ once: true }
|
|
2581
|
+
);
|
|
2582
|
+
});
|
|
2583
|
+
}
|
|
2584
|
+
}
|
|
2585
|
+
const payment = await client.getPayment(paymentId);
|
|
2586
|
+
return { payment, threeDs: analyze3DS(payment), resolved: false, attempts: maxAttempts };
|
|
2587
|
+
}
|
|
2150
2588
|
|
|
2151
2589
|
// src/webhook.ts
|
|
2590
|
+
init_crypto();
|
|
2152
2591
|
function parseWebhookEvent(body, searchParams) {
|
|
2153
2592
|
const parseResult = WebhookBodySchema.safeParse(body ?? {});
|
|
2154
2593
|
const parsedBody = parseResult.success ? parseResult.data : {};
|
|
@@ -2298,7 +2737,16 @@ var DEFAULT_DESCRIPTIONS = {
|
|
|
2298
2737
|
cancel_point_payment_intent: "Cancel an OPEN point payment intent before the buyer interacts with the device. ONLY WORKS while state='OPEN' \u2014 once the buyer taps, you can't cancel; refund_payment after the fact instead.",
|
|
2299
2738
|
// ── Pure helpers (v0.7) ──────────────────────────────────────────────────
|
|
2300
2739
|
compute_marketplace_fee: "PURE HELPER (no network) \u2014 given a transaction amount + fee rule (% or flat ARS, with optional min/max floors), returns the exact `marketplace_fee` value in ARS to pass to create_order or create_payment_preference. USE WHEN your platform takes a commission and you need to compute the exact fee per transaction. Examples: { percent: 5, minArs: 50, maxArs: 5000 } for percentage with floor + cap; { flatArs: 200, percent: 2 } for fixed + percentage.",
|
|
2301
|
-
explain_payment_status: "PURE HELPER (no network) \u2014 given a Payment object (from get_payment / create_payment / handle_webhook), returns { summary, recommendedAction, final, paid, retryable } in Spanish. Translates MP's cryptic status_detail codes to plain Spanish + actionable guidance ('reintentar con otra tarjeta' vs 'esperar webhook' vs 'estado final'). USE THIS instead of having to memorize 30+ status_detail codes \u2014 surface summary + recommendedAction directly to the user."
|
|
2740
|
+
explain_payment_status: "PURE HELPER (no network) \u2014 given a Payment object (from get_payment / create_payment / handle_webhook), returns { summary, recommendedAction, final, paid, retryable } in Spanish. Translates MP's cryptic status_detail codes to plain Spanish + actionable guidance ('reintentar con otra tarjeta' vs 'esperar webhook' vs 'estado final'). USE THIS instead of having to memorize 30+ status_detail codes \u2014 surface summary + recommendedAction directly to the user.",
|
|
2741
|
+
// ── v0.9 — Health check + observability ──────────────────────────────────
|
|
2742
|
+
mp_health_check: "Liveness probe against MP. Returns { ok, latencyMs, userId, circuit }. USE THIS as the first call in long-running agent workflows to verify (a) network path to MP is up, (b) accessToken is valid, (c) MP is responding. Circuit-breaker state included when configured \u2014 surface to ops dashboards. Returns ok=false instead of throwing \u2014 safe to call in monitoring loops without try/catch.",
|
|
2743
|
+
// ── v0.10 — AR issuer cuotas promos (pure) ───────────────────────────────
|
|
2744
|
+
find_applicable_promos: "PURE HELPER (no network, sub-ms) \u2014 returns the 'cuotas sin inter\xE9s' promotions applicable to a given (issuer, paymentMethodId, amount, category, date) tuple. Includes the federal Ahora 3/6/12/18/24/30 program AND issuer-specific deals (Naranja con Galicia los jueves, Santander Amex en supermercados los martes, etc.). USE THIS BEFORE checkout to surface 'pag\xE1 en 12 cuotas sin inter\xE9s con tu Galicia' hints to the buyer \u2014 drives conversion. Returns an array of CuotasPromo objects; the `description` field is in Spanish and ALWAYS surface verbatim. Catalog updated quarterly.",
|
|
2745
|
+
// ── v0.10 — 3DS challenge resolution ────────────────────────────────────
|
|
2746
|
+
confirm_3ds_challenge: "After the buyer completes a 3DS challenge (redirected back from challengeUrl), call this to poll MP and confirm whether the payment is now resolved. Polls get_payment up to N times with exponential backoff. Returns { payment, threeDs, resolved, attempts }. USE THIS as the FINAL step in the 3DS flow (after analyze_payment_3ds detected a challenge_required). Without confirming, the payment stays in 'pending' indefinitely from the buyer's perspective.",
|
|
2747
|
+
// ── v0.10 — Auto-paginate variants ──────────────────────────────────────
|
|
2748
|
+
search_payments_all: "Collect ALL payments matching a filter \u2014 auto-paginates under the hood. Returns an array (NOT paginated) so the agent doesn't have to manage offset/limit loops manually. SAFETY: pass `max_items` to cap; without it, MP traversal is bounded by the toolkit's internal max (10,000 items) to prevent runaway iterations. USE WHEN the agent needs to enumerate everything (e.g., monthly reconciliation 'all approved payments in March'). For agent flows that only need 'first N matches', pass `max_items` directly.",
|
|
2749
|
+
list_settlements_all: "Collect ALL settlements matching a filter \u2014 auto-paginates. Pass `max_items` to cap. Use for monthly bank-conciliation reports."
|
|
2302
2750
|
};
|
|
2303
2751
|
function mercadoPagoTools(client, options) {
|
|
2304
2752
|
const desc = (name) => options.descriptions?.[name] ?? DEFAULT_DESCRIPTIONS[name];
|
|
@@ -4056,6 +4504,21 @@ function mercadoPagoTools(client, options) {
|
|
|
4056
4504
|
};
|
|
4057
4505
|
}
|
|
4058
4506
|
}),
|
|
4507
|
+
mp_health_check: tool({
|
|
4508
|
+
description: desc("mp_health_check"),
|
|
4509
|
+
inputSchema: z.object({
|
|
4510
|
+
timeout_ms: z.number().int().positive().max(3e4).optional().describe("Cap the wait time (default 5s). Use lower for status-page polling.")
|
|
4511
|
+
}),
|
|
4512
|
+
execute: async ({ timeout_ms }) => {
|
|
4513
|
+
const controller = new AbortController();
|
|
4514
|
+
const t = setTimeout(() => controller.abort(), timeout_ms ?? 5e3);
|
|
4515
|
+
try {
|
|
4516
|
+
return await client.healthCheck(controller.signal);
|
|
4517
|
+
} finally {
|
|
4518
|
+
clearTimeout(t);
|
|
4519
|
+
}
|
|
4520
|
+
}
|
|
4521
|
+
}),
|
|
4059
4522
|
explain_payment_status: tool({
|
|
4060
4523
|
description: desc("explain_payment_status"),
|
|
4061
4524
|
inputSchema: z.object({
|
|
@@ -4082,6 +4545,101 @@ function mercadoPagoTools(client, options) {
|
|
|
4082
4545
|
...explanation
|
|
4083
4546
|
};
|
|
4084
4547
|
}
|
|
4548
|
+
}),
|
|
4549
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
4550
|
+
// v0.10 — AR issuer promos (pure)
|
|
4551
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
4552
|
+
find_applicable_promos: tool({
|
|
4553
|
+
description: desc("find_applicable_promos"),
|
|
4554
|
+
inputSchema: z.object({
|
|
4555
|
+
issuer: z.string().optional().describe("Issuer name (e.g. 'Banco Galicia')"),
|
|
4556
|
+
payment_method_id: z.string().optional().describe("e.g. 'visa', 'master', 'naranja'"),
|
|
4557
|
+
amount_ars: z.number().positive().optional(),
|
|
4558
|
+
category: z.enum([
|
|
4559
|
+
"electronics",
|
|
4560
|
+
"appliances",
|
|
4561
|
+
"clothing",
|
|
4562
|
+
"supermarket",
|
|
4563
|
+
"travel",
|
|
4564
|
+
"education",
|
|
4565
|
+
"health",
|
|
4566
|
+
"general"
|
|
4567
|
+
]).optional(),
|
|
4568
|
+
date: z.string().datetime().optional(),
|
|
4569
|
+
include_ahora_program: z.boolean().optional()
|
|
4570
|
+
}),
|
|
4571
|
+
execute: async (input) => {
|
|
4572
|
+
const args = {};
|
|
4573
|
+
if (input.issuer !== void 0) args.issuer = input.issuer;
|
|
4574
|
+
if (input.payment_method_id !== void 0) args.paymentMethodId = input.payment_method_id;
|
|
4575
|
+
if (input.amount_ars !== void 0) args.amountArs = input.amount_ars;
|
|
4576
|
+
if (input.category !== void 0) args.category = input.category;
|
|
4577
|
+
if (input.date !== void 0) args.date = new Date(input.date);
|
|
4578
|
+
if (input.include_ahora_program !== void 0) args.includeAhoraProgram = input.include_ahora_program;
|
|
4579
|
+
const promos = findApplicablePromos(args);
|
|
4580
|
+
return { ok: true, count: promos.length, promos };
|
|
4581
|
+
}
|
|
4582
|
+
}),
|
|
4583
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
4584
|
+
// v0.10 — 3DS challenge resolution (poll-and-confirm)
|
|
4585
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
4586
|
+
confirm_3ds_challenge: tool({
|
|
4587
|
+
description: desc("confirm_3ds_challenge"),
|
|
4588
|
+
inputSchema: z.object({
|
|
4589
|
+
payment_id: z.string(),
|
|
4590
|
+
max_attempts: z.number().int().positive().max(20).optional(),
|
|
4591
|
+
poll_interval_ms: z.number().int().positive().max(1e4).optional()
|
|
4592
|
+
}),
|
|
4593
|
+
execute: async ({ payment_id, max_attempts, poll_interval_ms }) => {
|
|
4594
|
+
const args = {};
|
|
4595
|
+
if (max_attempts !== void 0) args.maxAttempts = max_attempts;
|
|
4596
|
+
if (poll_interval_ms !== void 0) args.pollIntervalMs = poll_interval_ms;
|
|
4597
|
+
return confirmChallengeAndPoll(client, payment_id, args);
|
|
4598
|
+
}
|
|
4599
|
+
}),
|
|
4600
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
4601
|
+
// v0.10 — Auto-paginate variants (collect-all)
|
|
4602
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
4603
|
+
search_payments_all: tool({
|
|
4604
|
+
description: desc("search_payments_all"),
|
|
4605
|
+
inputSchema: z.object({
|
|
4606
|
+
status: z.string().optional(),
|
|
4607
|
+
external_reference: z.string().optional(),
|
|
4608
|
+
from: z.string().optional(),
|
|
4609
|
+
to: z.string().optional(),
|
|
4610
|
+
max_items: z.number().int().positive().max(1e4).optional().describe("Cap on total items returned (default 10,000 hard limit).")
|
|
4611
|
+
}),
|
|
4612
|
+
execute: async ({ max_items, ...filter }) => {
|
|
4613
|
+
const filterClean = {};
|
|
4614
|
+
for (const [k, v] of Object.entries(filter)) {
|
|
4615
|
+
if (v !== void 0) filterClean[k] = v;
|
|
4616
|
+
}
|
|
4617
|
+
const opts = {};
|
|
4618
|
+
if (max_items !== void 0) opts.maxItems = max_items;
|
|
4619
|
+
else opts.maxItems = 1e4;
|
|
4620
|
+
const all = await collect(paginatePayments(client, filterClean, opts));
|
|
4621
|
+
return { ok: true, count: all.length, payments: all };
|
|
4622
|
+
}
|
|
4623
|
+
}),
|
|
4624
|
+
list_settlements_all: tool({
|
|
4625
|
+
description: desc("list_settlements_all"),
|
|
4626
|
+
inputSchema: z.object({
|
|
4627
|
+
from: z.string().optional(),
|
|
4628
|
+
to: z.string().optional(),
|
|
4629
|
+
status: z.string().optional(),
|
|
4630
|
+
max_items: z.number().int().positive().max(1e4).optional()
|
|
4631
|
+
}),
|
|
4632
|
+
execute: async ({ max_items, ...filter }) => {
|
|
4633
|
+
const filterClean = {};
|
|
4634
|
+
if (filter.from !== void 0) filterClean.from = filter.from;
|
|
4635
|
+
if (filter.to !== void 0) filterClean.to = filter.to;
|
|
4636
|
+
if (filter.status !== void 0) filterClean.status = filter.status;
|
|
4637
|
+
const opts = {};
|
|
4638
|
+
if (max_items !== void 0) opts.maxItems = max_items;
|
|
4639
|
+
else opts.maxItems = 1e4;
|
|
4640
|
+
const all = await collect(paginateSettlements(client, filterClean, opts));
|
|
4641
|
+
return { ok: true, count: all.length, settlements: all };
|
|
4642
|
+
}
|
|
4085
4643
|
})
|
|
4086
4644
|
};
|
|
4087
4645
|
}
|
|
@@ -4146,6 +4704,452 @@ var InMemoryIdempotencyCache = class {
|
|
|
4146
4704
|
}
|
|
4147
4705
|
};
|
|
4148
4706
|
|
|
4149
|
-
|
|
4707
|
+
// src/circuit-breaker.ts
|
|
4708
|
+
var CircuitOpenError = class extends Error {
|
|
4709
|
+
constructor(retryAfterMs, consecutiveFailures) {
|
|
4710
|
+
super(
|
|
4711
|
+
`Circuit breaker is OPEN \u2014 failing fast. Retry in ${Math.ceil(
|
|
4712
|
+
retryAfterMs / 1e3
|
|
4713
|
+
)}s. Consecutive upstream failures: ${consecutiveFailures}.`
|
|
4714
|
+
);
|
|
4715
|
+
this.retryAfterMs = retryAfterMs;
|
|
4716
|
+
this.consecutiveFailures = consecutiveFailures;
|
|
4717
|
+
this.name = "CircuitOpenError";
|
|
4718
|
+
}
|
|
4719
|
+
retryAfterMs;
|
|
4720
|
+
consecutiveFailures;
|
|
4721
|
+
};
|
|
4722
|
+
var CircuitBreaker = class {
|
|
4723
|
+
state = "CLOSED";
|
|
4724
|
+
consecutiveFailures = 0;
|
|
4725
|
+
halfOpenSuccesses = 0;
|
|
4726
|
+
openedAt = 0;
|
|
4727
|
+
/** Timestamps of failures within the monitoring window. */
|
|
4728
|
+
failureWindow = [];
|
|
4729
|
+
failureThreshold;
|
|
4730
|
+
successThreshold;
|
|
4731
|
+
resetTimeoutMs;
|
|
4732
|
+
monitoringWindowMs;
|
|
4733
|
+
onStateChange;
|
|
4734
|
+
isFailureFn;
|
|
4735
|
+
now;
|
|
4736
|
+
constructor(opts = {}) {
|
|
4737
|
+
this.failureThreshold = opts.failureThreshold ?? 5;
|
|
4738
|
+
this.successThreshold = opts.successThreshold ?? 2;
|
|
4739
|
+
this.resetTimeoutMs = opts.resetTimeoutMs ?? 3e4;
|
|
4740
|
+
this.monitoringWindowMs = opts.monitoringWindowMs ?? 6e4;
|
|
4741
|
+
this.onStateChange = opts.onStateChange ?? null;
|
|
4742
|
+
this.isFailureFn = opts.isFailure ?? (() => true);
|
|
4743
|
+
this.now = opts.now ?? Date.now;
|
|
4744
|
+
}
|
|
4745
|
+
/** Read the current state. Useful for health checks + metrics. */
|
|
4746
|
+
getState() {
|
|
4747
|
+
if (this.state === "OPEN" && this.now() - this.openedAt >= this.resetTimeoutMs) {
|
|
4748
|
+
this.transitionTo("HALF_OPEN");
|
|
4749
|
+
}
|
|
4750
|
+
return this.state;
|
|
4751
|
+
}
|
|
4752
|
+
/** Read diagnostic state for health checks + dashboards. */
|
|
4753
|
+
getStats() {
|
|
4754
|
+
const state = this.getState();
|
|
4755
|
+
const msSinceOpened = this.openedAt > 0 ? this.now() - this.openedAt : null;
|
|
4756
|
+
const msUntilHalfOpen = state === "OPEN" && msSinceOpened !== null ? Math.max(0, this.resetTimeoutMs - msSinceOpened) : null;
|
|
4757
|
+
return {
|
|
4758
|
+
state,
|
|
4759
|
+
consecutiveFailures: this.consecutiveFailures,
|
|
4760
|
+
failuresInWindow: this.failuresInCurrentWindow(),
|
|
4761
|
+
msSinceOpened,
|
|
4762
|
+
msUntilHalfOpen
|
|
4763
|
+
};
|
|
4764
|
+
}
|
|
4765
|
+
/**
|
|
4766
|
+
* Execute `fn` under the breaker's protection.
|
|
4767
|
+
* - If the breaker is OPEN, throws `CircuitOpenError` immediately.
|
|
4768
|
+
* - If `fn` succeeds, may transition HALF_OPEN → CLOSED.
|
|
4769
|
+
* - If `fn` fails (and the error counts as a failure), records the
|
|
4770
|
+
* failure; may transition CLOSED → OPEN or HALF_OPEN → OPEN.
|
|
4771
|
+
*/
|
|
4772
|
+
async execute(fn) {
|
|
4773
|
+
const state = this.getState();
|
|
4774
|
+
if (state === "OPEN") {
|
|
4775
|
+
const elapsed = this.now() - this.openedAt;
|
|
4776
|
+
throw new CircuitOpenError(
|
|
4777
|
+
Math.max(0, this.resetTimeoutMs - elapsed),
|
|
4778
|
+
this.consecutiveFailures
|
|
4779
|
+
);
|
|
4780
|
+
}
|
|
4781
|
+
try {
|
|
4782
|
+
const result = await fn();
|
|
4783
|
+
this.recordSuccess();
|
|
4784
|
+
return result;
|
|
4785
|
+
} catch (err) {
|
|
4786
|
+
if (this.isFailureFn(err)) {
|
|
4787
|
+
this.recordFailure(err);
|
|
4788
|
+
}
|
|
4789
|
+
throw err;
|
|
4790
|
+
}
|
|
4791
|
+
}
|
|
4792
|
+
/** Manually force the breaker open. Useful for runbook / manual ops. */
|
|
4793
|
+
trip(reason) {
|
|
4794
|
+
if (this.state !== "OPEN") {
|
|
4795
|
+
this.transitionTo("OPEN", reason);
|
|
4796
|
+
}
|
|
4797
|
+
}
|
|
4798
|
+
/** Manually reset the breaker to CLOSED. */
|
|
4799
|
+
reset() {
|
|
4800
|
+
this.consecutiveFailures = 0;
|
|
4801
|
+
this.halfOpenSuccesses = 0;
|
|
4802
|
+
this.failureWindow = [];
|
|
4803
|
+
if (this.state !== "CLOSED") {
|
|
4804
|
+
this.transitionTo("CLOSED");
|
|
4805
|
+
}
|
|
4806
|
+
}
|
|
4807
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
4808
|
+
// Internal
|
|
4809
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
4810
|
+
recordSuccess() {
|
|
4811
|
+
this.consecutiveFailures = 0;
|
|
4812
|
+
if (this.state === "HALF_OPEN") {
|
|
4813
|
+
this.halfOpenSuccesses++;
|
|
4814
|
+
if (this.halfOpenSuccesses >= this.successThreshold) {
|
|
4815
|
+
this.transitionTo("CLOSED");
|
|
4816
|
+
}
|
|
4817
|
+
}
|
|
4818
|
+
}
|
|
4819
|
+
recordFailure(cause) {
|
|
4820
|
+
this.consecutiveFailures++;
|
|
4821
|
+
this.failureWindow.push(this.now());
|
|
4822
|
+
this.pruneWindow();
|
|
4823
|
+
if (this.state === "HALF_OPEN") {
|
|
4824
|
+
this.transitionTo("OPEN", cause);
|
|
4825
|
+
return;
|
|
4826
|
+
}
|
|
4827
|
+
if (this.state === "CLOSED" && this.failuresInCurrentWindow() >= this.failureThreshold) {
|
|
4828
|
+
this.transitionTo("OPEN", cause);
|
|
4829
|
+
}
|
|
4830
|
+
}
|
|
4831
|
+
transitionTo(to, cause) {
|
|
4832
|
+
const from = this.state;
|
|
4833
|
+
if (from === to) return;
|
|
4834
|
+
this.state = to;
|
|
4835
|
+
if (to === "OPEN") {
|
|
4836
|
+
this.openedAt = this.now();
|
|
4837
|
+
this.halfOpenSuccesses = 0;
|
|
4838
|
+
} else if (to === "CLOSED") {
|
|
4839
|
+
this.consecutiveFailures = 0;
|
|
4840
|
+
this.halfOpenSuccesses = 0;
|
|
4841
|
+
this.failureWindow = [];
|
|
4842
|
+
this.openedAt = 0;
|
|
4843
|
+
} else if (to === "HALF_OPEN") {
|
|
4844
|
+
this.halfOpenSuccesses = 0;
|
|
4845
|
+
}
|
|
4846
|
+
this.onStateChange?.({
|
|
4847
|
+
from,
|
|
4848
|
+
to,
|
|
4849
|
+
cause,
|
|
4850
|
+
consecutiveFailures: this.consecutiveFailures
|
|
4851
|
+
});
|
|
4852
|
+
}
|
|
4853
|
+
pruneWindow() {
|
|
4854
|
+
const cutoff = this.now() - this.monitoringWindowMs;
|
|
4855
|
+
while (this.failureWindow.length > 0 && this.failureWindow[0] < cutoff) {
|
|
4856
|
+
this.failureWindow.shift();
|
|
4857
|
+
}
|
|
4858
|
+
}
|
|
4859
|
+
failuresInCurrentWindow() {
|
|
4860
|
+
this.pruneWindow();
|
|
4861
|
+
return this.failureWindow.length;
|
|
4862
|
+
}
|
|
4863
|
+
};
|
|
4864
|
+
|
|
4865
|
+
// src/audit.ts
|
|
4866
|
+
var InMemoryAuditLog = class {
|
|
4867
|
+
entries = [];
|
|
4868
|
+
async append(entry) {
|
|
4869
|
+
this.entries.push(entry);
|
|
4870
|
+
}
|
|
4871
|
+
async query(filter) {
|
|
4872
|
+
const filtered = this.entries.filter((e) => {
|
|
4873
|
+
if (filter.actor && e.actor !== filter.actor) return false;
|
|
4874
|
+
if (filter.operation && e.operation !== filter.operation) return false;
|
|
4875
|
+
if (filter.tenantId && e.tenantId !== filter.tenantId) return false;
|
|
4876
|
+
if (filter.from && e.timestamp < filter.from) return false;
|
|
4877
|
+
if (filter.to && e.timestamp > filter.to) return false;
|
|
4878
|
+
return true;
|
|
4879
|
+
});
|
|
4880
|
+
return filter.limit ? filtered.slice(0, filter.limit) : filtered;
|
|
4881
|
+
}
|
|
4882
|
+
/** All entries (test helper, not part of the adapter interface). */
|
|
4883
|
+
all() {
|
|
4884
|
+
return [...this.entries];
|
|
4885
|
+
}
|
|
4886
|
+
reset() {
|
|
4887
|
+
this.entries.length = 0;
|
|
4888
|
+
}
|
|
4889
|
+
};
|
|
4890
|
+
var AuditLogger = class {
|
|
4891
|
+
adapter;
|
|
4892
|
+
defaultActor;
|
|
4893
|
+
redact;
|
|
4894
|
+
hash;
|
|
4895
|
+
constructor(options) {
|
|
4896
|
+
this.adapter = options.adapter;
|
|
4897
|
+
this.defaultActor = options.defaultActor ?? "unknown";
|
|
4898
|
+
this.redact = options.redact ?? true;
|
|
4899
|
+
this.hash = options.hashFn ?? defaultHasher;
|
|
4900
|
+
}
|
|
4901
|
+
/**
|
|
4902
|
+
* Wrap a tool execute() function with auto-audit. The returned function:
|
|
4903
|
+
* 1. Computes inputHash before the call.
|
|
4904
|
+
* 2. Invokes the original execute().
|
|
4905
|
+
* 3. On success, appends an entry with outcome="ok" + resourceId.
|
|
4906
|
+
* 4. On failure, appends an entry with outcome="error" + errorCode/Message.
|
|
4907
|
+
* 5. Re-throws the error transparently.
|
|
4908
|
+
*/
|
|
4909
|
+
async record(args) {
|
|
4910
|
+
const t0 = Date.now();
|
|
4911
|
+
const inputHash = await this.hash(stableStringify(args.input));
|
|
4912
|
+
try {
|
|
4913
|
+
const result = await args.fn();
|
|
4914
|
+
const resourceId = (args.extractResourceId ?? defaultExtractResourceId)(result);
|
|
4915
|
+
const entry = {
|
|
4916
|
+
id: `mpaud-${(/* @__PURE__ */ new Date()).toISOString()}-${Math.random().toString(36).slice(2, 10)}`,
|
|
4917
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
4918
|
+
operation: args.operation,
|
|
4919
|
+
actor: args.actor ?? this.defaultActor,
|
|
4920
|
+
inputHash,
|
|
4921
|
+
outcome: "ok",
|
|
4922
|
+
durationMs: Date.now() - t0
|
|
4923
|
+
};
|
|
4924
|
+
if (args.tenantId !== void 0) entry.tenantId = args.tenantId;
|
|
4925
|
+
if (resourceId !== void 0) entry.resourceId = resourceId;
|
|
4926
|
+
if (args.idempotencyKey !== void 0) entry.idempotencyKey = args.idempotencyKey;
|
|
4927
|
+
if (!this.redact) entry.inputRaw = args.input;
|
|
4928
|
+
await this.adapter.append(entry);
|
|
4929
|
+
return result;
|
|
4930
|
+
} catch (err) {
|
|
4931
|
+
const entry = {
|
|
4932
|
+
id: `mpaud-${(/* @__PURE__ */ new Date()).toISOString()}-${Math.random().toString(36).slice(2, 10)}`,
|
|
4933
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
4934
|
+
operation: args.operation,
|
|
4935
|
+
actor: args.actor ?? this.defaultActor,
|
|
4936
|
+
inputHash,
|
|
4937
|
+
outcome: "error",
|
|
4938
|
+
errorCode: extractErrorCode(err),
|
|
4939
|
+
errorMessage: err instanceof Error ? err.message : String(err),
|
|
4940
|
+
durationMs: Date.now() - t0
|
|
4941
|
+
};
|
|
4942
|
+
if (args.tenantId !== void 0) entry.tenantId = args.tenantId;
|
|
4943
|
+
if (args.idempotencyKey !== void 0) entry.idempotencyKey = args.idempotencyKey;
|
|
4944
|
+
if (!this.redact) entry.inputRaw = args.input;
|
|
4945
|
+
await this.adapter.append(entry);
|
|
4946
|
+
throw err;
|
|
4947
|
+
}
|
|
4948
|
+
}
|
|
4949
|
+
};
|
|
4950
|
+
async function defaultHasher(input) {
|
|
4951
|
+
const { sha256Hex: sha256Hex2 } = await Promise.resolve().then(() => (init_crypto(), crypto_exports));
|
|
4952
|
+
return sha256Hex2(input);
|
|
4953
|
+
}
|
|
4954
|
+
function stableStringify(obj) {
|
|
4955
|
+
return JSON.stringify(obj, (_, v) => {
|
|
4956
|
+
if (v && typeof v === "object" && !Array.isArray(v)) {
|
|
4957
|
+
const sorted = {};
|
|
4958
|
+
for (const k of Object.keys(v).sort()) {
|
|
4959
|
+
sorted[k] = v[k];
|
|
4960
|
+
}
|
|
4961
|
+
return sorted;
|
|
4962
|
+
}
|
|
4963
|
+
return v;
|
|
4964
|
+
});
|
|
4965
|
+
}
|
|
4966
|
+
function defaultExtractResourceId(result) {
|
|
4967
|
+
if (!result || typeof result !== "object") return void 0;
|
|
4968
|
+
const r = result;
|
|
4969
|
+
for (const key of [
|
|
4970
|
+
"id",
|
|
4971
|
+
"payment_id",
|
|
4972
|
+
"subscription_id",
|
|
4973
|
+
"order_id",
|
|
4974
|
+
"preference_id",
|
|
4975
|
+
"customer_id",
|
|
4976
|
+
"refund_id",
|
|
4977
|
+
"store_id",
|
|
4978
|
+
"pos_id",
|
|
4979
|
+
"merchant_order_id",
|
|
4980
|
+
"intent_id",
|
|
4981
|
+
"device_id"
|
|
4982
|
+
]) {
|
|
4983
|
+
const v = r[key];
|
|
4984
|
+
if (typeof v === "string" || typeof v === "number") return String(v);
|
|
4985
|
+
}
|
|
4986
|
+
return void 0;
|
|
4987
|
+
}
|
|
4988
|
+
function extractErrorCode(err) {
|
|
4989
|
+
if (err && typeof err === "object") {
|
|
4990
|
+
const e = err;
|
|
4991
|
+
return e.code ?? e.name ?? "unknown_error";
|
|
4992
|
+
}
|
|
4993
|
+
return "unknown_error";
|
|
4994
|
+
}
|
|
4995
|
+
|
|
4996
|
+
// src/webhook-dedup.ts
|
|
4997
|
+
var WebhookDedup = class {
|
|
4998
|
+
cache;
|
|
4999
|
+
ttlSeconds;
|
|
5000
|
+
onDuplicate;
|
|
5001
|
+
constructor(opts) {
|
|
5002
|
+
this.cache = opts.cache;
|
|
5003
|
+
this.ttlSeconds = opts.ttlSeconds ?? 7 * 24 * 3600;
|
|
5004
|
+
this.onDuplicate = opts.onDuplicate;
|
|
5005
|
+
}
|
|
5006
|
+
/**
|
|
5007
|
+
* Check whether a webhook delivery has been seen before. If new, mark it
|
|
5008
|
+
* as seen (so subsequent retries return shouldProcess=false). If seen,
|
|
5009
|
+
* return shouldProcess=false WITHOUT marking again.
|
|
5010
|
+
*
|
|
5011
|
+
* **Important**: this method is not atomic across concurrent calls — two
|
|
5012
|
+
* simultaneous deliveries with the same key may both pass shouldProcess=true.
|
|
5013
|
+
* For strict at-most-once processing, follow with a transaction or use a
|
|
5014
|
+
* cache that supports `setNX`-style semantics (Redis, Cloudflare KV with
|
|
5015
|
+
* conditional writes).
|
|
5016
|
+
*
|
|
5017
|
+
* For most webhook handlers this race is acceptable: even if two get
|
|
5018
|
+
* through, the downstream business logic (e.g., "charge if not already
|
|
5019
|
+
* charged") will be idempotent on its own.
|
|
5020
|
+
*/
|
|
5021
|
+
async check(args) {
|
|
5022
|
+
const deliveryKey = this.deriveKey(args);
|
|
5023
|
+
const seen = await this.cache.get(deliveryKey);
|
|
5024
|
+
if (seen) {
|
|
5025
|
+
this.onDuplicate?.(deliveryKey);
|
|
5026
|
+
return { shouldProcess: false, deliveryKey };
|
|
5027
|
+
}
|
|
5028
|
+
await this.cache.set(deliveryKey, true, this.ttlSeconds);
|
|
5029
|
+
return { shouldProcess: true, deliveryKey };
|
|
5030
|
+
}
|
|
5031
|
+
/**
|
|
5032
|
+
* Manually mark a delivery as processed. Call this AFTER your business
|
|
5033
|
+
* logic succeeds — useful when you want to control when the dedup
|
|
5034
|
+
* marker is written (e.g., only on success).
|
|
5035
|
+
*
|
|
5036
|
+
* Combined with calling `check()` BEFORE the work, this gives "at-least-once"
|
|
5037
|
+
* semantics: failed processing → no marker → retry will be processed again.
|
|
5038
|
+
*/
|
|
5039
|
+
async markProcessed(args) {
|
|
5040
|
+
const deliveryKey = this.deriveKey(args);
|
|
5041
|
+
await this.cache.set(deliveryKey, true, this.ttlSeconds);
|
|
5042
|
+
}
|
|
5043
|
+
/**
|
|
5044
|
+
* Variant of `check` that doesn't mark on first sight — caller must
|
|
5045
|
+
* explicitly `markProcessed` when their business logic succeeds.
|
|
5046
|
+
* Use this for at-least-once semantics (each delivery processed at
|
|
5047
|
+
* least once, possibly more if processing fails before mark).
|
|
5048
|
+
*/
|
|
5049
|
+
async peekIsDuplicate(args) {
|
|
5050
|
+
const deliveryKey = this.deriveKey(args);
|
|
5051
|
+
const seen = await this.cache.get(deliveryKey);
|
|
5052
|
+
if (seen) this.onDuplicate?.(deliveryKey);
|
|
5053
|
+
return { shouldProcess: !seen, deliveryKey };
|
|
5054
|
+
}
|
|
5055
|
+
deriveKey(args) {
|
|
5056
|
+
return `mp:webhook:${args.topic}:${args.dataId}:${args.requestId ?? "noreqid"}`;
|
|
5057
|
+
}
|
|
5058
|
+
};
|
|
5059
|
+
|
|
5060
|
+
// src/rate-limiter.ts
|
|
5061
|
+
var RateLimitTimeoutError = class extends Error {
|
|
5062
|
+
constructor(waitedMs) {
|
|
5063
|
+
super(`Rate limit acquire timed out after ${waitedMs}ms.`);
|
|
5064
|
+
this.waitedMs = waitedMs;
|
|
5065
|
+
this.name = "RateLimitTimeoutError";
|
|
5066
|
+
}
|
|
5067
|
+
waitedMs;
|
|
5068
|
+
};
|
|
5069
|
+
var TokenBucketRateLimiter = class {
|
|
5070
|
+
tokens;
|
|
5071
|
+
lastRefill;
|
|
5072
|
+
capacity;
|
|
5073
|
+
refillPerSecond;
|
|
5074
|
+
adaptive;
|
|
5075
|
+
acquireTimeoutMs;
|
|
5076
|
+
now;
|
|
5077
|
+
constructor(opts = {}) {
|
|
5078
|
+
this.capacity = opts.capacity ?? 50;
|
|
5079
|
+
this.refillPerSecond = opts.refillPerSecond ?? 25;
|
|
5080
|
+
this.adaptive = opts.adaptive ?? true;
|
|
5081
|
+
this.acquireTimeoutMs = opts.acquireTimeoutMs ?? 3e4;
|
|
5082
|
+
this.now = opts.now ?? Date.now;
|
|
5083
|
+
this.tokens = this.capacity;
|
|
5084
|
+
this.lastRefill = this.now();
|
|
5085
|
+
}
|
|
5086
|
+
/**
|
|
5087
|
+
* Acquire a token. Resolves immediately if tokens are available;
|
|
5088
|
+
* otherwise waits until one is. Rejects with `RateLimitTimeoutError`
|
|
5089
|
+
* if the wait exceeds `acquireTimeoutMs`.
|
|
5090
|
+
*/
|
|
5091
|
+
async acquire() {
|
|
5092
|
+
this.refill();
|
|
5093
|
+
if (this.tokens >= 1) {
|
|
5094
|
+
this.tokens -= 1;
|
|
5095
|
+
return;
|
|
5096
|
+
}
|
|
5097
|
+
const tokensNeeded = 1 - this.tokens;
|
|
5098
|
+
const waitMs = Math.ceil(tokensNeeded / this.refillPerSecond * 1e3);
|
|
5099
|
+
if (waitMs > this.acquireTimeoutMs) {
|
|
5100
|
+
throw new RateLimitTimeoutError(waitMs);
|
|
5101
|
+
}
|
|
5102
|
+
await sleep2(waitMs);
|
|
5103
|
+
this.refill();
|
|
5104
|
+
this.tokens -= 1;
|
|
5105
|
+
}
|
|
5106
|
+
/**
|
|
5107
|
+
* Best-effort acquire: returns true if a token was available, false
|
|
5108
|
+
* otherwise. Doesn't wait. Useful for "non-blocking" code paths that
|
|
5109
|
+
* want to fall back to a cached response or queue the request elsewhere.
|
|
5110
|
+
*/
|
|
5111
|
+
tryAcquire() {
|
|
5112
|
+
this.refill();
|
|
5113
|
+
if (this.tokens >= 1) {
|
|
5114
|
+
this.tokens -= 1;
|
|
5115
|
+
return true;
|
|
5116
|
+
}
|
|
5117
|
+
return false;
|
|
5118
|
+
}
|
|
5119
|
+
/**
|
|
5120
|
+
* Adaptive learning hook — call after every API response with MP's
|
|
5121
|
+
* rate-limit headers to keep the bucket in sync with reality.
|
|
5122
|
+
*/
|
|
5123
|
+
learnFromHeaders(headers) {
|
|
5124
|
+
if (!this.adaptive) return;
|
|
5125
|
+
if (headers.remaining === null) return;
|
|
5126
|
+
this.refill();
|
|
5127
|
+
if (headers.remaining < this.tokens) {
|
|
5128
|
+
this.tokens = Math.max(0, headers.remaining);
|
|
5129
|
+
}
|
|
5130
|
+
}
|
|
5131
|
+
/** Inspect the current bucket state. */
|
|
5132
|
+
getStats() {
|
|
5133
|
+
this.refill();
|
|
5134
|
+
return {
|
|
5135
|
+
tokens: this.tokens,
|
|
5136
|
+
capacity: this.capacity,
|
|
5137
|
+
refillPerSecond: this.refillPerSecond
|
|
5138
|
+
};
|
|
5139
|
+
}
|
|
5140
|
+
refill() {
|
|
5141
|
+
const now = this.now();
|
|
5142
|
+
const elapsedMs = now - this.lastRefill;
|
|
5143
|
+
if (elapsedMs <= 0) return;
|
|
5144
|
+
const refilled = elapsedMs / 1e3 * this.refillPerSecond;
|
|
5145
|
+
this.tokens = Math.min(this.capacity, this.tokens + refilled);
|
|
5146
|
+
this.lastRefill = now;
|
|
5147
|
+
}
|
|
5148
|
+
};
|
|
5149
|
+
function sleep2(ms) {
|
|
5150
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
5151
|
+
}
|
|
5152
|
+
|
|
5153
|
+
export { AHORA_PROGRAM_PROMOS, AR_ISSUER_PROMOS, AuditLogger, CircuitBreaker, CircuitOpenError, InMemoryAuditLog, InMemoryIdempotencyCache, InMemoryOAuthTokenStore, InMemoryStateAdapter, MercadoPagoAccountTypeMismatchError, MercadoPagoAuthError, MercadoPagoAuthorizeForbiddenError, MercadoPagoBackUrlInvalidError, MercadoPagoClient, MercadoPagoError, MercadoPagoOverloadedError, MercadoPagoPaymentRejectedError, MercadoPagoRateLimitError, MercadoPagoSelfPaymentError, MercadoPagoTimeoutError, RateLimitTimeoutError, TEST_CARDS_AR, TEST_PAYERS_AR, TokenBucketRateLimiter, WebhookDedup, analyze3DS, buildAuthorizeUrl, buildTestCardScenario, classifyError, collect, computeMarketplaceFee, confirmChallengeAndPoll, exchangeCodeForToken, expirationTimeMs, explainPaymentStatus, findApplicablePromos, isExpiringSoon, mercadoPagoTools, paginate, paginateAccountMovements, paginateMerchantOrders, paginatePayments, paginateSettlements, paginateSubscriptionPayments, paginateSubscriptionPlans, paginateSubscriptions, parseWebhookEvent, refreshAccessToken, verifyWebhookSignature };
|
|
4150
5154
|
//# sourceMappingURL=index.js.map
|
|
4151
5155
|
//# sourceMappingURL=index.js.map
|