@miguelmorales13/nestkit 0.31.3 → 0.32.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.
Files changed (59) hide show
  1. package/README.md +236 -0
  2. package/dist/chunk-2RQINZCR.cjs +17 -0
  3. package/dist/{chunk-LU3HO7B3.js → chunk-3WISEIHK.js} +4 -15
  4. package/dist/chunk-HMHUOXGB.cjs +63 -0
  5. package/dist/chunk-L2QK2HN5.js +17 -0
  6. package/dist/chunk-PBAPT3L5.js +63 -0
  7. package/dist/chunk-QVLTEABJ.cjs +248 -0
  8. package/dist/chunk-XKI3DJVA.js +248 -0
  9. package/dist/{chunk-33KFVAUZ.cjs → chunk-ZBOQKXGZ.cjs} +7 -18
  10. package/dist/index.cjs +2 -2
  11. package/dist/index.js +1 -1
  12. package/dist/payments/connect/terminal-connections.d.ts +7 -0
  13. package/dist/payments/index.cjs +36 -7
  14. package/dist/payments/index.js +31 -2
  15. package/dist/resilience/index.cjs +48 -262
  16. package/dist/resilience/index.js +19 -233
  17. package/dist/security/index.cjs +4 -2
  18. package/dist/security/index.js +5 -3
  19. package/dist/telephony/adapters/meta-whatsapp.telephony.d.ts +21 -0
  20. package/dist/telephony/adapters/simulated.telephony.d.ts +49 -0
  21. package/dist/telephony/adapters/twilio.telephony.d.ts +54 -0
  22. package/dist/telephony/index.cjs +2269 -0
  23. package/dist/telephony/index.d.ts +20 -0
  24. package/dist/telephony/index.js +2269 -0
  25. package/dist/telephony/provider-http.d.ts +35 -0
  26. package/dist/telephony/relay/access.d.ts +72 -0
  27. package/dist/telephony/relay/backend.d.ts +81 -0
  28. package/dist/telephony/relay/index.cjs +483 -0
  29. package/dist/telephony/relay/index.d.ts +9 -0
  30. package/dist/telephony/relay/index.js +483 -0
  31. package/dist/telephony/relay/server.d.ts +89 -0
  32. package/dist/telephony/relay/session.d.ts +100 -0
  33. package/dist/telephony/rules/call-limits.d.ts +48 -0
  34. package/dist/telephony/rules/call-token.d.ts +30 -0
  35. package/dist/telephony/rules/destination-policy.d.ts +21 -0
  36. package/dist/telephony/rules/dial-destination.d.ts +21 -0
  37. package/dist/telephony/rules/event-deduper.d.ts +15 -0
  38. package/dist/telephony/rules/handoff.d.ts +7 -0
  39. package/dist/telephony/rules/index.d.ts +20 -0
  40. package/dist/telephony/rules/opt-out.d.ts +32 -0
  41. package/dist/telephony/rules/phone.d.ts +9 -0
  42. package/dist/telephony/rules/provider-gate.d.ts +31 -0
  43. package/dist/telephony/rules/redact.d.ts +11 -0
  44. package/dist/telephony/rules/sanitize.d.ts +10 -0
  45. package/dist/telephony/rules/sliding-window.d.ts +10 -0
  46. package/dist/telephony/rules/ttl-cache.d.ts +14 -0
  47. package/dist/telephony/rules/usage-counter.d.ts +16 -0
  48. package/dist/telephony/telephony.errors.d.ts +46 -0
  49. package/dist/telephony/telephony.facade.d.ts +71 -0
  50. package/dist/telephony/telephony.module.d.ts +38 -0
  51. package/dist/telephony/telephony.options.d.ts +187 -0
  52. package/dist/telephony/telephony.port.d.ts +421 -0
  53. package/dist/telephony/telephony.registry.d.ts +24 -0
  54. package/dist/telephony/telephony.webhook.controller.d.ts +22 -0
  55. package/dist/telephony/telephony.webhooks.d.ts +53 -0
  56. package/dist/whatsapp/index.cjs +28 -0
  57. package/dist/whatsapp/index.js +28 -0
  58. package/dist/whatsapp/whatsapp-client.d.ts +5 -0
  59. package/package.json +12 -2
@@ -0,0 +1,248 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+ var _chunkQ5Y33L7Bcjs = require('./chunk-Q5Y33L7B.cjs');
4
+
5
+ // src/resilience/memory-alert-store.ts
6
+ var _crypto = require('crypto');
7
+ var MemoryAlertStore = class {
8
+ constructor() {
9
+ this.records = [];
10
+ }
11
+ async findOpen(key) {
12
+ return _nullishCoalesce(this.records.find(
13
+ (r) => r.resolvedAt === null && r.provider === key.provider && r.type === key.type && r.tenantId === (_nullishCoalesce(key.tenantId, () => ( null)))
14
+ ), () => ( null));
15
+ }
16
+ async create(input) {
17
+ const record = {
18
+ id: _crypto.randomUUID.call(void 0, ),
19
+ provider: input.provider,
20
+ type: input.type,
21
+ scope: input.scope,
22
+ tenantId: input.tenantId,
23
+ message: input.message,
24
+ details: input.details,
25
+ times: 1,
26
+ firstAt: input.at,
27
+ lastAt: input.at,
28
+ notifiedAt: null,
29
+ resolvedAt: null
30
+ };
31
+ this.records.push(record);
32
+ return record;
33
+ }
34
+ async touch(id, patch) {
35
+ const r = this.records.find((x) => x.id === id);
36
+ if (!r) throw new Error(`Alerta ${id} no existe`);
37
+ r.times += 1;
38
+ r.lastAt = patch.at;
39
+ r.message = patch.message;
40
+ r.details = { ...r.details, ..._nullishCoalesce(patch.details, () => ( {})) };
41
+ return r;
42
+ }
43
+ async markNotified(id, at) {
44
+ const r = this.records.find((x) => x.id === id);
45
+ if (r) r.notifiedAt = at;
46
+ }
47
+ async listOpen(filter = {}) {
48
+ return this.records.filter(
49
+ (r) => r.resolvedAt === null && (!filter.provider || r.provider === filter.provider) && (!filter.tenantId || r.tenantId === filter.tenantId)
50
+ ).sort((a, b) => b.lastAt.getTime() - a.lastAt.getTime());
51
+ }
52
+ async resolve(ids, at) {
53
+ for (const r of this.records) if (ids.includes(r.id) && r.resolvedAt === null) r.resolvedAt = at;
54
+ }
55
+ async list(opts) {
56
+ const limit = Math.min(_nullishCoalesce(opts.limit, () => ( 30)), 100);
57
+ const cursor = opts.cursor ? new Date(opts.cursor).getTime() : Infinity;
58
+ const rows = this.records.filter((r) => (!opts.onlyOpen || r.resolvedAt === null) && r.lastAt.getTime() < cursor).sort((a, b) => b.lastAt.getTime() - a.lastAt.getTime());
59
+ const items = rows.slice(0, limit);
60
+ return { items, next: rows.length > limit ? items.at(-1).lastAt.toISOString() : null };
61
+ }
62
+ };
63
+
64
+ // src/resilience/resilience.options.ts
65
+ var RESILIENCE_OPTIONS = /* @__PURE__ */ Symbol("RESILIENCE_OPTIONS");
66
+ var ALERT_STORE = /* @__PURE__ */ Symbol("ALERT_STORE");
67
+ var DEFAULT_RETRYABLE_STATUS = [408, 425, 429, 500, 502, 503, 504];
68
+ var DEFAULT_ERROR_CODE = "PROVIDER_UNAVAILABLE";
69
+ var DEFAULT_BACKOFF = {
70
+ baseMs: 400,
71
+ factor: 2,
72
+ maxMs: 3e4,
73
+ jitterMs: 100
74
+ };
75
+ function defaultMessage(_provider, name, info) {
76
+ const why = info.reason === "timeout" ? "tiempo agotado" : info.reason === "http" ? `HTTP ${info.status}` : "sin conexi\xF3n";
77
+ return `${name} no responde (${why}). Intenta de nuevo en un momento.`;
78
+ }
79
+ function resolveOptions(options = {}) {
80
+ const d = _nullishCoalesce(options.porDefecto, () => ( {}));
81
+ const a = _nullishCoalesce(options.alertas, () => ( {}));
82
+ return {
83
+ proveedores: _nullishCoalesce(options.proveedores, () => ( {})),
84
+ porDefecto: {
85
+ ...d,
86
+ timeoutMs: _nullishCoalesce(d.timeoutMs, () => ( 15e3)),
87
+ reintentos: _nullishCoalesce(d.reintentos, () => ( 2)),
88
+ backoff: { ...DEFAULT_BACKOFF, ..._nullishCoalesce(d.backoff, () => ( {})) }
89
+ },
90
+ alertas: {
91
+ almacen: _nullishCoalesce(a.almacen, () => ( new MemoryAlertStore())),
92
+ canales: _nullishCoalesce(a.canales, () => ( [])),
93
+ ventanaDedupeMs: _nullishCoalesce(a.ventanaDedupeMs, () => ( 30 * 6e4)),
94
+ topePorMinuto: _nullishCoalesce(a.topePorMinuto, () => ( 15)),
95
+ origen: _nullishCoalesce(a.origen, () => ( `api \xB7 ${_nullishCoalesce(process.env["NODE_ENV"], () => ( "development"))}`)),
96
+ interceptorGlobal: _nullishCoalesce(a.interceptorGlobal, () => ( false))
97
+ },
98
+ rutaSalud: options.rutaSalud,
99
+ salud: _nullishCoalesce(options.salud, () => ( {})),
100
+ codigoErrorProveedor: _nullishCoalesce(options.codigoErrorProveedor, () => ( DEFAULT_ERROR_CODE)),
101
+ mensajeProveedor: _nullishCoalesce(options.mensajeProveedor, () => ( defaultMessage))
102
+ };
103
+ }
104
+
105
+ // src/resilience/runtime.ts
106
+ var current = { options: resolveOptions(), sink: null, notifier: null };
107
+ var getRuntime = () => current;
108
+ function configureRuntime(options) {
109
+ current = { ...current, options };
110
+ }
111
+ function registerAlerts(sink, notifier) {
112
+ current = { ...current, sink, notifier };
113
+ }
114
+ function resetRuntime() {
115
+ current = { options: resolveOptions(), sink: null, notifier: null };
116
+ }
117
+
118
+ // src/resilience/provider-unavailable.exception.ts
119
+ var _common = require('@nestjs/common');
120
+ var log = new (0, _common.Logger)("ProviderUnavailable");
121
+ var ProviderUnavailableException = class extends _chunkQ5Y33L7Bcjs.AppException {
122
+ constructor(provider, info) {
123
+ const cfg = getRuntime().options;
124
+ const name = _nullishCoalesce(_optionalChain([cfg, 'access', _ => _.proveedores, 'access', _2 => _2[provider], 'optionalAccess', _3 => _3.nombre]), () => ( provider));
125
+ log.warn(
126
+ `${provider} no disponible: ${info.reason} status=${_nullishCoalesce(info.status, () => ( "-"))} url=${info.url} intentos=${info.attempts}${info.detail ? ` detalle=${info.detail}` : ""}`
127
+ );
128
+ super(
129
+ cfg.codigoErrorProveedor,
130
+ cfg.mensajeProveedor(provider, name, info),
131
+ _common.HttpStatus.BAD_GATEWAY,
132
+ { provider, reason: info.reason, status: info.status, attempts: info.attempts }
133
+ );
134
+ this.provider = provider;
135
+ }
136
+ };
137
+
138
+ // src/resilience/resilient-fetch.ts
139
+ var SIDE_EFFECT_FREE = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]);
140
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
141
+ function retryDelay(n, backoff, retryAfter) {
142
+ const asked = retryAfter ? Number(retryAfter) * 1e3 : NaN;
143
+ if (Number.isFinite(asked) && asked > 0) return Math.min(asked, backoff.maxMs);
144
+ const wait = backoff.baseMs * backoff.factor ** n + Math.floor(Math.random() * (backoff.jitterMs + 1));
145
+ return Math.min(wait, backoff.maxMs);
146
+ }
147
+ function hasIdempotencyHeader(headers) {
148
+ if (!headers) return false;
149
+ for (const k of new Headers(headers).keys()) if (/idempotency/i.test(k)) return true;
150
+ return false;
151
+ }
152
+ function stripQuery(url) {
153
+ try {
154
+ const u = new URL(url);
155
+ return `${u.origin}${u.pathname}`;
156
+ } catch (e2) {
157
+ return _nullishCoalesce(url.split("?")[0], () => ( url));
158
+ }
159
+ }
160
+ function fetchResiliente(o) {
161
+ const resilient = async (input, init) => {
162
+ const { options } = getRuntime();
163
+ const cfg = _nullishCoalesce(options.proveedores[o.proveedor], () => ( {}));
164
+ const def = options.porDefecto;
165
+ const timeoutMs = _nullishCoalesce(_nullishCoalesce(o.timeoutMs, () => ( cfg.timeoutMs)), () => ( def.timeoutMs));
166
+ const retries = _nullishCoalesce(_nullishCoalesce(o.reintentos, () => ( cfg.reintentos)), () => ( def.reintentos));
167
+ const backoff = { ...def.backoff, ..._nullishCoalesce(cfg.backoff, () => ( {})), ..._nullishCoalesce(o.backoff, () => ( {})) };
168
+ const retryable = new Set(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(o.statusReintentables, () => ( cfg.statusReintentables)), () => ( def.statusReintentables)), () => ( DEFAULT_RETRYABLE_STATUS)));
169
+ const idempotent = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(o.idempotente, () => ( cfg.idempotente)), () => ( def.idempotente)), () => ( false));
170
+ const doFetch = _nullishCoalesce(o.fetchImpl, () => ( fetch));
171
+ const wait = _nullishCoalesce(o.sleep, () => ( sleep));
172
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
173
+ const method = (_nullishCoalesce(_optionalChain([init, 'optionalAccess', _4 => _4.method]), () => ( "GET"))).toUpperCase();
174
+ const safe = SIDE_EFFECT_FREE.has(method) || idempotent || hasIdempotencyHeader(_optionalChain([init, 'optionalAccess', _5 => _5.headers]));
175
+ const sink = getRuntime().sink;
176
+ for (let attempt = 0; ; attempt++) {
177
+ const signal = _optionalChain([init, 'optionalAccess', _6 => _6.signal]) ? AbortSignal.any([init.signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs);
178
+ let res;
179
+ try {
180
+ res = await doFetch(input, { ...init, signal });
181
+ } catch (e) {
182
+ const err = e;
183
+ if (_optionalChain([init, 'optionalAccess', _7 => _7.signal, 'optionalAccess', _8 => _8.aborted])) throw e;
184
+ const reason = err.name === "TimeoutError" || err.name === "AbortError" ? "timeout" : "network";
185
+ const info2 = {
186
+ reason,
187
+ attempts: attempt + 1,
188
+ url: stripQuery(url),
189
+ tenantId: o.tenantId,
190
+ detail: err.message
191
+ };
192
+ if (safe && attempt < retries) {
193
+ await wait(retryDelay(attempt, backoff));
194
+ continue;
195
+ }
196
+ _optionalChain([sink, 'optionalAccess', _9 => _9.failure, 'call', _10 => _10(o.proveedor, { ...info2, tenantId: void 0 })]);
197
+ throw new ProviderUnavailableException(o.proveedor, info2);
198
+ }
199
+ if (retryable.has(res.status) && safe && attempt < retries) {
200
+ await _optionalChain([res, 'access', _11 => _11.body, 'optionalAccess', _12 => _12.cancel, 'call', _13 => _13(), 'access', _14 => _14.catch, 'call', _15 => _15(() => void 0)]);
201
+ await wait(retryDelay(attempt, backoff, res.headers.get("retry-after")));
202
+ continue;
203
+ }
204
+ const info = {
205
+ reason: "http",
206
+ status: res.status,
207
+ attempts: attempt + 1,
208
+ url: stripQuery(url),
209
+ tenantId: o.tenantId
210
+ };
211
+ if (res.status >= 500 || res.status === 429) _optionalChain([sink, 'optionalAccess', _16 => _16.failure, 'call', _17 => _17(o.proveedor, { ...info, tenantId: void 0 })]);
212
+ else if (res.status === 401 || res.status === 403) _optionalChain([sink, 'optionalAccess', _18 => _18.credentials, 'call', _19 => _19(o.proveedor, info)]);
213
+ else _optionalChain([sink, 'optionalAccess', _20 => _20.success, 'call', _21 => _21(o.proveedor)]);
214
+ return res;
215
+ }
216
+ };
217
+ return resilient;
218
+ }
219
+ async function withRetries(fn, isTransient, opts = {}) {
220
+ const retries = _nullishCoalesce(opts.reintentos, () => ( getRuntime().options.porDefecto.reintentos));
221
+ const backoff = { ...getRuntime().options.porDefecto.backoff, ..._nullishCoalesce(opts.backoff, () => ( {})) };
222
+ const wait = _nullishCoalesce(opts.sleep, () => ( sleep));
223
+ for (let attempt = 0; ; attempt++) {
224
+ try {
225
+ return await fn();
226
+ } catch (e) {
227
+ if (!isTransient(e) || attempt >= retries) throw e;
228
+ await wait(retryDelay(attempt, backoff));
229
+ }
230
+ }
231
+ }
232
+
233
+
234
+
235
+
236
+
237
+
238
+
239
+
240
+
241
+
242
+
243
+
244
+
245
+
246
+
247
+
248
+ exports.MemoryAlertStore = MemoryAlertStore; exports.RESILIENCE_OPTIONS = RESILIENCE_OPTIONS; exports.ALERT_STORE = ALERT_STORE; exports.DEFAULT_ERROR_CODE = DEFAULT_ERROR_CODE; exports.resolveOptions = resolveOptions; exports.getRuntime = getRuntime; exports.configureRuntime = configureRuntime; exports.registerAlerts = registerAlerts; exports.resetRuntime = resetRuntime; exports.ProviderUnavailableException = ProviderUnavailableException; exports.retryDelay = retryDelay; exports.stripQuery = stripQuery; exports.fetchResiliente = fetchResiliente; exports.withRetries = withRetries;
@@ -0,0 +1,248 @@
1
+ import {
2
+ AppException
3
+ } from "./chunk-M3GQDRWR.js";
4
+
5
+ // src/resilience/memory-alert-store.ts
6
+ import { randomUUID } from "crypto";
7
+ var MemoryAlertStore = class {
8
+ constructor() {
9
+ this.records = [];
10
+ }
11
+ async findOpen(key) {
12
+ return this.records.find(
13
+ (r) => r.resolvedAt === null && r.provider === key.provider && r.type === key.type && r.tenantId === (key.tenantId ?? null)
14
+ ) ?? null;
15
+ }
16
+ async create(input) {
17
+ const record = {
18
+ id: randomUUID(),
19
+ provider: input.provider,
20
+ type: input.type,
21
+ scope: input.scope,
22
+ tenantId: input.tenantId,
23
+ message: input.message,
24
+ details: input.details,
25
+ times: 1,
26
+ firstAt: input.at,
27
+ lastAt: input.at,
28
+ notifiedAt: null,
29
+ resolvedAt: null
30
+ };
31
+ this.records.push(record);
32
+ return record;
33
+ }
34
+ async touch(id, patch) {
35
+ const r = this.records.find((x) => x.id === id);
36
+ if (!r) throw new Error(`Alerta ${id} no existe`);
37
+ r.times += 1;
38
+ r.lastAt = patch.at;
39
+ r.message = patch.message;
40
+ r.details = { ...r.details, ...patch.details ?? {} };
41
+ return r;
42
+ }
43
+ async markNotified(id, at) {
44
+ const r = this.records.find((x) => x.id === id);
45
+ if (r) r.notifiedAt = at;
46
+ }
47
+ async listOpen(filter = {}) {
48
+ return this.records.filter(
49
+ (r) => r.resolvedAt === null && (!filter.provider || r.provider === filter.provider) && (!filter.tenantId || r.tenantId === filter.tenantId)
50
+ ).sort((a, b) => b.lastAt.getTime() - a.lastAt.getTime());
51
+ }
52
+ async resolve(ids, at) {
53
+ for (const r of this.records) if (ids.includes(r.id) && r.resolvedAt === null) r.resolvedAt = at;
54
+ }
55
+ async list(opts) {
56
+ const limit = Math.min(opts.limit ?? 30, 100);
57
+ const cursor = opts.cursor ? new Date(opts.cursor).getTime() : Infinity;
58
+ const rows = this.records.filter((r) => (!opts.onlyOpen || r.resolvedAt === null) && r.lastAt.getTime() < cursor).sort((a, b) => b.lastAt.getTime() - a.lastAt.getTime());
59
+ const items = rows.slice(0, limit);
60
+ return { items, next: rows.length > limit ? items.at(-1).lastAt.toISOString() : null };
61
+ }
62
+ };
63
+
64
+ // src/resilience/resilience.options.ts
65
+ var RESILIENCE_OPTIONS = /* @__PURE__ */ Symbol("RESILIENCE_OPTIONS");
66
+ var ALERT_STORE = /* @__PURE__ */ Symbol("ALERT_STORE");
67
+ var DEFAULT_RETRYABLE_STATUS = [408, 425, 429, 500, 502, 503, 504];
68
+ var DEFAULT_ERROR_CODE = "PROVIDER_UNAVAILABLE";
69
+ var DEFAULT_BACKOFF = {
70
+ baseMs: 400,
71
+ factor: 2,
72
+ maxMs: 3e4,
73
+ jitterMs: 100
74
+ };
75
+ function defaultMessage(_provider, name, info) {
76
+ const why = info.reason === "timeout" ? "tiempo agotado" : info.reason === "http" ? `HTTP ${info.status}` : "sin conexi\xF3n";
77
+ return `${name} no responde (${why}). Intenta de nuevo en un momento.`;
78
+ }
79
+ function resolveOptions(options = {}) {
80
+ const d = options.porDefecto ?? {};
81
+ const a = options.alertas ?? {};
82
+ return {
83
+ proveedores: options.proveedores ?? {},
84
+ porDefecto: {
85
+ ...d,
86
+ timeoutMs: d.timeoutMs ?? 15e3,
87
+ reintentos: d.reintentos ?? 2,
88
+ backoff: { ...DEFAULT_BACKOFF, ...d.backoff ?? {} }
89
+ },
90
+ alertas: {
91
+ almacen: a.almacen ?? new MemoryAlertStore(),
92
+ canales: a.canales ?? [],
93
+ ventanaDedupeMs: a.ventanaDedupeMs ?? 30 * 6e4,
94
+ topePorMinuto: a.topePorMinuto ?? 15,
95
+ origen: a.origen ?? `api \xB7 ${process.env["NODE_ENV"] ?? "development"}`,
96
+ interceptorGlobal: a.interceptorGlobal ?? false
97
+ },
98
+ rutaSalud: options.rutaSalud,
99
+ salud: options.salud ?? {},
100
+ codigoErrorProveedor: options.codigoErrorProveedor ?? DEFAULT_ERROR_CODE,
101
+ mensajeProveedor: options.mensajeProveedor ?? defaultMessage
102
+ };
103
+ }
104
+
105
+ // src/resilience/runtime.ts
106
+ var current = { options: resolveOptions(), sink: null, notifier: null };
107
+ var getRuntime = () => current;
108
+ function configureRuntime(options) {
109
+ current = { ...current, options };
110
+ }
111
+ function registerAlerts(sink, notifier) {
112
+ current = { ...current, sink, notifier };
113
+ }
114
+ function resetRuntime() {
115
+ current = { options: resolveOptions(), sink: null, notifier: null };
116
+ }
117
+
118
+ // src/resilience/provider-unavailable.exception.ts
119
+ import { HttpStatus, Logger } from "@nestjs/common";
120
+ var log = new Logger("ProviderUnavailable");
121
+ var ProviderUnavailableException = class extends AppException {
122
+ constructor(provider, info) {
123
+ const cfg = getRuntime().options;
124
+ const name = cfg.proveedores[provider]?.nombre ?? provider;
125
+ log.warn(
126
+ `${provider} no disponible: ${info.reason} status=${info.status ?? "-"} url=${info.url} intentos=${info.attempts}${info.detail ? ` detalle=${info.detail}` : ""}`
127
+ );
128
+ super(
129
+ cfg.codigoErrorProveedor,
130
+ cfg.mensajeProveedor(provider, name, info),
131
+ HttpStatus.BAD_GATEWAY,
132
+ { provider, reason: info.reason, status: info.status, attempts: info.attempts }
133
+ );
134
+ this.provider = provider;
135
+ }
136
+ };
137
+
138
+ // src/resilience/resilient-fetch.ts
139
+ var SIDE_EFFECT_FREE = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]);
140
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
141
+ function retryDelay(n, backoff, retryAfter) {
142
+ const asked = retryAfter ? Number(retryAfter) * 1e3 : NaN;
143
+ if (Number.isFinite(asked) && asked > 0) return Math.min(asked, backoff.maxMs);
144
+ const wait = backoff.baseMs * backoff.factor ** n + Math.floor(Math.random() * (backoff.jitterMs + 1));
145
+ return Math.min(wait, backoff.maxMs);
146
+ }
147
+ function hasIdempotencyHeader(headers) {
148
+ if (!headers) return false;
149
+ for (const k of new Headers(headers).keys()) if (/idempotency/i.test(k)) return true;
150
+ return false;
151
+ }
152
+ function stripQuery(url) {
153
+ try {
154
+ const u = new URL(url);
155
+ return `${u.origin}${u.pathname}`;
156
+ } catch {
157
+ return url.split("?")[0] ?? url;
158
+ }
159
+ }
160
+ function fetchResiliente(o) {
161
+ const resilient = async (input, init) => {
162
+ const { options } = getRuntime();
163
+ const cfg = options.proveedores[o.proveedor] ?? {};
164
+ const def = options.porDefecto;
165
+ const timeoutMs = o.timeoutMs ?? cfg.timeoutMs ?? def.timeoutMs;
166
+ const retries = o.reintentos ?? cfg.reintentos ?? def.reintentos;
167
+ const backoff = { ...def.backoff, ...cfg.backoff ?? {}, ...o.backoff ?? {} };
168
+ const retryable = new Set(o.statusReintentables ?? cfg.statusReintentables ?? def.statusReintentables ?? DEFAULT_RETRYABLE_STATUS);
169
+ const idempotent = o.idempotente ?? cfg.idempotente ?? def.idempotente ?? false;
170
+ const doFetch = o.fetchImpl ?? fetch;
171
+ const wait = o.sleep ?? sleep;
172
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
173
+ const method = (init?.method ?? "GET").toUpperCase();
174
+ const safe = SIDE_EFFECT_FREE.has(method) || idempotent || hasIdempotencyHeader(init?.headers);
175
+ const sink = getRuntime().sink;
176
+ for (let attempt = 0; ; attempt++) {
177
+ const signal = init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs);
178
+ let res;
179
+ try {
180
+ res = await doFetch(input, { ...init, signal });
181
+ } catch (e) {
182
+ const err = e;
183
+ if (init?.signal?.aborted) throw e;
184
+ const reason = err.name === "TimeoutError" || err.name === "AbortError" ? "timeout" : "network";
185
+ const info2 = {
186
+ reason,
187
+ attempts: attempt + 1,
188
+ url: stripQuery(url),
189
+ tenantId: o.tenantId,
190
+ detail: err.message
191
+ };
192
+ if (safe && attempt < retries) {
193
+ await wait(retryDelay(attempt, backoff));
194
+ continue;
195
+ }
196
+ sink?.failure(o.proveedor, { ...info2, tenantId: void 0 });
197
+ throw new ProviderUnavailableException(o.proveedor, info2);
198
+ }
199
+ if (retryable.has(res.status) && safe && attempt < retries) {
200
+ await res.body?.cancel().catch(() => void 0);
201
+ await wait(retryDelay(attempt, backoff, res.headers.get("retry-after")));
202
+ continue;
203
+ }
204
+ const info = {
205
+ reason: "http",
206
+ status: res.status,
207
+ attempts: attempt + 1,
208
+ url: stripQuery(url),
209
+ tenantId: o.tenantId
210
+ };
211
+ if (res.status >= 500 || res.status === 429) sink?.failure(o.proveedor, { ...info, tenantId: void 0 });
212
+ else if (res.status === 401 || res.status === 403) sink?.credentials(o.proveedor, info);
213
+ else sink?.success(o.proveedor);
214
+ return res;
215
+ }
216
+ };
217
+ return resilient;
218
+ }
219
+ async function withRetries(fn, isTransient, opts = {}) {
220
+ const retries = opts.reintentos ?? getRuntime().options.porDefecto.reintentos;
221
+ const backoff = { ...getRuntime().options.porDefecto.backoff, ...opts.backoff ?? {} };
222
+ const wait = opts.sleep ?? sleep;
223
+ for (let attempt = 0; ; attempt++) {
224
+ try {
225
+ return await fn();
226
+ } catch (e) {
227
+ if (!isTransient(e) || attempt >= retries) throw e;
228
+ await wait(retryDelay(attempt, backoff));
229
+ }
230
+ }
231
+ }
232
+
233
+ export {
234
+ MemoryAlertStore,
235
+ RESILIENCE_OPTIONS,
236
+ ALERT_STORE,
237
+ DEFAULT_ERROR_CODE,
238
+ resolveOptions,
239
+ getRuntime,
240
+ configureRuntime,
241
+ registerAlerts,
242
+ resetRuntime,
243
+ ProviderUnavailableException,
244
+ retryDelay,
245
+ stripQuery,
246
+ fetchResiliente,
247
+ withRetries
248
+ };
@@ -1,4 +1,8 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/security/signed-state.ts
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
2
+
3
+ var _chunk2RQINZCRcjs = require('./chunk-2RQINZCR.cjs');
4
+
5
+ // src/security/signed-state.ts
2
6
  var _crypto = require('crypto');
3
7
  function signState(payload, options) {
4
8
  const body = JSON.stringify({ ts: Date.now(), nonce: _crypto.randomBytes.call(void 0, 8).toString("hex"), ...payload });
@@ -89,19 +93,6 @@ function maskFields(value, rules, maxDepth = 8) {
89
93
  return walk(value, 0);
90
94
  }
91
95
 
92
- // src/security/hash.ts
93
-
94
- var hashSha256 = (value) => _crypto.createHash.call(void 0, "sha256").update(value).digest("hex");
95
- function constantTimeEqual(a, b) {
96
- const ba = Buffer.from(a);
97
- const bb = Buffer.from(b);
98
- if (ba.length !== bb.length) {
99
- _crypto.timingSafeEqual.call(void 0, ba, ba);
100
- return false;
101
- }
102
- return _crypto.timingSafeEqual.call(void 0, ba, bb);
103
- }
104
-
105
96
  // src/security/signed-grant.ts
106
97
 
107
98
  var sign = (b64, secret) => _crypto.createHmac.call(void 0, "sha256", secret).update(b64).digest("base64url");
@@ -122,7 +113,7 @@ function verifyGrant(token, secret, expected) {
122
113
  const parts = token.split(".");
123
114
  if (parts.length !== 2) return null;
124
115
  const [b64, sig] = parts;
125
- if (!constantTimeEqual(sig, sign(b64, secret))) return null;
116
+ if (!_chunk2RQINZCRcjs.constantTimeEqual.call(void 0, sig, sign(b64, secret))) return null;
126
117
  let p;
127
118
  try {
128
119
  p = JSON.parse(Buffer.from(b64, "base64url").toString());
@@ -146,6 +137,4 @@ function verifyGrant(token, secret, expected) {
146
137
 
147
138
 
148
139
 
149
-
150
-
151
- exports.signState = signState; exports.readState = readState; exports.maskEmail = maskEmail; exports.maskPhone = maskPhone; exports.maskToken = maskToken; exports.shapeOf = shapeOf; exports.maskFields = maskFields; exports.hashSha256 = hashSha256; exports.constantTimeEqual = constantTimeEqual; exports.signGrant = signGrant; exports.verifyGrant = verifyGrant;
140
+ exports.signState = signState; exports.readState = readState; exports.maskEmail = maskEmail; exports.maskPhone = maskPhone; exports.maskToken = maskToken; exports.shapeOf = shapeOf; exports.maskFields = maskFields; exports.signGrant = signGrant; exports.verifyGrant = verifyGrant;
package/dist/index.cjs CHANGED
@@ -1,9 +1,9 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});require('./chunk-KVBQBT3D.cjs');
2
+
2
3
 
3
4
 
4
5
 
5
6
  var _chunk47IYXZHWcjs = require('./chunk-47IYXZHW.cjs');
6
- require('./chunk-KVBQBT3D.cjs');
7
7
 
8
8
 
9
9
 
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
+ import "./chunk-EPVKCBPT.js";
1
2
  import {
2
3
  PG_POOL,
3
4
  PgModule,
4
5
  withTenantScope
5
6
  } from "./chunk-ENZ7LQRE.js";
6
- import "./chunk-EPVKCBPT.js";
7
7
  import {
8
8
  SUPABASE_ANON_CLIENT,
9
9
  SUPABASE_SERVICE_ROLE_CLIENT,
@@ -216,6 +216,13 @@ export declare class TerminalConnections {
216
216
  id: string;
217
217
  terminals: number;
218
218
  }>;
219
+ /**
220
+ * Re-authorizing an account the tenant already connected renews that row (credentials, active) instead of piling up
221
+ * copies of it; alias, primary flag and chosen terminal stay. Returns null — a new row is due — when the account is
222
+ * new, or when it holds terminals that no row has taken yet (that is how a second terminal is added). A row still
223
+ * waiting for its terminal is reused first.
224
+ */
225
+ private renewMercadoPago;
219
226
  /** Inserts a new row (never overwrites); the tenant's first terminal becomes primary on its own. */
220
227
  private save;
221
228
  terminals(scopeId: string, id: string): Promise<TerminalSummary[]>;
@@ -1,7 +1,8 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
2
 
3
3
 
4
- var _chunk33KFVAUZcjs = require('../chunk-33KFVAUZ.cjs');
4
+ var _chunkZBOQKXGZcjs = require('../chunk-ZBOQKXGZ.cjs');
5
+ require('../chunk-2RQINZCR.cjs');
5
6
  require('../chunk-7SOM7EZP.cjs');
6
7
  require('../chunk-JJKGQNGD.cjs');
7
8
  require('../chunk-AXMW5JF7.cjs');
@@ -1366,7 +1367,7 @@ var TerminalConnections = class {
1366
1367
  if (!connect)
1367
1368
  throw new (0, _chunkHDFPSA2Vcjs.ConflictAppException)("Mercado Pago no est\xE1 configurado en el servidor.", {}, "MERCADOPAGO_NO_CONFIGURADO");
1368
1369
  const csrf = _crypto.randomBytes.call(void 0, 16).toString("hex");
1369
- const state = _chunk33KFVAUZcjs.signState.call(void 0, { scopeId, actorId, csrf, destination }, { secret: this.stateSecret(), ttlMs: STATE_TTL_MS });
1370
+ const state = _chunkZBOQKXGZcjs.signState.call(void 0, { scopeId, actorId, csrf, destination }, { secret: this.stateSecret(), ttlMs: STATE_TTL_MS });
1370
1371
  return { url: connect.authorizationUrl(state), csrf };
1371
1372
  }
1372
1373
  stateSecret() {
@@ -1376,7 +1377,7 @@ var TerminalConnections = class {
1376
1377
  return secret;
1377
1378
  }
1378
1379
  readOAuthState(state) {
1379
- return _chunk33KFVAUZcjs.readState.call(void 0, state, { secret: this.stateSecret(), ttlMs: STATE_TTL_MS });
1380
+ return _chunkZBOQKXGZcjs.readState.call(void 0, state, { secret: this.stateSecret(), ttlMs: STATE_TTL_MS });
1380
1381
  }
1381
1382
  /** Where to go back after the callback. An unreadable `state` goes back to `fallback`. */
1382
1383
  oauthDestination(state, fallback = "web") {
@@ -1408,9 +1409,37 @@ var TerminalConnections = class {
1408
1409
  expira: tokens.expiresAt.toISOString()
1409
1410
  };
1410
1411
  const terminals = await this.adapter("mercadopago", credentials, signed.scopeId).listTerminals();
1411
- const id = await this.save(signed.scopeId, "mercadopago", credentials, terminals);
1412
+ const id = await _asyncNullishCoalesce(await this.renewMercadoPago(signed.scopeId, credentials, terminals), async () => ( await this.save(signed.scopeId, "mercadopago", credentials, terminals)));
1412
1413
  return { scopeId: signed.scopeId, actorId: signed.actorId, id, terminals: terminals.length };
1413
1414
  }
1415
+ /**
1416
+ * Re-authorizing an account the tenant already connected renews that row (credentials, active) instead of piling up
1417
+ * copies of it; alias, primary flag and chosen terminal stay. Returns null — a new row is due — when the account is
1418
+ * new, or when it holds terminals that no row has taken yet (that is how a second terminal is added). A row still
1419
+ * waiting for its terminal is reused first.
1420
+ */
1421
+ async renewMercadoPago(scopeId, credentials, terminals) {
1422
+ if (!credentials.mpUserId) return null;
1423
+ const cipher = this.requireCipher();
1424
+ const same = this.sorted(await this.o.store.list(scopeId)).filter((r) => {
1425
+ if (r.provider !== "mercadopago") return false;
1426
+ try {
1427
+ return cipher.decryptJson(r.encryptedCredentials).mpUserId === credentials.mpUserId;
1428
+ } catch (e4) {
1429
+ return false;
1430
+ }
1431
+ });
1432
+ const only = terminals.length === 1 ? terminals[0] : null;
1433
+ const allTaken = terminals.every((t) => same.some((r) => r.terminalId === t.id));
1434
+ const row = _nullishCoalesce(_nullishCoalesce((only && same.find((r) => r.terminalId === only.id)), () => ( same.find((r) => !r.terminalId))), () => ( (allTaken ? same[0] : void 0)));
1435
+ if (!row) return null;
1436
+ await this.o.store.update(row.id, {
1437
+ encryptedCredentials: cipher.encryptJson(credentials),
1438
+ active: true,
1439
+ ...only && !row.terminalId && { terminalId: only.id, terminalName: terminalName(only) }
1440
+ });
1441
+ return row.id;
1442
+ }
1414
1443
  /** Inserts a new row (never overwrites); the tenant's first terminal becomes primary on its own. */
1415
1444
  async save(scopeId, provider, credentials, terminals) {
1416
1445
  const cipher = this.requireCipher();
@@ -1616,7 +1645,7 @@ var TerminalConnections = class {
1616
1645
  scopes.add(r.scopeId);
1617
1646
  seen.set(u, scopes);
1618
1647
  byUser.set(u, (_nullishCoalesce(byUser.get(u), () => ( /* @__PURE__ */ new Set()))).add(r.id));
1619
- } catch (e4) {
1648
+ } catch (e5) {
1620
1649
  }
1621
1650
  }
1622
1651
  this.mpCache = { at: Date.now(), byUser };
@@ -2086,7 +2115,7 @@ var OpenpayConnections = class {
2086
2115
  const partner = this.partner;
2087
2116
  const secret = this.stateSecret;
2088
2117
  if (!this.cipher || !partner || !secret) throw new (0, _chunkHDFPSA2Vcjs.ConflictAppException)(this.msg.notConfigured, void 0, "OPENPAY_NO_CONFIGURADO");
2089
- const state = _chunk33KFVAUZcjs.signState.call(void 0, { ...extra, scopeId, purpose: STATE_PURPOSE }, { secret });
2118
+ const state = _chunkZBOQKXGZcjs.signState.call(void 0, { ...extra, scopeId, purpose: STATE_PURPOSE }, { secret });
2090
2119
  const params = new URLSearchParams({
2091
2120
  client_id: partner.clientId,
2092
2121
  redirect_uri: partner.redirectUri,
@@ -2100,7 +2129,7 @@ var OpenpayConnections = class {
2100
2129
  readState(state) {
2101
2130
  const secret = this.stateSecret;
2102
2131
  if (!secret) return null;
2103
- const s = _chunk33KFVAUZcjs.readState.call(void 0, state, { secret });
2132
+ const s = _chunkZBOQKXGZcjs.readState.call(void 0, state, { secret });
2104
2133
  return s && s.purpose === STATE_PURPOSE && s.scopeId ? s : null;
2105
2134
  }
2106
2135
  /**