@miguelmorales13/nestkit 0.31.4 → 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 (56) hide show
  1. package/README.md +234 -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/payments/index.cjs +6 -5
  11. package/dist/payments/index.js +2 -1
  12. package/dist/resilience/index.cjs +48 -262
  13. package/dist/resilience/index.js +19 -233
  14. package/dist/security/index.cjs +4 -2
  15. package/dist/security/index.js +5 -3
  16. package/dist/telephony/adapters/meta-whatsapp.telephony.d.ts +21 -0
  17. package/dist/telephony/adapters/simulated.telephony.d.ts +49 -0
  18. package/dist/telephony/adapters/twilio.telephony.d.ts +54 -0
  19. package/dist/telephony/index.cjs +2269 -0
  20. package/dist/telephony/index.d.ts +20 -0
  21. package/dist/telephony/index.js +2269 -0
  22. package/dist/telephony/provider-http.d.ts +35 -0
  23. package/dist/telephony/relay/access.d.ts +72 -0
  24. package/dist/telephony/relay/backend.d.ts +81 -0
  25. package/dist/telephony/relay/index.cjs +483 -0
  26. package/dist/telephony/relay/index.d.ts +9 -0
  27. package/dist/telephony/relay/index.js +483 -0
  28. package/dist/telephony/relay/server.d.ts +89 -0
  29. package/dist/telephony/relay/session.d.ts +100 -0
  30. package/dist/telephony/rules/call-limits.d.ts +48 -0
  31. package/dist/telephony/rules/call-token.d.ts +30 -0
  32. package/dist/telephony/rules/destination-policy.d.ts +21 -0
  33. package/dist/telephony/rules/dial-destination.d.ts +21 -0
  34. package/dist/telephony/rules/event-deduper.d.ts +15 -0
  35. package/dist/telephony/rules/handoff.d.ts +7 -0
  36. package/dist/telephony/rules/index.d.ts +20 -0
  37. package/dist/telephony/rules/opt-out.d.ts +32 -0
  38. package/dist/telephony/rules/phone.d.ts +9 -0
  39. package/dist/telephony/rules/provider-gate.d.ts +31 -0
  40. package/dist/telephony/rules/redact.d.ts +11 -0
  41. package/dist/telephony/rules/sanitize.d.ts +10 -0
  42. package/dist/telephony/rules/sliding-window.d.ts +10 -0
  43. package/dist/telephony/rules/ttl-cache.d.ts +14 -0
  44. package/dist/telephony/rules/usage-counter.d.ts +16 -0
  45. package/dist/telephony/telephony.errors.d.ts +46 -0
  46. package/dist/telephony/telephony.facade.d.ts +71 -0
  47. package/dist/telephony/telephony.module.d.ts +38 -0
  48. package/dist/telephony/telephony.options.d.ts +187 -0
  49. package/dist/telephony/telephony.port.d.ts +421 -0
  50. package/dist/telephony/telephony.registry.d.ts +24 -0
  51. package/dist/telephony/telephony.webhook.controller.d.ts +22 -0
  52. package/dist/telephony/telephony.webhooks.d.ts +53 -0
  53. package/dist/whatsapp/index.cjs +28 -0
  54. package/dist/whatsapp/index.js +28 -0
  55. package/dist/whatsapp/whatsapp-client.d.ts +5 -0
  56. package/package.json +12 -2
@@ -0,0 +1,2269 @@
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
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+ var _chunkHMHUOXGBcjs = require('../chunk-HMHUOXGB.cjs');
10
+
11
+
12
+
13
+ var _chunkQVLTEABJcjs = require('../chunk-QVLTEABJ.cjs');
14
+
15
+
16
+ var _chunk2RQINZCRcjs = require('../chunk-2RQINZCR.cjs');
17
+
18
+
19
+ var _chunkQ5Y33L7Bcjs = require('../chunk-Q5Y33L7B.cjs');
20
+ require('../chunk-PNK5WMPP.cjs');
21
+
22
+
23
+
24
+ var _chunkLRX7AMSScjs = require('../chunk-LRX7AMSS.cjs');
25
+
26
+ // src/telephony/telephony.port.ts
27
+ var TELEPHONY = /* @__PURE__ */ Symbol("TELEPHONY");
28
+ var TELEPHONY_PORT_VERSION = 1;
29
+ var TELEPHONY_EVENTS = {
30
+ CALL_INCOMING: "llamada.entrante",
31
+ CALL_STATUS: "llamada.estado",
32
+ CALL_ENDED: "llamada.terminada",
33
+ CALL_ACTION: "llamada.accion",
34
+ SMS_RECEIVED: "sms.recibido",
35
+ SMS_STATUS: "sms.estado",
36
+ WHATSAPP_RECEIVED: "whatsapp.recibido",
37
+ WHATSAPP_STATUS: "whatsapp.estado"
38
+ };
39
+
40
+ // src/telephony/telephony.options.ts
41
+ var TELEPHONY_OPTIONS = /* @__PURE__ */ Symbol("TELEPHONY_OPTIONS");
42
+ var TELEPHONY_WEBHOOKS = /* @__PURE__ */ Symbol("TELEPHONY_WEBHOOKS");
43
+ var TELEPHONY_HOOKS = /* @__PURE__ */ Symbol("TELEPHONY_HOOKS");
44
+ var DEFAULT_TEXTS = {
45
+ unavailable: "Por el momento no podemos atender tu llamada. Intenta de nuevo en unos minutos.",
46
+ greetingFallback: "Gracias por llamar."
47
+ };
48
+
49
+ // src/telephony/rules/opt-out.ts
50
+ var norm = (s) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").trim().toLowerCase().replace(/[.!¡¿?\s]+$/g, "").replace(/\s+/g, " ");
51
+ var OPT_OUT_KEYWORDS = [
52
+ "stop",
53
+ "stopall",
54
+ "unsubscribe",
55
+ "cancel",
56
+ "end",
57
+ "quit",
58
+ "baja",
59
+ "alto",
60
+ "cancelar",
61
+ "parar",
62
+ "detener",
63
+ "no mas",
64
+ "dar de baja"
65
+ ];
66
+ var OPT_IN_KEYWORDS = ["start", "unstop", "yes", "alta", "reanudar", "suscribir", "si quiero"];
67
+ var HELP_KEYWORDS = ["help", "ayuda", "info"];
68
+ function classifyKeyword(text) {
69
+ const t = norm(_nullishCoalesce(text, () => ( "")));
70
+ if (!t) return null;
71
+ if (OPT_OUT_KEYWORDS.includes(t)) return "opt_out";
72
+ if (OPT_IN_KEYWORDS.includes(t)) return "opt_in";
73
+ if (HELP_KEYWORDS.includes(t)) return "help";
74
+ return null;
75
+ }
76
+ var keyOf = (k) => `${_nullishCoalesce(k.tenantId, () => ( ""))}|${k.line}|${k.recipient}`;
77
+ var MemoryOptOutStore = class {
78
+ constructor(maxEntries = 1e5) {
79
+ this.maxEntries = maxEntries;
80
+ this.set = /* @__PURE__ */ new Set();
81
+ }
82
+ async isOptedOut(key) {
83
+ return this.set.has(keyOf(key));
84
+ }
85
+ async optOut(key) {
86
+ if (this.set.size >= this.maxEntries) this.set.delete(this.set.values().next().value);
87
+ this.set.add(keyOf(key));
88
+ }
89
+ async optIn(key) {
90
+ this.set.delete(keyOf(key));
91
+ }
92
+ };
93
+
94
+ // src/telephony/rules/dial-destination.ts
95
+ var BLOCKED_MX_PREFIXES = ["800", "900", "700"];
96
+ function toE164Mexico(phone) {
97
+ const digits = (_nullishCoalesce(phone, () => ( ""))).replace(/\D/g, "");
98
+ if (digits.length === 10) return `+52${digits}`;
99
+ if (digits.length === 12 && digits.startsWith("52")) return `+${digits}`;
100
+ if (digits.length === 13 && digits.startsWith("521")) return `+52${digits.slice(3)}`;
101
+ return null;
102
+ }
103
+ function isAllowedDialDestination(e164, blockedPrefixes = BLOCKED_MX_PREFIXES) {
104
+ const match = /^\+52(\d{10})$/.exec(_nullishCoalesce(e164, () => ( "")));
105
+ if (!match) return false;
106
+ const national = match[1];
107
+ if (/^[01]/.test(national)) return false;
108
+ return !blockedPrefixes.some((prefix) => national.startsWith(prefix));
109
+ }
110
+ function sanitizeDialDestination(phone, blockedPrefixes = BLOCKED_MX_PREFIXES) {
111
+ const e164 = toE164Mexico(phone);
112
+ return e164 && isAllowedDialDestination(e164, blockedPrefixes) ? e164 : null;
113
+ }
114
+
115
+ // src/telephony/rules/destination-policy.ts
116
+ var DEFAULT_BLOCKED_PREFIXES = [
117
+ "+52800",
118
+ "+52900",
119
+ "+52700",
120
+ "+1900",
121
+ "+1976",
122
+ "+1809",
123
+ "+1829",
124
+ "+1849",
125
+ "+870",
126
+ "+878",
127
+ "+881",
128
+ "+882",
129
+ "+883",
130
+ "+979"
131
+ ];
132
+ function checkDestination(e164, policy = {}) {
133
+ if (!e164 || !/^\+[1-9]\d{7,14}$/.test(e164)) return { ok: false, reason: "invalid" };
134
+ const blocked = [..._nullishCoalesce(policy.blockedPrefixes, () => ( DEFAULT_BLOCKED_PREFIXES)), ..._nullishCoalesce(policy.extraBlockedPrefixes, () => ( []))];
135
+ if (blocked.some((p) => e164.startsWith(p))) return { ok: false, reason: "blocked_prefix" };
136
+ const allowed = _nullishCoalesce(policy.allowedPrefixes, () => ( ["+52"]));
137
+ if (!allowed.includes("*") && !allowed.some((p) => e164.startsWith(p))) return { ok: false, reason: "country_not_allowed" };
138
+ if (e164.startsWith("+52") && !isAllowedDialDestination(e164, [])) return { ok: false, reason: "invalid" };
139
+ return { ok: true };
140
+ }
141
+
142
+ // src/telephony/rules/phone.ts
143
+ var isE164 = (value) => typeof value === "string" && /^\+[1-9]\d{7,14}$/.test(value);
144
+ var stripChannelPrefix = (value) => value.replace(/^whatsapp:/i, "");
145
+ function normalizeE164(raw) {
146
+ if (!raw) return null;
147
+ const text = stripChannelPrefix(raw.trim());
148
+ if (text.startsWith("+")) {
149
+ const candidate = `+${text.slice(1).replace(/\D/g, "")}`;
150
+ const mx = /^\+521(\d{10})$/.exec(candidate);
151
+ const result = mx ? `+52${mx[1]}` : candidate;
152
+ return isE164(result) ? result : null;
153
+ }
154
+ return toE164Mexico(text);
155
+ }
156
+
157
+ // src/telephony/rules/sanitize.ts
158
+ var CONTROL = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F​-‏‪-‮⁦-⁩]/g;
159
+ var stripControl = (text) => text.replace(CONTROL, "");
160
+ var MAX_SMS_BODY = 1600;
161
+ function sanitizeMessageBody(text, maxLength = MAX_SMS_BODY) {
162
+ const clean = stripControl(String(_nullishCoalesce(text, () => ( "")))).trim();
163
+ if (!clean || clean.length > maxLength) return null;
164
+ return clean;
165
+ }
166
+ function sanitizeTemplateVariable(value, maxLength = 1024) {
167
+ return stripControl(String(_nullishCoalesce(value, () => ( "")))).replace(/[\r\n\t]+/g, " ").replace(/ {4,}/g, " ").trim().slice(0, maxLength);
168
+ }
169
+
170
+ // src/telephony/rules/ttl-cache.ts
171
+ var TtlCache = class {
172
+ constructor(ttlMs, maxEntries = 500) {
173
+ this.ttlMs = ttlMs;
174
+ this.maxEntries = maxEntries;
175
+ this.map = /* @__PURE__ */ new Map();
176
+ /** Devuelve lo cacheado o lo calcula y lo guarda. Una consulta en vuelo se comparte (no hay N peticiones iguales). */
177
+ this.inflight = /* @__PURE__ */ new Map();
178
+ }
179
+ get(key, now = Date.now()) {
180
+ const hit = this.map.get(key);
181
+ if (!hit) return void 0;
182
+ if (hit.until <= now) {
183
+ this.map.delete(key);
184
+ return void 0;
185
+ }
186
+ return hit.value;
187
+ }
188
+ set(key, value, now = Date.now()) {
189
+ this.map.delete(key);
190
+ this.map.set(key, { value, until: now + this.ttlMs });
191
+ if (this.map.size > this.maxEntries) this.map.delete(this.map.keys().next().value);
192
+ }
193
+ async remember(key, load, now = Date.now()) {
194
+ const cached = this.get(key, now);
195
+ if (cached !== void 0) return cached;
196
+ const running = this.inflight.get(key);
197
+ if (running) return running;
198
+ const p = load().then((v) => {
199
+ this.set(key, v);
200
+ return v;
201
+ }).finally(() => this.inflight.delete(key));
202
+ this.inflight.set(key, p);
203
+ return p;
204
+ }
205
+ delete(key) {
206
+ this.map.delete(key);
207
+ }
208
+ clear() {
209
+ this.map.clear();
210
+ }
211
+ };
212
+
213
+ // src/telephony/adapters/simulated.telephony.ts
214
+ var _crypto = require('crypto');
215
+
216
+ // src/telephony/rules/usage-counter.ts
217
+ var UsageCounter = class {
218
+ constructor(windowMs, maxKeys = 5e4) {
219
+ this.windowMs = windowMs;
220
+ this.maxKeys = maxKeys;
221
+ this.buckets = /* @__PURE__ */ new Map();
222
+ }
223
+ add(key, amount = 1, now = Date.now()) {
224
+ const current = this.current(key, now);
225
+ current.total += amount;
226
+ this.buckets.delete(key);
227
+ this.buckets.set(key, current);
228
+ if (this.buckets.size > this.maxKeys) this.buckets.delete(this.buckets.keys().next().value);
229
+ return current.total;
230
+ }
231
+ total(key, now = Date.now()) {
232
+ return this.current(key, now).total;
233
+ }
234
+ exceeds(key, limit, now = Date.now()) {
235
+ return this.total(key, now) >= limit;
236
+ }
237
+ current(key, now) {
238
+ const b = this.buckets.get(key);
239
+ if (b && b.windowStart + this.windowMs > now) return b;
240
+ return { windowStart: now, total: 0 };
241
+ }
242
+ };
243
+ function billableMinutes(durationSeconds, incrementSeconds = 60) {
244
+ if (!Number.isFinite(durationSeconds) || durationSeconds <= 0) return 0;
245
+ return Math.ceil(durationSeconds / incrementSeconds) * incrementSeconds / 60;
246
+ }
247
+
248
+ // src/telephony/telephony.errors.ts
249
+ var _common = require('@nestjs/common');
250
+ var TelephonyProviderException = class extends _chunkQ5Y33L7Bcjs.AppException {
251
+ constructor(provider, reason, options = {}) {
252
+ super("TELEPHONY_PROVIDER_ERROR", MESSAGES[reason], _common.HttpStatus.BAD_GATEWAY, {
253
+ provider,
254
+ reason,
255
+ ...options.status ? { status: options.status } : {}
256
+ });
257
+ this.reason = reason;
258
+ this.retryAfterSeconds = options.retryAfterSeconds;
259
+ Object.defineProperty(this, "raw", { value: options.raw, enumerable: false });
260
+ }
261
+ };
262
+ var MESSAGES = {
263
+ unreachable: "El proveedor de telefon\xEDa no responde.",
264
+ timeout: "El proveedor de telefon\xEDa tard\xF3 demasiado.",
265
+ auth: "Las credenciales del proveedor de telefon\xEDa no son v\xE1lidas.",
266
+ rate_limited: "El proveedor de telefon\xEDa pidi\xF3 esperar antes de reintentar.",
267
+ rejected: "El proveedor de telefon\xEDa rechaz\xF3 la petici\xF3n.",
268
+ invalid_number: "El n\xFAmero no es v\xE1lido para el proveedor.",
269
+ regulation_required: "Falta un tr\xE1mite regulatorio (bundle o direcci\xF3n) para este n\xFAmero.",
270
+ insufficient_funds: "La cuenta del proveedor de telefon\xEDa no tiene saldo.",
271
+ opted_out: "El destinatario pidi\xF3 no recibir mensajes.",
272
+ circuit_open: "El proveedor de telefon\xEDa est\xE1 temporalmente fuera de servicio.",
273
+ overloaded: "Hay demasiadas peticiones al proveedor de telefon\xEDa.",
274
+ not_found: "El recurso no existe en el proveedor de telefon\xEDa.",
275
+ unknown: "El proveedor de telefon\xEDa fall\xF3."
276
+ };
277
+ var UnsupportedCapabilityException = class extends _chunkQ5Y33L7Bcjs.AppException {
278
+ constructor(provider, capability) {
279
+ super("TELEPHONY_UNSUPPORTED", `El proveedor "${provider}" no soporta ${capability}.`, _common.HttpStatus.NOT_IMPLEMENTED, {
280
+ provider,
281
+ capability
282
+ });
283
+ }
284
+ };
285
+ var DestinationNotAllowedException = class extends _chunkQ5Y33L7Bcjs.AppException {
286
+ constructor(reason) {
287
+ super("TELEPHONY_DESTINATION_BLOCKED", "El destino no est\xE1 permitido.", _common.HttpStatus.UNPROCESSABLE_ENTITY, { reason });
288
+ }
289
+ };
290
+ var RecipientOptedOutException = class extends _chunkQ5Y33L7Bcjs.AppException {
291
+ constructor() {
292
+ super("TELEPHONY_OPTED_OUT", MESSAGES.opted_out, _common.HttpStatus.CONFLICT);
293
+ }
294
+ };
295
+ var InvalidMessageException = class extends _chunkQ5Y33L7Bcjs.AppException {
296
+ constructor(message = "El mensaje no es v\xE1lido.") {
297
+ super("TELEPHONY_INVALID_MESSAGE", message, _common.HttpStatus.UNPROCESSABLE_ENTITY);
298
+ }
299
+ };
300
+ var TelephonyLimitExceededException = class extends _chunkQ5Y33L7Bcjs.AppException {
301
+ constructor(limit) {
302
+ super("TELEPHONY_LIMIT_EXCEEDED", "Se alcanz\xF3 un tope de uso de telefon\xEDa.", _common.HttpStatus.TOO_MANY_REQUESTS, { limit });
303
+ }
304
+ };
305
+ var TenantNotConfiguredException = class extends _chunkQ5Y33L7Bcjs.AppException {
306
+ constructor() {
307
+ super("TELEPHONY_TENANT_NOT_CONFIGURED", "La telefon\xEDa de este tenant no est\xE1 configurada.", _common.HttpStatus.NOT_FOUND);
308
+ }
309
+ };
310
+
311
+ // src/telephony/adapters/simulated.telephony.ts
312
+ var JSON_TYPE = "application/json; charset=utf-8";
313
+ var EVENT_TYPES = new Set(Object.values(TELEPHONY_EVENTS));
314
+ function simulatedSignature(url, rawBody, secret) {
315
+ return _crypto.createHmac.call(void 0, "sha256", secret).update(`${url}
316
+ ${rawBody}`, "utf8").digest("hex");
317
+ }
318
+ var SimulatedTelephony = class {
319
+ constructor(o = {}) {
320
+ this.o = o;
321
+ this.portVersion = TELEPHONY_PORT_VERSION;
322
+ this.owned = /* @__PURE__ */ new Map();
323
+ this.byKey = /* @__PURE__ */ new Map();
324
+ this.callStore = /* @__PURE__ */ new Map();
325
+ this.messageStore = /* @__PURE__ */ new Map();
326
+ this.seq = 0;
327
+ this.counter = 0;
328
+ this.provider = _nullishCoalesce(o.name, () => ( "simulated"));
329
+ this.secret = _nullishCoalesce(o.secret, () => ( "simulated-secret"));
330
+ this.inventory = o.inventory ? [...o.inventory] : [];
331
+ const has = (c) => !o.capabilities || o.capabilities.includes(c);
332
+ this.webhooks = this.buildWebhooks();
333
+ if (has("numbers")) this.numbers = this.buildNumbers();
334
+ if (has("voice")) this.voice = this.buildVoice();
335
+ if (has("sms")) this.sms = this.buildSms();
336
+ if (has("whatsapp")) this.whatsapp = this.buildWhatsApp();
337
+ if (has("usage")) this.usage = this.buildUsage();
338
+ }
339
+ // ── Ayudas de prueba ───────────────────────────────────────────────────────────────────────────────────────────
340
+ get calls() {
341
+ return [...new Set(this.callStore.values())];
342
+ }
343
+ get sentMessages() {
344
+ return [...new Set(this.messageStore.values())];
345
+ }
346
+ /** Cierra una llamada con duración, como lo haría el proveedor. */
347
+ completeCall(id, durationSeconds, status = "completed") {
348
+ const call = this.callStore.get(id);
349
+ if (!call) throw new TelephonyProviderException(this.provider, "not_found");
350
+ const done = { ...call, status, durationSeconds, billableMinutes: billableMinutes(durationSeconds) };
351
+ this.callStore.set(id, done);
352
+ return done;
353
+ }
354
+ /** Una petición de webhook correctamente firmada con eventos normalizados (sin `provider`/`receivedAt`). */
355
+ webhookFor(events, url = "https://example.test/telephony/webhooks/simulated") {
356
+ const rawBody = JSON.stringify({ events });
357
+ return { url, rawBody, headers: { "x-simulated-signature": simulatedSignature(url, rawBody, this.secret) } };
358
+ }
359
+ // ── Números ────────────────────────────────────────────────────────────────────────────────────────────────────
360
+ nextNumber() {
361
+ this.counter += 1;
362
+ return `+5255${String(1e7 + this.counter).slice(-8)}`;
363
+ }
364
+ available(limit, filter) {
365
+ if (this.o.inventory) return this.inventory.filter(filter).slice(0, limit);
366
+ const out = [];
367
+ while (out.length < limit) {
368
+ const n = this.nextNumber();
369
+ if (filter(n)) out.push(n);
370
+ }
371
+ return out;
372
+ }
373
+ buildNumbers() {
374
+ const t = this;
375
+ const toAvailable = (n) => ({
376
+ number: n,
377
+ country: "MX",
378
+ type: "local",
379
+ capabilities: { voice: true, sms: true },
380
+ requiresRegulation: false
381
+ });
382
+ return {
383
+ async search(query = {}) {
384
+ const limit = Math.min(_nullishCoalesce(query.limit, () => ( 10)), 50);
385
+ const area = query.areaCode;
386
+ const contains = query.contains;
387
+ return t.available(limit, (n) => (!area || n.startsWith(`+52${area}`)) && (!contains || n.includes(contains))).map(toAvailable);
388
+ },
389
+ async requirements(country = "MX", type = "local") {
390
+ return { country, type, needsBundle: false, needsAddress: false, notes: ["El simulador no exige tr\xE1mites."], source: "static" };
391
+ },
392
+ async monthlyCost() {
393
+ return { amount: "1.15", currency: "USD" };
394
+ },
395
+ async provision(input) {
396
+ if (input.idempotencyKey) {
397
+ const existing = t.byKey.get(input.idempotencyKey);
398
+ if (existing) return _nullishCoalesce(t.owned.get(existing), () => ( null));
399
+ }
400
+ const number = _nullishCoalesce(input.number, () => ( t.available(1, () => true)[0]));
401
+ if (!number) return null;
402
+ t.inventory = t.inventory.filter((n) => n !== number);
403
+ const phone = {
404
+ id: `PN_sim_${++t.seq}`,
405
+ number,
406
+ provider: t.provider,
407
+ status: "active",
408
+ country: "MX",
409
+ type: "local",
410
+ capabilities: { voice: true, sms: true },
411
+ voiceUrl: input.voiceUrl,
412
+ ...input.smsUrl ? { smsUrl: input.smsUrl } : {},
413
+ ...input.label ? { label: input.label } : {},
414
+ monthlyCost: { amount: "1.15", currency: "USD" },
415
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
416
+ };
417
+ t.owned.set(phone.id, phone);
418
+ if (input.idempotencyKey) t.byKey.set(input.idempotencyKey, phone.id);
419
+ return phone;
420
+ },
421
+ async configure(id, input) {
422
+ const phone = t.owned.get(id);
423
+ if (!phone) throw new TelephonyProviderException(t.provider, "not_found");
424
+ const next = {
425
+ ...phone,
426
+ ...input.voiceUrl ? { voiceUrl: input.voiceUrl } : {},
427
+ ...input.smsUrl ? { smsUrl: input.smsUrl } : {},
428
+ ...input.label ? { label: input.label } : {}
429
+ };
430
+ t.owned.set(id, next);
431
+ return next;
432
+ },
433
+ async get(id) {
434
+ const phone = t.owned.get(id);
435
+ if (!phone) throw new TelephonyProviderException(t.provider, "not_found");
436
+ return phone;
437
+ },
438
+ async list(options = {}) {
439
+ const all = [...t.owned.values()];
440
+ const start = Number(_nullishCoalesce(options.cursor, () => ( 0))) || 0;
441
+ const limit = Math.min(_nullishCoalesce(options.limit, () => ( 50)), 200);
442
+ const items = all.slice(start, start + limit);
443
+ return { items, ...start + limit < all.length ? { nextCursor: String(start + limit) } : {} };
444
+ },
445
+ async release(id) {
446
+ t.owned.delete(id);
447
+ },
448
+ async transfer(id) {
449
+ const phone = t.owned.get(id);
450
+ if (!phone) throw new TelephonyProviderException(t.provider, "not_found");
451
+ return phone;
452
+ }
453
+ };
454
+ }
455
+ // ── Voz ────────────────────────────────────────────────────────────────────────────────────────────────────────
456
+ buildVoice() {
457
+ const t = this;
458
+ const answer = (instruction) => {
459
+ let safe = instruction;
460
+ if (instruction.kind === "dial") {
461
+ const to = sanitizeDialDestination(instruction.to);
462
+ safe = to ? { ...instruction, to } : { kind: "hangup", message: instruction.fallbackMessage };
463
+ }
464
+ return { body: JSON.stringify(safe), contentType: JSON_TYPE };
465
+ };
466
+ return {
467
+ buildAnswer: answer,
468
+ async placeCall(input) {
469
+ if (!isE164(input.from) || !isE164(input.to)) throw new TelephonyProviderException(t.provider, "invalid_number");
470
+ if (input.idempotencyKey) {
471
+ const prior = t.callStore.get(`key:${input.idempotencyKey}`);
472
+ if (prior) return prior;
473
+ }
474
+ const call = {
475
+ id: `CA_sim_${++t.seq}`,
476
+ provider: t.provider,
477
+ direction: "outbound",
478
+ from: input.from,
479
+ to: input.to,
480
+ status: "queued",
481
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
482
+ };
483
+ t.callStore.set(call.id, call);
484
+ if (input.idempotencyKey) t.callStore.set(`key:${input.idempotencyKey}`, call);
485
+ return call;
486
+ },
487
+ async placeTestCall() {
488
+ return !t.o.failTestCalls;
489
+ },
490
+ async getCall(id) {
491
+ const call = t.callStore.get(id);
492
+ if (!call) throw new TelephonyProviderException(t.provider, "not_found");
493
+ return call;
494
+ }
495
+ };
496
+ }
497
+ // ── Mensajes ───────────────────────────────────────────────────────────────────────────────────────────────────
498
+ message(channel, from, to, body, key) {
499
+ const idKey = key ? `key:${key}` : void 0;
500
+ const prior = idKey ? this.messageStore.get(idKey) : void 0;
501
+ if (prior) return prior;
502
+ const msg = {
503
+ id: `MM_sim_${++this.seq}`,
504
+ provider: this.provider,
505
+ channel,
506
+ direction: "outbound",
507
+ from,
508
+ to,
509
+ status: "queued",
510
+ body,
511
+ segments: Math.max(1, Math.ceil(body.length / 160)),
512
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
513
+ };
514
+ this.messageStore.set(msg.id, msg);
515
+ if (idKey) this.messageStore.set(idKey, msg);
516
+ return msg;
517
+ }
518
+ buildSms() {
519
+ const t = this;
520
+ return {
521
+ async send(input) {
522
+ if (!isE164(input.from) || !isE164(input.to)) throw new TelephonyProviderException(t.provider, "invalid_number");
523
+ return t.message("sms", input.from, input.to, input.body, input.idempotencyKey);
524
+ },
525
+ async get(id) {
526
+ const m = t.messageStore.get(id);
527
+ if (!m) throw new TelephonyProviderException(t.provider, "not_found");
528
+ return m;
529
+ }
530
+ };
531
+ }
532
+ buildWhatsApp() {
533
+ const t = this;
534
+ return {
535
+ async sendText(input) {
536
+ if (!isE164(input.to)) throw new TelephonyProviderException(t.provider, "invalid_number");
537
+ return t.message("whatsapp", _nullishCoalesce(input.from, () => ( "")), input.to, input.body, input.idempotencyKey);
538
+ },
539
+ async sendTemplate(input) {
540
+ if (!isE164(input.to)) throw new TelephonyProviderException(t.provider, "invalid_number");
541
+ return t.message("whatsapp", _nullishCoalesce(input.from, () => ( "")), input.to, `[plantilla ${input.template}] ${(_nullishCoalesce(input.variables, () => ( []))).join(" | ")}`, input.idempotencyKey);
542
+ },
543
+ async get(id) {
544
+ const m = t.messageStore.get(id);
545
+ if (!m) throw new TelephonyProviderException(t.provider, "not_found");
546
+ return m;
547
+ }
548
+ };
549
+ }
550
+ // ── Uso ────────────────────────────────────────────────────────────────────────────────────────────────────────
551
+ buildUsage() {
552
+ const t = this;
553
+ return {
554
+ async query(q) {
555
+ const inRange = (iso) => !iso || iso.slice(0, 10) >= q.from && iso.slice(0, 10) < q.to;
556
+ const base = { category: q.category, periodStart: q.from, periodEnd: q.to };
557
+ if (q.category === "numbers") {
558
+ const count = [...t.owned.values()].filter((n) => !q.number || n.number === q.number).length;
559
+ return [{ ...base, count, units: count, unit: "numbers", providerCost: { amount: (count * 1.15).toFixed(2), currency: "USD" } }];
560
+ }
561
+ if (q.category === "voice") {
562
+ const calls = [...t.callStore.values()].filter(
563
+ (c, i, a) => a.indexOf(c) === i && (!q.number || c.from === q.number || c.to === q.number) && inRange(c.startedAt)
564
+ );
565
+ return [{ ...base, count: calls.length, units: calls.reduce((s, c) => s + (_nullishCoalesce(c.billableMinutes, () => ( 0))), 0), unit: "minutes" }];
566
+ }
567
+ const messages = [...t.messageStore.values()].filter(
568
+ (m, i, a) => a.indexOf(m) === i && m.channel === q.category && (!q.number || m.from === q.number || m.to === q.number) && inRange(m.createdAt)
569
+ );
570
+ return [{ ...base, count: messages.length, units: messages.reduce((s, m) => s + (_nullishCoalesce(m.segments, () => ( 1))), 0), unit: "messages" }];
571
+ }
572
+ };
573
+ }
574
+ // ── Webhooks ───────────────────────────────────────────────────────────────────────────────────────────────────
575
+ buildWebhooks() {
576
+ const t = this;
577
+ const header = (r, name) => {
578
+ for (const [k, v] of Object.entries(r.headers)) if (k.toLowerCase() === name) return Array.isArray(v) ? v[0] : v;
579
+ return void 0;
580
+ };
581
+ return {
582
+ verify(request) {
583
+ const sig = header(request, "x-simulated-signature");
584
+ if (!sig || request.rawBody === void 0) return false;
585
+ return _chunk2RQINZCRcjs.constantTimeEqual.call(void 0, simulatedSignature(request.url, request.rawBody, t.secret), sig);
586
+ },
587
+ parse(request) {
588
+ let events;
589
+ try {
590
+ events = JSON.parse(_nullishCoalesce(request.rawBody, () => ( ""))).events;
591
+ } catch (e2) {
592
+ return [];
593
+ }
594
+ if (!Array.isArray(events)) return [];
595
+ const now = Date.now();
596
+ return events.filter((e) => !!e && typeof e === "object" && EVENT_TYPES.has(String(e.type)) && typeof e.id === "string").slice(0, 100).map((e) => ({ ...e, provider: t.provider, receivedAt: now }));
597
+ },
598
+ acknowledge: () => ({ body: "{}", contentType: JSON_TYPE })
599
+ };
600
+ }
601
+ };
602
+
603
+ // src/telephony/adapters/twilio.telephony.ts
604
+
605
+
606
+ // src/telephony/rules/provider-gate.ts
607
+ var GateRejectedError = class extends Error {
608
+ constructor(reason) {
609
+ super(reason);
610
+ this.reason = reason;
611
+ }
612
+ };
613
+ var ProviderGate = class {
614
+ constructor(options = {}) {
615
+ this.active = 0;
616
+ this.waiting = [];
617
+ this.failures = 0;
618
+ this.openUntil = 0;
619
+ this.o = { maxConcurrent: 20, maxQueue: 100, failureThreshold: 5, cooldownMs: 3e4, now: Date.now, ...options };
620
+ }
621
+ get isOpen() {
622
+ return this.o.now() < this.openUntil;
623
+ }
624
+ /** Envuelve un `fetch`: cuenta como fallo una excepción o un 5xx (un 4xx/429 no es caída del proveedor). */
625
+ wrap(inner) {
626
+ return (async (input, init) => {
627
+ if (this.isOpen) throw new GateRejectedError("circuit_open");
628
+ await this.acquire();
629
+ try {
630
+ const res = await inner(input, init);
631
+ if (res.status >= 500) this.fail();
632
+ else this.failures = 0;
633
+ return res;
634
+ } catch (e) {
635
+ this.fail();
636
+ throw e;
637
+ } finally {
638
+ this.release();
639
+ }
640
+ });
641
+ }
642
+ fail() {
643
+ if (++this.failures >= this.o.failureThreshold) {
644
+ this.openUntil = this.o.now() + this.o.cooldownMs;
645
+ this.failures = 0;
646
+ }
647
+ }
648
+ async acquire() {
649
+ if (this.active < this.o.maxConcurrent) {
650
+ this.active++;
651
+ return;
652
+ }
653
+ if (this.waiting.length >= this.o.maxQueue) throw new GateRejectedError("overloaded");
654
+ await new Promise((resolve) => this.waiting.push(resolve));
655
+ }
656
+ release() {
657
+ const next = this.waiting.shift();
658
+ if (next) next();
659
+ else this.active--;
660
+ }
661
+ };
662
+
663
+ // src/telephony/provider-http.ts
664
+ function createProviderHttp(provider, options = {}) {
665
+ const gate = options.gate instanceof ProviderGate ? options.gate : new ProviderGate(options.gate);
666
+ const inner = gate.wrap(
667
+ _chunkQVLTEABJcjs.fetchResiliente.call(void 0, {
668
+ proveedor: provider,
669
+ tenantId: options.tenantId,
670
+ fetchImpl: options.fetchImpl,
671
+ ..._nullishCoalesce(options.resilience, () => ( {}))
672
+ })
673
+ );
674
+ async function request(url, init) {
675
+ let response;
676
+ try {
677
+ response = await inner(url, init);
678
+ } catch (e) {
679
+ if (e instanceof GateRejectedError) throw new TelephonyProviderException(provider, e.reason);
680
+ if (e instanceof _chunkQVLTEABJcjs.ProviderUnavailableException) {
681
+ throw new TelephonyProviderException(provider, _optionalChain([e, 'access', _ => _.details, 'optionalAccess', _2 => _2.reason]) === "timeout" ? "timeout" : "unreachable");
682
+ }
683
+ throw new TelephonyProviderException(provider, "unreachable");
684
+ }
685
+ const text = await response.text();
686
+ let body;
687
+ if (text) {
688
+ try {
689
+ body = JSON.parse(text);
690
+ } catch (e3) {
691
+ body = text;
692
+ }
693
+ }
694
+ return { ok: response.ok, status: response.status, body, headers: response.headers };
695
+ }
696
+ return { request, gate };
697
+ }
698
+ var TWILIO_CODES = {
699
+ 20003: "auth",
700
+ 20429: "rate_limited",
701
+ 21211: "invalid_number",
702
+ 21214: "invalid_number",
703
+ 21408: "invalid_number",
704
+ 21610: "opted_out",
705
+ 21608: "insufficient_funds",
706
+ 21649: "regulation_required",
707
+ 21650: "regulation_required",
708
+ 21651: "regulation_required",
709
+ 21652: "regulation_required",
710
+ 21631: "regulation_required",
711
+ 22300: "regulation_required"
712
+ };
713
+ function providerError(provider, r, codeMap = TWILIO_CODES) {
714
+ const code = Number(_optionalChain([r, 'access', _3 => _3.body, 'optionalAccess', _4 => _4.code]));
715
+ let reason = _nullishCoalesce(codeMap[code], () => ( "unknown"));
716
+ if (reason === "unknown") {
717
+ if (r.status === 401 || r.status === 403) reason = "auth";
718
+ else if (r.status === 404) reason = "not_found";
719
+ else if (r.status === 429) reason = "rate_limited";
720
+ else if (r.status === 402) reason = "insufficient_funds";
721
+ else if (r.status >= 400 && r.status < 500) reason = "rejected";
722
+ }
723
+ const retryAfter = Number(r.headers.get("retry-after"));
724
+ return new TelephonyProviderException(provider, reason, {
725
+ status: r.status,
726
+ raw: r.body,
727
+ retryAfterSeconds: Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : void 0
728
+ });
729
+ }
730
+
731
+ // src/telephony/adapters/twilio.telephony.ts
732
+ var DEFAULT_BASE_URL = "https://api.twilio.com";
733
+ var XML = "text/xml; charset=utf-8";
734
+ function twilioSignature(url, params, authToken) {
735
+ const data = Object.keys(params).sort().reduce((acc, key) => acc + key + params[key], url);
736
+ return _crypto.createHmac.call(void 0, "sha1", authToken).update(data, "utf8").digest("base64");
737
+ }
738
+ var escapeXml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
739
+ var wrap = (inner) => ({
740
+ body: `<?xml version="1.0" encoding="UTF-8"?><Response>${inner}</Response>`,
741
+ contentType: XML
742
+ });
743
+ var DIAL_CODES = { MX: "52", US: "1", CA: "1", CO: "57", AR: "54", ES: "34", CL: "56", PE: "51", BR: "55" };
744
+ var TYPE_PATH = { local: "Local", mobile: "Mobile", toll_free: "TollFree" };
745
+ var PRICE_TYPE = { local: "local", mobile: "mobile", toll_free: "toll free" };
746
+ var CALL_STATUS = {
747
+ queued: "queued",
748
+ ringing: "ringing",
749
+ "in-progress": "in_progress",
750
+ completed: "completed",
751
+ busy: "busy",
752
+ "no-answer": "no_answer",
753
+ failed: "failed",
754
+ canceled: "canceled"
755
+ };
756
+ var MESSAGE_STATUS = {
757
+ accepted: "queued",
758
+ scheduled: "queued",
759
+ queued: "queued",
760
+ sending: "queued",
761
+ sent: "sent",
762
+ delivered: "delivered",
763
+ read: "read",
764
+ undelivered: "undelivered",
765
+ failed: "failed",
766
+ received: "received",
767
+ receiving: "received"
768
+ };
769
+ var ENDED = /* @__PURE__ */ new Set(["completed", "busy", "no-answer", "failed", "canceled"]);
770
+ function money(price, unit) {
771
+ if (price === null || price === void 0 || price === "") return void 0;
772
+ const n = Number(price);
773
+ if (!Number.isFinite(n)) return void 0;
774
+ const amount = String(price).replace(/^-/, "");
775
+ return { amount, currency: String(_nullishCoalesce(unit, () => ( "USD"))).toUpperCase() };
776
+ }
777
+ var asDate = (v) => {
778
+ const t = typeof v === "string" ? Date.parse(v) : NaN;
779
+ return Number.isNaN(t) ? void 0 : new Date(t).toISOString();
780
+ };
781
+ var TwilioTelephony = class {
782
+ constructor(o) {
783
+ this.o = o;
784
+ this.provider = "twilio";
785
+ this.portVersion = TELEPHONY_PORT_VERSION;
786
+ this.cache = new TtlCache(3e4, 200);
787
+ this.priceCache = new TtlCache(60 * 6e4, 50);
788
+ if (!o.accountSid || !o.authToken) throw new Error("TwilioTelephony: faltan accountSid y authToken.");
789
+ this.http = createProviderHttp("twilio", o);
790
+ this.accountUrl = `${_nullishCoalesce(o.baseUrl, () => ( DEFAULT_BASE_URL))}/2010-04-01/Accounts/${o.accountSid}`;
791
+ this.numbers = this.buildNumbers();
792
+ this.voice = this.buildVoice();
793
+ this.sms = this.buildSms();
794
+ this.whatsapp = this.buildWhatsApp();
795
+ this.usage = this.buildUsage();
796
+ this.webhooks = this.buildWebhooks();
797
+ }
798
+ // ── HTTP ──────────────────────────────────────────────────────────────────────────────────────────────────────
799
+ auth() {
800
+ return { Authorization: `Basic ${Buffer.from(`${this.o.accountSid}:${this.o.authToken}`).toString("base64")}` };
801
+ }
802
+ get(url) {
803
+ return this.http.request(url, { method: "GET", headers: this.auth() });
804
+ }
805
+ post(url, form, idempotencyKey) {
806
+ const body = new URLSearchParams();
807
+ for (const [k, v] of Object.entries(form)) if (v !== void 0) body.set(k, v);
808
+ const headers = { ...this.auth() };
809
+ if (idempotencyKey) headers["I-Twilio-Idempotency-Token"] = idempotencyKey;
810
+ return this.http.request(url, { method: "POST", headers, body });
811
+ }
812
+ async ok(r) {
813
+ const res = await r;
814
+ if (!res.ok) throw providerError("twilio", res);
815
+ return _nullishCoalesce(res.body, () => ( {}));
816
+ }
817
+ acct(path) {
818
+ return `${this.accountUrl}${path}`;
819
+ }
820
+ /** `cursor` opaco = el `next_page_uri` de Twilio; solo se acepta si es de ESTA cuenta (no se puede apuntar a otra). */
821
+ encodeCursor(nextUri) {
822
+ return typeof nextUri === "string" && nextUri ? Buffer.from(nextUri).toString("base64url") : void 0;
823
+ }
824
+ decodeCursor(cursor) {
825
+ const uri = Buffer.from(cursor, "base64url").toString("utf8");
826
+ if (!uri.startsWith(`/2010-04-01/Accounts/${this.o.accountSid}/`)) {
827
+ throw new TelephonyProviderException("twilio", "rejected");
828
+ }
829
+ return `${_nullishCoalesce(this.o.baseUrl, () => ( DEFAULT_BASE_URL))}${uri}`;
830
+ }
831
+ // ── Números ───────────────────────────────────────────────────────────────────────────────────────────────────
832
+ toPhoneNumber(b, country, type) {
833
+ const needsReg = b.address_requirements && b.address_requirements !== "none" && !b.address_sid;
834
+ return {
835
+ id: b.sid,
836
+ number: b.phone_number,
837
+ provider: "twilio",
838
+ status: b.status === "released" ? "released" : needsReg ? "pending_regulation" : "active",
839
+ ...country ? { country } : {},
840
+ ...type ? { type } : {},
841
+ ...b.friendly_name ? { label: b.friendly_name } : {},
842
+ ...b.capabilities ? { capabilities: { voice: !!b.capabilities.voice, sms: !!b.capabilities.sms } } : {},
843
+ ...b.voice_url ? { voiceUrl: b.voice_url } : {},
844
+ ...b.sms_url ? { smsUrl: b.sms_url } : {},
845
+ ...asDate(b.date_created) ? { createdAt: asDate(b.date_created) } : {}
846
+ };
847
+ }
848
+ buildNumbers() {
849
+ const self = this;
850
+ return {
851
+ async search(query = {}) {
852
+ const country = (_nullishCoalesce(query.country, () => ( "MX"))).toUpperCase();
853
+ const type = _nullishCoalesce(query.type, () => ( "local"));
854
+ const areaCode = _nullishCoalesce(query.areaCode, () => ( self.o.areaCode));
855
+ const q = new URLSearchParams({ PageSize: String(Math.min(_nullishCoalesce(query.limit, () => ( 10)), 50)) });
856
+ if (_optionalChain([query, 'access', _5 => _5.needs, 'optionalAccess', _6 => _6.voice]) !== false) q.set("VoiceEnabled", "true");
857
+ if (_optionalChain([query, 'access', _7 => _7.needs, 'optionalAccess', _8 => _8.sms])) q.set("SmsEnabled", "true");
858
+ if (query.city) q.set("InLocality", query.city);
859
+ if (areaCode && (country === "US" || country === "CA")) q.set("AreaCode", areaCode);
860
+ else if (areaCode || query.contains) q.set("Contains", `+${_nullishCoalesce(DIAL_CODES[country], () => ( ""))}${_nullishCoalesce(areaCode, () => ( ""))}${_nullishCoalesce(query.contains, () => ( ""))}*`);
861
+ else if (query.contains) q.set("Contains", query.contains);
862
+ const body = await self.ok(self.get(self.acct(`/AvailablePhoneNumbers/${country}/${TYPE_PATH[type]}.json?${q}`)));
863
+ return (_nullishCoalesce(body.available_phone_numbers, () => ( []))).map((n) => ({
864
+ number: n.phone_number,
865
+ country: _nullishCoalesce(n.iso_country, () => ( country)),
866
+ type,
867
+ ...n.locality ? { city: n.locality } : {},
868
+ ...n.region ? { region: n.region } : {},
869
+ capabilities: { voice: !!_optionalChain([n, 'access', _9 => _9.capabilities, 'optionalAccess', _10 => _10.voice]), sms: !!_optionalChain([n, 'access', _11 => _11.capabilities, 'optionalAccess', _12 => _12.SMS]), mms: !!_optionalChain([n, 'access', _13 => _13.capabilities, 'optionalAccess', _14 => _14.MMS]) },
870
+ requiresRegulation: !!n.address_requirements && n.address_requirements !== "none"
871
+ }));
872
+ },
873
+ async requirements(country = "MX", type = "local") {
874
+ const c = country.toUpperCase();
875
+ if (c === "MX") {
876
+ return {
877
+ country: c,
878
+ type,
879
+ needsBundle: true,
880
+ needsAddress: true,
881
+ source: "static",
882
+ notes: [
883
+ "Twilio exige un Regulatory Bundle aprobado para M\xE9xico y una direcci\xF3n registrada en la cuenta.",
884
+ "Los crea y aprueba una persona en la consola de Twilio; la aprobaci\xF3n no es inmediata.",
885
+ "El n\xFAmero debe ser de la zona de la direcci\xF3n del Bundle."
886
+ ]
887
+ };
888
+ }
889
+ return {
890
+ country: c,
891
+ type,
892
+ needsBundle: false,
893
+ needsAddress: false,
894
+ source: "static",
895
+ notes: ["Sin datos incluidos para este pa\xEDs: consulta los requisitos regulatorios en la consola del proveedor."]
896
+ };
897
+ },
898
+ async monthlyCost(country = "MX", type = "local") {
899
+ const c = country.toUpperCase();
900
+ return self.priceCache.remember(`${c}|${type}`, async () => {
901
+ const res = await self.get(`${_nullishCoalesce(self.o.pricingBaseUrl, () => ( "https://pricing.twilio.com"))}/v1/PhoneNumbers/Countries/${c}`);
902
+ if (!res.ok) return null;
903
+ const row = (_nullishCoalesce(_optionalChain([res, 'access', _15 => _15.body, 'optionalAccess', _16 => _16.phone_number_prices]), () => ( []))).find((p) => p.number_type === PRICE_TYPE[type]);
904
+ return _nullishCoalesce(money(_nullishCoalesce(_optionalChain([row, 'optionalAccess', _17 => _17.current_price]), () => ( _optionalChain([row, 'optionalAccess', _18 => _18.base_price]))), _optionalChain([res, 'access', _19 => _19.body, 'optionalAccess', _20 => _20.price_unit])), () => ( null));
905
+ });
906
+ },
907
+ async provision(input) {
908
+ const search = _nullishCoalesce(input.search, () => ( {}));
909
+ let candidate = input.number;
910
+ if (!candidate) {
911
+ const found = await this.search({ ...search, limit: 1, needs: { voice: true, ...search.needs } });
912
+ candidate = _optionalChain([found, 'access', _21 => _21[0], 'optionalAccess', _22 => _22.number]);
913
+ }
914
+ if (!candidate) return null;
915
+ const form = {
916
+ PhoneNumber: candidate,
917
+ VoiceUrl: input.voiceUrl,
918
+ VoiceMethod: "POST",
919
+ SmsUrl: input.smsUrl,
920
+ SmsMethod: input.smsUrl ? "POST" : void 0,
921
+ StatusCallback: input.statusCallbackUrl,
922
+ FriendlyName: input.label,
923
+ BundleSid: self.o.bundleSid,
924
+ AddressSid: self.o.addressSid,
925
+ ..._nullishCoalesce(input.extra, () => ( {}))
926
+ };
927
+ const body = await self.ok(self.post(self.acct("/IncomingPhoneNumbers.json"), form, input.idempotencyKey));
928
+ if (!body.sid || !body.phone_number) throw new TelephonyProviderException("twilio", "unknown", { raw: body });
929
+ const country = (_nullishCoalesce(search.country, () => ( "MX"))).toUpperCase();
930
+ const type = _nullishCoalesce(search.type, () => ( "local"));
931
+ const phone = self.toPhoneNumber(body, country, type);
932
+ const monthlyCost = await this.monthlyCost(country, type).catch(() => null);
933
+ return monthlyCost ? { ...phone, monthlyCost } : phone;
934
+ },
935
+ async configure(id, input) {
936
+ const body = await self.ok(
937
+ self.post(self.acct(`/IncomingPhoneNumbers/${encodeURIComponent(id)}.json`), {
938
+ VoiceUrl: input.voiceUrl,
939
+ VoiceMethod: input.voiceUrl ? "POST" : void 0,
940
+ VoiceFallbackUrl: input.voiceFallbackUrl,
941
+ SmsUrl: input.smsUrl,
942
+ SmsMethod: input.smsUrl ? "POST" : void 0,
943
+ StatusCallback: input.statusCallbackUrl,
944
+ FriendlyName: input.label
945
+ })
946
+ );
947
+ return self.toPhoneNumber(body);
948
+ },
949
+ async get(id) {
950
+ return self.toPhoneNumber(await self.ok(self.get(self.acct(`/IncomingPhoneNumbers/${encodeURIComponent(id)}.json`))));
951
+ },
952
+ async list(options = {}) {
953
+ const url = options.cursor ? self.decodeCursor(options.cursor) : self.acct(`/IncomingPhoneNumbers.json?PageSize=${Math.min(_nullishCoalesce(options.limit, () => ( 50)), 200)}`);
954
+ const body = await self.ok(self.get(url));
955
+ const next = self.encodeCursor(body.next_page_uri);
956
+ return {
957
+ items: (_nullishCoalesce(body.incoming_phone_numbers, () => ( []))).map((n) => self.toPhoneNumber(n)),
958
+ ...next ? { nextCursor: next } : {}
959
+ };
960
+ },
961
+ async release(id) {
962
+ const r = await self.http.request(self.acct(`/IncomingPhoneNumbers/${encodeURIComponent(id)}.json`), {
963
+ method: "DELETE",
964
+ headers: self.auth()
965
+ });
966
+ if (!r.ok && r.status !== 404) throw providerError("twilio", r);
967
+ },
968
+ async transfer(id, toAccountId) {
969
+ const body = await self.ok(self.post(self.acct(`/IncomingPhoneNumbers/${encodeURIComponent(id)}.json`), { AccountSid: toAccountId }));
970
+ return self.toPhoneNumber(body);
971
+ }
972
+ };
973
+ }
974
+ // ── Voz ───────────────────────────────────────────────────────────────────────────────────────────────────────
975
+ toCall(b) {
976
+ const duration = b.duration !== void 0 && b.duration !== null ? Number(b.duration) : void 0;
977
+ const cost = money(b.price, b.price_unit);
978
+ return {
979
+ id: b.sid,
980
+ provider: "twilio",
981
+ direction: String(_nullishCoalesce(b.direction, () => ( ""))).startsWith("inbound") ? "inbound" : "outbound",
982
+ from: _nullishCoalesce(_nullishCoalesce(b.from, () => ( b.from_formatted)), () => ( "")),
983
+ to: _nullishCoalesce(_nullishCoalesce(b.to, () => ( b.to_formatted)), () => ( "")),
984
+ status: _nullishCoalesce(CALL_STATUS[b.status], () => ( "queued")),
985
+ ...duration !== void 0 && Number.isFinite(duration) ? { durationSeconds: duration, billableMinutes: billableMinutes(duration) } : {},
986
+ ...cost ? { cost } : {},
987
+ ...asDate(b.start_time) ? { startedAt: asDate(b.start_time) } : {},
988
+ ...asDate(b.end_time) ? { endedAt: asDate(b.end_time) } : {}
989
+ };
990
+ }
991
+ answer(instruction) {
992
+ const language = _nullishCoalesce(_nullishCoalesce(instruction.language, () => ( this.o.language)), () => ( "es-MX"));
993
+ switch (instruction.kind) {
994
+ case "relay": {
995
+ if (!this.o.allowInsecureRelay && !/^wss:\/\//i.test(instruction.url)) {
996
+ throw new Error("TwilioTelephony: la URL del relay debe ser wss:// (conexi\xF3n cifrada).");
997
+ }
998
+ const params = Object.entries(_nullishCoalesce(instruction.parameters, () => ( {}))).map(([name, value]) => `<Parameter name="${escapeXml(name)}" value="${escapeXml(value)}"/>`).join("");
999
+ const voice = this.o.voice ? ` voice="${escapeXml(this.o.voice)}"` : "";
1000
+ return wrap(
1001
+ `<Connect action="${escapeXml(instruction.actionUrl)}"><ConversationRelay url="${escapeXml(instruction.url)}" welcomeGreeting="${escapeXml(instruction.greeting)}" language="${escapeXml(language)}" ttsProvider="${escapeXml(_nullishCoalesce(this.o.ttsProvider, () => ( "Google")))}" transcriptionProvider="${escapeXml(_nullishCoalesce(this.o.transcriptionProvider, () => ( "Google")))}"${voice} interruptible="${_nullishCoalesce(this.o.interruptible, () => ( "speech"))}">${params}</ConversationRelay></Connect>`
1002
+ );
1003
+ }
1004
+ case "dial": {
1005
+ const destination = sanitizeDialDestination(instruction.to);
1006
+ if (!destination) {
1007
+ return this.answer({
1008
+ kind: "hangup",
1009
+ message: _nullishCoalesce(_nullishCoalesce(instruction.fallbackMessage, () => ( this.o.unavailableMessage)), () => ( DEFAULT_TEXTS.unavailable)),
1010
+ language
1011
+ });
1012
+ }
1013
+ const callerId = instruction.callerId && isE164(instruction.callerId) ? ` callerId="${escapeXml(instruction.callerId)}"` : "";
1014
+ return wrap(
1015
+ `<Dial${callerId} timeout="${_nullishCoalesce(instruction.ringSeconds, () => ( 25))}" timeLimit="${_nullishCoalesce(instruction.maxSeconds, () => ( 1800))}">${escapeXml(destination)}</Dial>`
1016
+ );
1017
+ }
1018
+ case "reject":
1019
+ return wrap("<Reject/>");
1020
+ case "hangup":
1021
+ return wrap(
1022
+ instruction.message ? `<Say language="${escapeXml(language)}">${escapeXml(instruction.message)}</Say><Hangup/>` : "<Hangup/>"
1023
+ );
1024
+ }
1025
+ }
1026
+ buildVoice() {
1027
+ const self = this;
1028
+ return {
1029
+ buildAnswer: (instruction) => self.answer(instruction),
1030
+ async placeCall(input) {
1031
+ if (!isE164(input.from) || !isE164(input.to)) throw new TelephonyProviderException("twilio", "invalid_number");
1032
+ const body = await self.ok(
1033
+ self.post(
1034
+ self.acct("/Calls.json"),
1035
+ {
1036
+ From: input.from,
1037
+ To: input.to,
1038
+ ...input.answer ? { Twiml: self.answer(input.answer).body } : { Url: input.answerUrl },
1039
+ StatusCallback: input.statusCallbackUrl,
1040
+ StatusCallbackEvent: input.statusCallbackUrl ? "completed" : void 0,
1041
+ StatusCallbackMethod: input.statusCallbackUrl ? "POST" : void 0,
1042
+ Timeout: input.ringSeconds ? String(input.ringSeconds) : void 0,
1043
+ TimeLimit: input.maxSeconds ? String(input.maxSeconds) : void 0,
1044
+ ..._nullishCoalesce(input.extra, () => ( {}))
1045
+ },
1046
+ input.idempotencyKey
1047
+ )
1048
+ );
1049
+ return self.toCall({ direction: "outbound-api", from: input.from, to: input.to, ...body });
1050
+ },
1051
+ async placeTestCall(from, to) {
1052
+ try {
1053
+ await this.placeCall({
1054
+ from,
1055
+ to,
1056
+ answer: { kind: "reject" },
1057
+ // Con el desvío «si no contesto» la compañía lo reenvía tras ~20-30 s sin respuesta.
1058
+ ringSeconds: _nullishCoalesce(self.o.testCallRingSeconds, () => ( 40))
1059
+ });
1060
+ return true;
1061
+ } catch (e4) {
1062
+ return false;
1063
+ }
1064
+ },
1065
+ async getCall(id) {
1066
+ return self.toCall(await self.ok(self.get(self.acct(`/Calls/${encodeURIComponent(id)}.json`))));
1067
+ }
1068
+ };
1069
+ }
1070
+ // ── SMS y WhatsApp ────────────────────────────────────────────────────────────────────────────────────────────
1071
+ toMessage(b) {
1072
+ const cost = money(b.price, b.price_unit);
1073
+ const whatsapp = String(_nullishCoalesce(b.from, () => ( ""))).startsWith("whatsapp:") || String(_nullishCoalesce(b.to, () => ( ""))).startsWith("whatsapp:");
1074
+ return {
1075
+ id: b.sid,
1076
+ provider: "twilio",
1077
+ channel: whatsapp ? "whatsapp" : "sms",
1078
+ direction: String(_nullishCoalesce(b.direction, () => ( ""))).startsWith("inbound") ? "inbound" : "outbound",
1079
+ from: stripChannelPrefix(String(_nullishCoalesce(b.from, () => ( "")))),
1080
+ to: stripChannelPrefix(String(_nullishCoalesce(b.to, () => ( "")))),
1081
+ status: _nullishCoalesce(MESSAGE_STATUS[b.status], () => ( "queued")),
1082
+ ...typeof b.body === "string" ? { body: b.body } : {},
1083
+ ...b.num_segments !== void 0 ? { segments: Number(b.num_segments) } : {},
1084
+ ...cost ? { cost } : {},
1085
+ ...b.error_code ? { errorReason: `provider_${b.error_code}` } : {},
1086
+ ...asDate(b.date_created) ? { createdAt: asDate(b.date_created) } : {}
1087
+ };
1088
+ }
1089
+ sendMessage(form, idempotencyKey) {
1090
+ return this.ok(this.post(this.acct("/Messages.json"), form, idempotencyKey)).then((b) => this.toMessage(b));
1091
+ }
1092
+ buildSms() {
1093
+ const self = this;
1094
+ return {
1095
+ send: async (i) => {
1096
+ if (!isE164(i.from) || !isE164(i.to)) throw new TelephonyProviderException("twilio", "invalid_number");
1097
+ return self.sendMessage({ From: i.from, To: i.to, Body: i.body, StatusCallback: i.statusCallbackUrl, ..._nullishCoalesce(i.extra, () => ( {})) }, i.idempotencyKey);
1098
+ },
1099
+ async get(id) {
1100
+ return self.toMessage(await self.ok(self.get(self.acct(`/Messages/${encodeURIComponent(id)}.json`))));
1101
+ }
1102
+ };
1103
+ }
1104
+ buildWhatsApp() {
1105
+ const self = this;
1106
+ const fromOf = (from) => {
1107
+ const line = _nullishCoalesce(from, () => ( self.o.whatsappFrom));
1108
+ if (!line) throw new Error("TwilioTelephony: falta `from` o la opci\xF3n `whatsappFrom` para WhatsApp.");
1109
+ return `whatsapp:${stripChannelPrefix(line)}`;
1110
+ };
1111
+ return {
1112
+ sendText: async (i) => {
1113
+ if (!isE164(i.to)) throw new TelephonyProviderException("twilio", "invalid_number");
1114
+ return self.sendMessage(
1115
+ { From: fromOf(i.from), To: `whatsapp:${i.to}`, Body: i.body, StatusCallback: i.statusCallbackUrl },
1116
+ i.idempotencyKey
1117
+ );
1118
+ },
1119
+ sendTemplate: async (i) => {
1120
+ if (!isE164(i.to)) throw new TelephonyProviderException("twilio", "invalid_number");
1121
+ return self.sendMessage(
1122
+ {
1123
+ From: fromOf(i.from),
1124
+ To: `whatsapp:${i.to}`,
1125
+ ContentSid: i.template,
1126
+ ContentVariables: JSON.stringify(Object.fromEntries((_nullishCoalesce(i.variables, () => ( []))).map((v, n) => [String(n + 1), v]))),
1127
+ StatusCallback: i.statusCallbackUrl
1128
+ },
1129
+ i.idempotencyKey
1130
+ );
1131
+ },
1132
+ async get(id) {
1133
+ return self.toMessage(await self.ok(self.get(self.acct(`/Messages/${encodeURIComponent(id)}.json`))));
1134
+ }
1135
+ };
1136
+ }
1137
+ // ── Uso ───────────────────────────────────────────────────────────────────────────────────────────────────────
1138
+ buildUsage() {
1139
+ const self = this;
1140
+ const CATEGORY = { voice: "calls", sms: "sms", whatsapp: "whatsapp", numbers: "phonenumbers" };
1141
+ const UNIT = { voice: "minutes", sms: "messages", whatsapp: "messages", numbers: "numbers" };
1142
+ async function perNumber(q) {
1143
+ if (q.category === "numbers") throw new UnsupportedCapabilityException("twilio", "uso de la renta por n\xFAmero");
1144
+ const calls = q.category === "voice";
1145
+ const resource = calls ? "Calls" : "Messages";
1146
+ const dateKey = calls ? "StartTime" : "DateSent";
1147
+ const maxPages = _nullishCoalesce(self.o.maxUsagePages, () => ( 20));
1148
+ const days = /* @__PURE__ */ new Map();
1149
+ const bucket = (day) => {
1150
+ const key = q.granularity === "day" ? day : "total";
1151
+ let r = days.get(key);
1152
+ if (!r) {
1153
+ r = {
1154
+ category: q.category,
1155
+ periodStart: q.granularity === "day" ? day : q.from,
1156
+ periodEnd: q.granularity === "day" ? day : q.to,
1157
+ count: 0,
1158
+ units: 0,
1159
+ unit: UNIT[q.category]
1160
+ };
1161
+ days.set(key, r);
1162
+ }
1163
+ return r;
1164
+ };
1165
+ for (const side of [calls ? "To" : "To", "From"]) {
1166
+ let url = self.acct(
1167
+ `/${resource}.json?${side}=${encodeURIComponent(q.category === "whatsapp" ? `whatsapp:${q.number}` : q.number)}&${dateKey}>=${q.from}&${dateKey}<=${q.to}&PageSize=1000`
1168
+ );
1169
+ for (let page = 0; url && page < maxPages; page++) {
1170
+ const body = await self.ok(self.get(url));
1171
+ for (const row of _nullishCoalesce(body[calls ? "calls" : "messages"], () => ( []))) {
1172
+ const whatsapp = String(_nullishCoalesce(row.from, () => ( ""))).startsWith("whatsapp:") || String(_nullishCoalesce(row.to, () => ( ""))).startsWith("whatsapp:");
1173
+ if (!calls && q.category === "whatsapp" !== whatsapp) continue;
1174
+ const day = (_nullishCoalesce(asDate(_nullishCoalesce(_nullishCoalesce(row.start_time, () => ( row.date_sent)), () => ( row.date_created))), () => ( q.from))).slice(0, 10);
1175
+ const r = bucket(day);
1176
+ r.count += 1;
1177
+ r.units += calls ? billableMinutes(Number(_nullishCoalesce(row.duration, () => ( 0)))) : Number(_nullishCoalesce(row.num_segments, () => ( 1)));
1178
+ const cost = money(row.price, row.price_unit);
1179
+ if (cost) {
1180
+ const sum = Number(_nullishCoalesce(_optionalChain([r, 'access', _23 => _23.providerCost, 'optionalAccess', _24 => _24.amount]), () => ( 0))) + Number(cost.amount);
1181
+ r.providerCost = { amount: String(Math.round(sum * 1e6) / 1e6), currency: cost.currency };
1182
+ }
1183
+ }
1184
+ url = body.next_page_uri ? self.decodeCursor(self.encodeCursor(body.next_page_uri)) : void 0;
1185
+ }
1186
+ }
1187
+ return [...days.values()];
1188
+ }
1189
+ return {
1190
+ async query(q) {
1191
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(q.from) || !/^\d{4}-\d{2}-\d{2}$/.test(q.to)) {
1192
+ throw new TelephonyProviderException("twilio", "rejected");
1193
+ }
1194
+ const key = JSON.stringify(q);
1195
+ return await self.cache.remember(key, async () => {
1196
+ if (q.number) return perNumber(q);
1197
+ const kind = q.granularity === "day" ? "Daily" : "AllTime";
1198
+ const body = await self.ok(
1199
+ self.get(self.acct(`/Usage/Records/${kind}.json?Category=${CATEGORY[q.category]}&StartDate=${q.from}&EndDate=${q.to}&PageSize=1000`))
1200
+ );
1201
+ return (_nullishCoalesce(body.usage_records, () => ( []))).map(
1202
+ (r) => ({
1203
+ category: q.category,
1204
+ periodStart: _nullishCoalesce(r.start_date, () => ( q.from)),
1205
+ periodEnd: _nullishCoalesce(r.end_date, () => ( q.to)),
1206
+ count: Number(_nullishCoalesce(r.count, () => ( 0))),
1207
+ units: Number(_nullishCoalesce(r.usage, () => ( 0))),
1208
+ unit: UNIT[q.category],
1209
+ ...money(r.price, r.price_unit) ? { providerCost: money(r.price, r.price_unit) } : {}
1210
+ })
1211
+ );
1212
+ });
1213
+ }
1214
+ };
1215
+ }
1216
+ // ── Webhooks ──────────────────────────────────────────────────────────────────────────────────────────────────
1217
+ paramsOf(request) {
1218
+ if (request.params) return request.params;
1219
+ if (request.rawBody === void 0) return null;
1220
+ return Object.fromEntries(new URLSearchParams(request.rawBody));
1221
+ }
1222
+ header(request, name) {
1223
+ for (const [k, v] of Object.entries(request.headers)) {
1224
+ if (k.toLowerCase() === name) return Array.isArray(v) ? v[0] : v;
1225
+ }
1226
+ return void 0;
1227
+ }
1228
+ buildWebhooks() {
1229
+ const self = this;
1230
+ return {
1231
+ verify(request) {
1232
+ const signature = self.header(request, "x-twilio-signature");
1233
+ const params = self.paramsOf(request);
1234
+ if (!signature || !params || !self.o.authToken) return false;
1235
+ return _chunk2RQINZCRcjs.constantTimeEqual.call(void 0, twilioSignature(request.url, params, self.o.authToken), signature);
1236
+ },
1237
+ parse(request) {
1238
+ const p = _nullishCoalesce(self.paramsOf(request), () => ( {}));
1239
+ const now = Date.now();
1240
+ const token = self.header(request, "i-twilio-idempotency-token");
1241
+ const occurredAt = p.Timestamp && !Number.isNaN(Date.parse(p.Timestamp)) ? Date.parse(p.Timestamp) : void 0;
1242
+ const base = { provider: "twilio", receivedAt: now, ...occurredAt ? { occurredAt } : {} };
1243
+ const id = (kind, sid, status = "") => _nullishCoalesce(token, () => ( `twilio:${kind}:${sid}:${status}`));
1244
+ const messageSid = _nullishCoalesce(p.MessageSid, () => ( p.SmsSid));
1245
+ if (messageSid) {
1246
+ const whatsapp = (_nullishCoalesce(p.From, () => ( ""))).startsWith("whatsapp:") || (_nullishCoalesce(p.To, () => ( ""))).startsWith("whatsapp:");
1247
+ const raw = (_nullishCoalesce(_nullishCoalesce(p.MessageStatus, () => ( p.SmsStatus)), () => ( ""))).toLowerCase();
1248
+ const status = _nullishCoalesce(MESSAGE_STATUS[raw], () => ( "queued"));
1249
+ if (raw === "received" || raw === "" && p.Body !== void 0) {
1250
+ const body = _nullishCoalesce(p.Body, () => ( ""));
1251
+ const keyword = _nullishCoalesce(classifyKeyword(body), () => ( void 0));
1252
+ return [
1253
+ {
1254
+ ...base,
1255
+ id: id("msg-in", messageSid),
1256
+ type: whatsapp ? TELEPHONY_EVENTS.WHATSAPP_RECEIVED : TELEPHONY_EVENTS.SMS_RECEIVED,
1257
+ messageId: messageSid,
1258
+ from: stripChannelPrefix(_nullishCoalesce(p.From, () => ( ""))),
1259
+ to: stripChannelPrefix(_nullishCoalesce(p.To, () => ( ""))),
1260
+ body,
1261
+ ...keyword ? { keyword } : {}
1262
+ }
1263
+ ];
1264
+ }
1265
+ return [
1266
+ {
1267
+ ...base,
1268
+ id: id("msg-status", messageSid, raw),
1269
+ type: whatsapp ? TELEPHONY_EVENTS.WHATSAPP_STATUS : TELEPHONY_EVENTS.SMS_STATUS,
1270
+ messageId: messageSid,
1271
+ status,
1272
+ ...p.ErrorCode ? { errorReason: `provider_${p.ErrorCode}` } : {}
1273
+ }
1274
+ ];
1275
+ }
1276
+ const callSid = p.CallSid;
1277
+ if (callSid) {
1278
+ if (p.HandoffData !== void 0 || p.SessionStatus !== void 0) {
1279
+ return [
1280
+ {
1281
+ ...base,
1282
+ id: id("call-action", callSid),
1283
+ type: TELEPHONY_EVENTS.CALL_ACTION,
1284
+ callId: callSid,
1285
+ handoff: (_nullishCoalesce(p.HandoffData, () => ( ""))).length > 0,
1286
+ sessionFailed: p.SessionStatus === "failed"
1287
+ }
1288
+ ];
1289
+ }
1290
+ const raw = (_nullishCoalesce(p.CallStatus, () => ( ""))).toLowerCase();
1291
+ const status = _nullishCoalesce(CALL_STATUS[raw], () => ( "queued"));
1292
+ const from = stripChannelPrefix(_nullishCoalesce(p.From, () => ( "")));
1293
+ const to = stripChannelPrefix(_nullishCoalesce(p.To, () => ( "")));
1294
+ if (ENDED.has(raw)) {
1295
+ const duration = Math.max(0, Number(_nullishCoalesce(_nullishCoalesce(p.CallDuration, () => ( p.Duration)), () => ( 0))) || 0);
1296
+ return [
1297
+ {
1298
+ ...base,
1299
+ id: id("call-ended", callSid),
1300
+ type: TELEPHONY_EVENTS.CALL_ENDED,
1301
+ callId: callSid,
1302
+ status,
1303
+ from,
1304
+ to,
1305
+ durationSeconds: duration,
1306
+ billableMinutes: billableMinutes(duration)
1307
+ }
1308
+ ];
1309
+ }
1310
+ if (raw === "ringing" && (_nullishCoalesce(p.Direction, () => ( ""))).startsWith("inbound")) {
1311
+ return [{ ...base, id: id("call-in", callSid), type: TELEPHONY_EVENTS.CALL_INCOMING, callId: callSid, from, to }];
1312
+ }
1313
+ return [{ ...base, id: id("call-status", callSid, raw), type: TELEPHONY_EVENTS.CALL_STATUS, callId: callSid, status, from, to }];
1314
+ }
1315
+ return [];
1316
+ },
1317
+ acknowledge: () => wrap("")
1318
+ };
1319
+ }
1320
+ };
1321
+
1322
+ // src/telephony/adapters/meta-whatsapp.telephony.ts
1323
+
1324
+ var objects = (v) => Array.isArray(v) ? v.filter((x) => !!x && typeof x === "object") : [];
1325
+ var STATUS = {
1326
+ sent: "sent",
1327
+ delivered: "delivered",
1328
+ read: "read",
1329
+ failed: "failed"
1330
+ };
1331
+ function toProviderError(e) {
1332
+ if (e instanceof TelephonyProviderException) return e;
1333
+ const text = e instanceof Error ? e.message : "";
1334
+ const status = Number(_optionalChain([/\((\d{3})\)/, 'access', _25 => _25.exec, 'call', _26 => _26(text), 'optionalAccess', _27 => _27[1]]));
1335
+ let reason = "unreachable";
1336
+ if (status === 401 || status === 403) reason = "auth";
1337
+ else if (status === 429) reason = "rate_limited";
1338
+ else if (status >= 400 && status < 500) reason = "rejected";
1339
+ else if (status >= 500) reason = "unreachable";
1340
+ return new TelephonyProviderException("meta-whatsapp", reason, { status: status || void 0, raw: text });
1341
+ }
1342
+ var MetaWhatsAppTelephony = class {
1343
+ constructor(o) {
1344
+ this.o = o;
1345
+ this.provider = "meta-whatsapp";
1346
+ this.portVersion = TELEPHONY_PORT_VERSION;
1347
+ if (!_optionalChain([o, 'optionalAccess', _28 => _28.client])) throw new Error("MetaWhatsAppTelephony: falta `client` (WhatsAppClient).");
1348
+ this.whatsapp = this.buildWhatsApp();
1349
+ this.webhooks = this.buildWebhooks();
1350
+ }
1351
+ info(id, to, body, from) {
1352
+ return {
1353
+ id: _nullishCoalesce(id, () => ( "")),
1354
+ provider: this.provider,
1355
+ channel: "whatsapp",
1356
+ direction: "outbound",
1357
+ from: _nullishCoalesce(_nullishCoalesce(from, () => ( this.o.displayNumber)), () => ( "")),
1358
+ to,
1359
+ status: "queued",
1360
+ body,
1361
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1362
+ };
1363
+ }
1364
+ buildWhatsApp() {
1365
+ const t = this;
1366
+ const digits = (n) => n.replace(/^\+/, "");
1367
+ return {
1368
+ async sendText(input) {
1369
+ try {
1370
+ const r = await t.o.client.sendTextMessage(digits(input.to), input.body);
1371
+ return t.info(_optionalChain([r, 'access', _29 => _29.messages, 'optionalAccess', _30 => _30[0], 'optionalAccess', _31 => _31.id]), input.to, input.body, input.from);
1372
+ } catch (e) {
1373
+ throw toProviderError(e);
1374
+ }
1375
+ },
1376
+ async sendTemplate(input) {
1377
+ const send = t.o.client.sendTemplateMessage;
1378
+ if (!send) throw new TelephonyProviderException(t.provider, "rejected");
1379
+ try {
1380
+ const r = await send.call(t.o.client, digits(input.to), input.template, _nullishCoalesce(input.language, () => ( "es_MX")), _nullishCoalesce(input.variables, () => ( [])));
1381
+ return t.info(_optionalChain([r, 'access', _32 => _32.messages, 'optionalAccess', _33 => _33[0], 'optionalAccess', _34 => _34.id]), input.to, `[plantilla ${input.template}]`, input.from);
1382
+ } catch (e) {
1383
+ throw toProviderError(e);
1384
+ }
1385
+ }
1386
+ };
1387
+ }
1388
+ header(request, name) {
1389
+ for (const [k, v] of Object.entries(request.headers)) {
1390
+ if (k.toLowerCase() === name) return Array.isArray(v) ? v[0] : v;
1391
+ }
1392
+ return void 0;
1393
+ }
1394
+ buildWebhooks() {
1395
+ const t = this;
1396
+ const plus = (n) => n ? n.startsWith("+") ? n : `+${n}` : "";
1397
+ return {
1398
+ verify(request) {
1399
+ const secret = t.o.appSecret;
1400
+ const header = t.header(request, "x-hub-signature-256");
1401
+ if (!secret || !header || request.rawBody === void 0) return false;
1402
+ const expected = `sha256=${_crypto.createHmac.call(void 0, "sha256", secret).update(request.rawBody, "utf8").digest("hex")}`;
1403
+ return _chunk2RQINZCRcjs.constantTimeEqual.call(void 0, expected, header);
1404
+ },
1405
+ challenge(query) {
1406
+ const token = t.o.verifyToken;
1407
+ if (!token || query["hub.mode"] !== "subscribe") return null;
1408
+ const sent = _nullishCoalesce(query["hub.verify_token"], () => ( ""));
1409
+ const challenge = query["hub.challenge"];
1410
+ return _chunk2RQINZCRcjs.constantTimeEqual.call(void 0, sent, token) && challenge && /^\d{1,32}$/.test(challenge) ? challenge : null;
1411
+ },
1412
+ parse(request) {
1413
+ let payload;
1414
+ try {
1415
+ payload = JSON.parse(_nullishCoalesce(request.rawBody, () => ( "")));
1416
+ } catch (e5) {
1417
+ return [];
1418
+ }
1419
+ const events = [];
1420
+ const now = Date.now();
1421
+ for (const entry of objects(_optionalChain([payload, 'optionalAccess', _35 => _35.entry]))) {
1422
+ for (const change of objects(entry.changes)) {
1423
+ const value = change.value && typeof change.value === "object" ? change.value : {};
1424
+ const line = plus(_optionalChain([value, 'access', _36 => _36.metadata, 'optionalAccess', _37 => _37.display_phone_number]));
1425
+ for (const m of objects(value.messages)) {
1426
+ if (typeof m.id !== "string") continue;
1427
+ const body = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([m, 'access', _38 => _38.text, 'optionalAccess', _39 => _39.body]), () => ( _optionalChain([m, 'access', _40 => _40.button, 'optionalAccess', _41 => _41.text]))), () => ( _optionalChain([m, 'access', _42 => _42.interactive, 'optionalAccess', _43 => _43.button_reply, 'optionalAccess', _44 => _44.title]))), () => ( _optionalChain([m, 'access', _45 => _45.interactive, 'optionalAccess', _46 => _46.list_reply, 'optionalAccess', _47 => _47.title]))), () => ( ""));
1428
+ const keyword = _nullishCoalesce(classifyKeyword(body), () => ( void 0));
1429
+ const ts = Number(m.timestamp) * 1e3;
1430
+ events.push({
1431
+ id: `meta:msg:${m.id}`,
1432
+ provider: t.provider,
1433
+ receivedAt: now,
1434
+ ...Number.isFinite(ts) && ts > 0 ? { occurredAt: ts } : {},
1435
+ type: TELEPHONY_EVENTS.WHATSAPP_RECEIVED,
1436
+ messageId: m.id,
1437
+ from: plus(m.from),
1438
+ to: line || t.o.displayNumber || "",
1439
+ body: String(body).slice(0, 4096),
1440
+ ...keyword ? { keyword } : {}
1441
+ });
1442
+ }
1443
+ for (const s of objects(value.statuses)) {
1444
+ if (typeof s.id !== "string") continue;
1445
+ const ts = Number(s.timestamp) * 1e3;
1446
+ events.push({
1447
+ id: `meta:status:${s.id}:${s.status}`,
1448
+ provider: t.provider,
1449
+ receivedAt: now,
1450
+ ...Number.isFinite(ts) && ts > 0 ? { occurredAt: ts } : {},
1451
+ type: TELEPHONY_EVENTS.WHATSAPP_STATUS,
1452
+ messageId: s.id,
1453
+ status: _nullishCoalesce(STATUS[String(s.status)], () => ( "queued")),
1454
+ ..._optionalChain([s, 'access', _48 => _48.errors, 'optionalAccess', _49 => _49[0], 'optionalAccess', _50 => _50.code]) ? { errorReason: `provider_${s.errors[0].code}` } : {}
1455
+ });
1456
+ }
1457
+ }
1458
+ }
1459
+ return events;
1460
+ },
1461
+ // Meta solo necesita un 200; el cuerpo no importa.
1462
+ acknowledge: () => ({ body: "", contentType: "text/plain; charset=utf-8" })
1463
+ };
1464
+ }
1465
+ };
1466
+
1467
+ // src/telephony/telephony.registry.ts
1468
+ var BUILT_IN_PROVIDERS = {
1469
+ twilio: (config) => new TwilioTelephony(config),
1470
+ simulated: (config) => new SimulatedTelephony(config),
1471
+ "meta-whatsapp": (config) => new MetaWhatsAppTelephony(config)
1472
+ };
1473
+ var TelephonyRegistry = class {
1474
+ constructor(options = {}) {
1475
+ this.options = options;
1476
+ this.factories = new Map(Object.entries(BUILT_IN_PROVIDERS));
1477
+ this.shared = /* @__PURE__ */ new Map();
1478
+ for (const [name, factory] of Object.entries(_nullishCoalesce(options.factories, () => ( {})))) this.factories.set(name, factory);
1479
+ }
1480
+ registerProvider(name, factory) {
1481
+ this.factories.set(name, factory);
1482
+ this.shared.delete(name);
1483
+ }
1484
+ has(name) {
1485
+ return this.factories.has(name);
1486
+ }
1487
+ /** La configuración de un proveedor del proceso: la propia de las opciones, o `providers[nombre]`. */
1488
+ configOf(name) {
1489
+ switch (name) {
1490
+ case "twilio":
1491
+ return this.options.twilio;
1492
+ case "simulated":
1493
+ return _nullishCoalesce(this.options.simulated, () => ( {}));
1494
+ case "meta-whatsapp":
1495
+ return this.options.metaWhatsApp;
1496
+ default:
1497
+ return _optionalChain([this, 'access', _51 => _51.options, 'access', _52 => _52.providers, 'optionalAccess', _53 => _53[name]]);
1498
+ }
1499
+ }
1500
+ /** Adaptador compartido del proceso. Falla en voz alta (al arrancar) si falta su configuración. */
1501
+ get(name) {
1502
+ const cached = this.shared.get(name);
1503
+ if (cached) return cached;
1504
+ const adapter = this.build(name, this.configOf(name));
1505
+ this.shared.set(name, adapter);
1506
+ return adapter;
1507
+ }
1508
+ /** Adaptador con configuración propia (un tenant): no se comparte ni se guarda aquí. */
1509
+ build(name, config, context = {}) {
1510
+ const factory = this.factories.get(name);
1511
+ if (!factory) throw new Error(`Telefon\xEDa: proveedor desconocido "${name}". Reg\xEDstralo con registerProvider().`);
1512
+ if (config === void 0 || config === null) {
1513
+ throw new Error(`Telefon\xEDa: faltan las opciones del proveedor "${name}".`);
1514
+ }
1515
+ return factory(config, context);
1516
+ }
1517
+ };
1518
+
1519
+ // src/telephony/telephony.facade.ts
1520
+ var TRANSIENT = /* @__PURE__ */ new Set(["unreachable", "timeout", "circuit_open", "overloaded", "rate_limited"]);
1521
+ var Telephony = class _Telephony {
1522
+ constructor(options = {}, hooks = {}, internal = {}) {
1523
+ this.options = options;
1524
+ this.hooks = hooks;
1525
+ this.registry = _nullishCoalesce(internal.registry, () => ( new TelephonyRegistry(options)));
1526
+ this.tenantId = internal.tenantId;
1527
+ this.optOutStore = _nullishCoalesce(_nullishCoalesce(internal.optOut, () => ( _optionalChain([options, 'access', _54 => _54.policy, 'optionalAccess', _55 => _55.optOutStore]))), () => ( new MemoryOptOutStore()));
1528
+ this.cache = new TtlCache(_nullishCoalesce(_optionalChain([options, 'access', _56 => _56.policy, 'optionalAccess', _57 => _57.readCacheTtlMs]), () => ( 3e4)), 500);
1529
+ this.tenants = new TtlCache(_nullishCoalesce(_optionalChain([options, 'access', _58 => _58.tenantCache, 'optionalAccess', _59 => _59.ttlMs]), () => ( 10 * 6e4)), _nullishCoalesce(_optionalChain([options, 'access', _60 => _60.tenantCache, 'optionalAccess', _61 => _61.max]), () => ( 500)));
1530
+ if (internal.adapters) {
1531
+ this.adapters = internal.adapters;
1532
+ } else {
1533
+ const names = [options.provider, ..._nullishCoalesce(options.fallbacks, () => ( []))].filter((n) => !!n);
1534
+ const channelOnly = Object.values(_nullishCoalesce(options.channels, () => ( {}))).filter((n) => !!n);
1535
+ if (!names.length && !channelOnly.length) {
1536
+ throw new Error("Telefon\xEDa: no hay proveedor \u2014 pasa `provider` o define TELEPHONY_PROVIDER.");
1537
+ }
1538
+ this.adapters = [...new Set(names)].map((n) => this.registry.get(n));
1539
+ for (const n of channelOnly) this.registry.get(n);
1540
+ }
1541
+ this.numbers = this.buildNumbers();
1542
+ this.voice = this.buildVoice();
1543
+ this.sms = this.buildSms();
1544
+ this.whatsapp = this.buildWhatsApp();
1545
+ this.usage = this.buildUsage();
1546
+ }
1547
+ // ── Selección de proveedor ─────────────────────────────────────────────────────────────────────────────────────
1548
+ /** Proveedor principal. */
1549
+ get provider() {
1550
+ return _nullishCoalesce(_nullishCoalesce(_optionalChain([this, 'access', _62 => _62.adapters, 'access', _63 => _63[0], 'optionalAccess', _64 => _64.provider]), () => ( this.options.provider)), () => ( "none"));
1551
+ }
1552
+ /** ¿Algún proveedor configurado soporta esta capacidad? */
1553
+ supports(capability) {
1554
+ return this.candidates(capability).length > 0;
1555
+ }
1556
+ /** Las capacidades disponibles, para pantallas de configuración. */
1557
+ capabilities() {
1558
+ return ["numbers", "voice", "sms", "whatsapp", "usage"].filter((c) => this.supports(c));
1559
+ }
1560
+ /** El adaptador de un proveedor por nombre (para los webhooks). */
1561
+ adapterNamed(name) {
1562
+ const found = this.adapters.find((a) => a.provider === name);
1563
+ if (found) return found;
1564
+ if (!this.tenantId && (this.options.channels && Object.values(this.options.channels).includes(name))) {
1565
+ return this.registry.get(name);
1566
+ }
1567
+ throw new UnsupportedCapabilityException(name, "este proveedor");
1568
+ }
1569
+ candidates(capability) {
1570
+ const forced = _optionalChain([this, 'access', _65 => _65.options, 'access', _66 => _66.channels, 'optionalAccess', _67 => _67[capability]]);
1571
+ if (forced && !this.tenantId) {
1572
+ const adapter = this.registry.get(forced);
1573
+ return adapter[capability] ? [adapter] : [];
1574
+ }
1575
+ return this.adapters.filter((a) => a[capability]);
1576
+ }
1577
+ unsupported(capability) {
1578
+ return new UnsupportedCapabilityException(this.provider, capability);
1579
+ }
1580
+ pick(capability) {
1581
+ const adapter = this.candidates(capability)[0];
1582
+ if (!adapter) throw this.unsupported(capability);
1583
+ return adapter[capability];
1584
+ }
1585
+ /** Lectura: cacheada, comparte la consulta en vuelo y prueba el respaldo ante una caída transitoria. */
1586
+ async read(capability, key, fn) {
1587
+ const run = async () => {
1588
+ const list = this.candidates(capability);
1589
+ if (!list.length) throw this.unsupported(capability);
1590
+ let last;
1591
+ for (const adapter of list) {
1592
+ try {
1593
+ return await fn(adapter[capability]);
1594
+ } catch (e) {
1595
+ last = e;
1596
+ if (!(e instanceof TelephonyProviderException && TRANSIENT.has(e.reason))) throw e;
1597
+ this.log(`${adapter.provider} no respondi\xF3 (${e.reason}); se prueba el respaldo`);
1598
+ }
1599
+ }
1600
+ throw last;
1601
+ };
1602
+ return key ? this.cache.remember(`${capability}|${key}`, run) : run();
1603
+ }
1604
+ // ── Tenants ────────────────────────────────────────────────────────────────────────────────────────────────────
1605
+ /**
1606
+ * La telefonía con las credenciales de UN tenant (`options.tenantProvider`). Cada tenant tiene su adaptador, su
1607
+ * caché y su cortacircuito: lo que le pase a uno no toca a los demás. Se conserva en memoria acotada.
1608
+ */
1609
+ async forTenant(tenantId) {
1610
+ if (!this.options.tenantProvider) throw new TenantNotConfiguredException();
1611
+ return this.tenants.remember(tenantId, async () => {
1612
+ const config = await this.options.tenantProvider(tenantId);
1613
+ if (!config) throw new TenantNotConfiguredException();
1614
+ const adapters = [
1615
+ this.registry.build(config.provider, config.config, { tenantId }),
1616
+ ...(_nullishCoalesce(config.fallbacks, () => ( []))).map((f) => this.registry.build(f.provider, f.config, { tenantId }))
1617
+ ];
1618
+ return new _Telephony(this.options, this.hooks, {
1619
+ tenantId,
1620
+ registry: this.registry,
1621
+ optOut: this.optOutStore,
1622
+ adapters
1623
+ });
1624
+ });
1625
+ }
1626
+ /** Olvida el adaptador de un tenant (cambió sus credenciales). */
1627
+ forgetTenant(tenantId) {
1628
+ this.tenants.delete(tenantId);
1629
+ }
1630
+ // ── Política de salida ─────────────────────────────────────────────────────────────────────────────────────────
1631
+ /** Destino listo para marcar o escribir; lanza si el formato o la política no lo permiten. */
1632
+ destination(raw) {
1633
+ const to = normalizeE164(raw);
1634
+ const verdict = checkDestination(to, _optionalChain([this, 'access', _68 => _68.options, 'access', _69 => _69.policy, 'optionalAccess', _70 => _70.destinations]));
1635
+ if (!to || !verdict.ok) throw new DestinationNotAllowedException(verdict.ok ? "invalid" : verdict.reason);
1636
+ return to;
1637
+ }
1638
+ line(raw) {
1639
+ if (raw === void 0) return void 0;
1640
+ const from = normalizeE164(raw);
1641
+ if (!from || !isE164(from)) throw new InvalidMessageException("El n\xFAmero de origen no es v\xE1lido.");
1642
+ return from;
1643
+ }
1644
+ async assertNotOptedOut(from, to, tenantId) {
1645
+ if (await this.optOutStore.isOptedOut({ tenantId, line: _nullishCoalesce(from, () => ( "*")), recipient: to })) {
1646
+ throw new RecipientOptedOutException();
1647
+ }
1648
+ }
1649
+ body(text) {
1650
+ const clean = sanitizeMessageBody(text, _nullishCoalesce(_optionalChain([this, 'access', _71 => _71.options, 'access', _72 => _72.policy, 'optionalAccess', _73 => _73.maxMessageLength]), () => ( MAX_SMS_BODY)));
1651
+ if (!clean) throw new InvalidMessageException();
1652
+ return clean;
1653
+ }
1654
+ async outbound(op, send) {
1655
+ await _optionalChain([this, 'access', _74 => _74.options, 'access', _75 => _75.policy, 'optionalAccess', _76 => _76.beforeOutbound, 'optionalCall', _77 => _77(op)]);
1656
+ const result = await send();
1657
+ try {
1658
+ await _optionalChain([this, 'access', _78 => _78.options, 'access', _79 => _79.policy, 'optionalAccess', _80 => _80.afterOutbound, 'optionalCall', _81 => _81(op, { id: result.id })]);
1659
+ } catch (e) {
1660
+ this.log(`afterOutbound fall\xF3: ${e instanceof Error ? e.message : "error"}`);
1661
+ }
1662
+ return result;
1663
+ }
1664
+ // ── Capacidades ────────────────────────────────────────────────────────────────────────────────────────────────
1665
+ buildNumbers() {
1666
+ const t = this;
1667
+ const invalidate = (p) => p.finally(() => t.cache.clear());
1668
+ const key = (...parts) => JSON.stringify(parts);
1669
+ return {
1670
+ search: (query) => t.read("numbers", key("search", query), (p) => p.search(query)),
1671
+ requirements: (country, type) => t.read("numbers", key("req", country, type), (p) => p.requirements(country, type)),
1672
+ monthlyCost: (country, type) => t.read("numbers", key("cost", country, type), (p) => p.monthlyCost(country, type)),
1673
+ provision: (input) => invalidate(t.pick("numbers").provision(input)),
1674
+ configure: (id, input) => invalidate(t.pick("numbers").configure(id, input)),
1675
+ get: (id) => t.read("numbers", key("get", id), (p) => p.get(id)),
1676
+ list: (options) => t.read("numbers", key("list", options), (p) => p.list(options)),
1677
+ release: (id) => invalidate(t.pick("numbers").release(id)),
1678
+ transfer: (id, toAccountId) => {
1679
+ const port = t.pick("numbers");
1680
+ if (!port.transfer) throw t.unsupported("transferir n\xFAmeros");
1681
+ return invalidate(port.transfer(id, toAccountId));
1682
+ }
1683
+ };
1684
+ }
1685
+ buildVoice() {
1686
+ const t = this;
1687
+ const texts = { ...DEFAULT_TEXTS, ..._nullishCoalesce(_optionalChain([this, 'access', _82 => _82.options, 'access', _83 => _83.webhook, 'optionalAccess', _84 => _84.texts]), () => ( {})) };
1688
+ const safe = (instruction) => {
1689
+ if (instruction.kind !== "dial") return instruction;
1690
+ try {
1691
+ return { ...instruction, to: t.destination(instruction.to) };
1692
+ } catch (e6) {
1693
+ return {
1694
+ kind: "hangup",
1695
+ message: _nullishCoalesce(instruction.fallbackMessage, () => ( texts.unavailable)),
1696
+ ...instruction.language ? { language: instruction.language } : {}
1697
+ };
1698
+ }
1699
+ };
1700
+ return {
1701
+ buildAnswer: (instruction) => t.pick("voice").buildAnswer(safe(instruction)),
1702
+ placeCall: async (input) => {
1703
+ const to = t.destination(input.to);
1704
+ const from = t.line(input.from);
1705
+ const op = { kind: "call", tenantId: t.tenantId, from, to };
1706
+ return t.outbound(
1707
+ op,
1708
+ () => t.pick("voice").placeCall({ ...input, from, to, ...input.answer ? { answer: safe(input.answer) } : {} })
1709
+ );
1710
+ },
1711
+ placeTestCall: async (from, to) => {
1712
+ const dest = t.destination(to);
1713
+ const line = t.line(from);
1714
+ const op = { kind: "call", tenantId: t.tenantId, from: line, to: dest };
1715
+ await _optionalChain([t, 'access', _85 => _85.options, 'access', _86 => _86.policy, 'optionalAccess', _87 => _87.beforeOutbound, 'optionalCall', _88 => _88(op)]);
1716
+ return t.pick("voice").placeTestCall(line, dest);
1717
+ },
1718
+ getCall: (id) => t.read("voice", null, (p) => p.getCall(id))
1719
+ };
1720
+ }
1721
+ buildSms() {
1722
+ const t = this;
1723
+ return {
1724
+ send: async (input) => {
1725
+ const to = t.destination(input.to);
1726
+ const from = t.line(input.from);
1727
+ const body = t.body(input.body);
1728
+ await t.assertNotOptedOut(from, to, _nullishCoalesce(input.tenantId, () => ( t.tenantId)));
1729
+ const op = { kind: "sms", tenantId: _nullishCoalesce(input.tenantId, () => ( t.tenantId)), from, to };
1730
+ return t.outbound(op, () => t.pick("sms").send({ ...input, from, to, body }));
1731
+ },
1732
+ get: (id) => t.read("sms", null, (p) => p.get(id))
1733
+ };
1734
+ }
1735
+ buildWhatsApp() {
1736
+ const t = this;
1737
+ return {
1738
+ sendText: async (input) => {
1739
+ const to = t.destination(input.to);
1740
+ const from = t.line(input.from);
1741
+ const body = t.body(input.body);
1742
+ await t.assertNotOptedOut(from, to, _nullishCoalesce(input.tenantId, () => ( t.tenantId)));
1743
+ const op = { kind: "whatsapp", tenantId: _nullishCoalesce(input.tenantId, () => ( t.tenantId)), from, to };
1744
+ return t.outbound(op, () => t.pick("whatsapp").sendText({ ...input, ...from ? { from } : {}, to, body }));
1745
+ },
1746
+ sendTemplate: async (input) => {
1747
+ const to = t.destination(input.to);
1748
+ const from = t.line(input.from);
1749
+ if (!input.template || input.template.length > 128) throw new InvalidMessageException("La plantilla no es v\xE1lida.");
1750
+ await t.assertNotOptedOut(from, to, _nullishCoalesce(input.tenantId, () => ( t.tenantId)));
1751
+ const variables = (_nullishCoalesce(input.variables, () => ( []))).map((v) => sanitizeTemplateVariable(v));
1752
+ const op = { kind: "whatsapp", tenantId: _nullishCoalesce(input.tenantId, () => ( t.tenantId)), from, to };
1753
+ return t.outbound(
1754
+ op,
1755
+ () => t.pick("whatsapp").sendTemplate({ ...input, ...from ? { from } : {}, to, variables })
1756
+ );
1757
+ },
1758
+ get: (id) => t.read("whatsapp", null, (p) => {
1759
+ if (!p.get) throw t.unsupported("consultar mensajes de WhatsApp");
1760
+ return p.get(id);
1761
+ })
1762
+ };
1763
+ }
1764
+ buildUsage() {
1765
+ return { query: (q) => this.read("usage", JSON.stringify(q), (p) => p.query(q)) };
1766
+ }
1767
+ // ── Bajas y registro ───────────────────────────────────────────────────────────────────────────────────────────
1768
+ /** Registra o quita una baja (la llaman los webhooks al recibir STOP/BAJA/ALTA; también tu pantalla de ajustes). */
1769
+ async setOptOut(line, recipient, optedOut, tenantId = this.tenantId) {
1770
+ const who = _nullishCoalesce(normalizeE164(recipient), () => ( recipient));
1771
+ for (const l of /* @__PURE__ */ new Set([_nullishCoalesce(normalizeE164(line), () => ( line)), "*"])) {
1772
+ const key = { tenantId, line: l, recipient: who };
1773
+ await (optedOut ? this.optOutStore.optOut(key) : this.optOutStore.optIn(key));
1774
+ }
1775
+ }
1776
+ isOptedOut(line, recipient, tenantId = this.tenantId) {
1777
+ return this.optOutStore.isOptedOut({
1778
+ tenantId,
1779
+ line: line && normalizeE164(line) || line || "*",
1780
+ recipient: _nullishCoalesce(normalizeE164(recipient), () => ( recipient))
1781
+ });
1782
+ }
1783
+ log(line) {
1784
+ const write = this.options.logger;
1785
+ if (!write) return;
1786
+ const secrets = [
1787
+ _optionalChain([this, 'access', _89 => _89.options, 'access', _90 => _90.twilio, 'optionalAccess', _91 => _91.authToken]),
1788
+ _optionalChain([this, 'access', _92 => _92.options, 'access', _93 => _93.metaWhatsApp, 'optionalAccess', _94 => _94.appSecret]),
1789
+ _optionalChain([this, 'access', _95 => _95.options, 'access', _96 => _96.metaWhatsApp, 'optionalAccess', _97 => _97.verifyToken])
1790
+ ];
1791
+ write(_chunkHMHUOXGBcjs.redactText.call(void 0, `[telephony] ${line}`, secrets));
1792
+ }
1793
+ };
1794
+
1795
+ // src/telephony/rules/event-deduper.ts
1796
+ var MemoryEventDeduper = class {
1797
+ constructor(ttlMs = 15 * 6e4, maxEntries = 5e4) {
1798
+ this.ttlMs = ttlMs;
1799
+ this.maxEntries = maxEntries;
1800
+ this.seen = /* @__PURE__ */ new Map();
1801
+ }
1802
+ async firstSeen(id, now = Date.now()) {
1803
+ const until = this.seen.get(id);
1804
+ if (until !== void 0 && until > now) return false;
1805
+ this.seen.delete(id);
1806
+ this.seen.set(id, now + this.ttlMs);
1807
+ if (this.seen.size > this.maxEntries) {
1808
+ for (const [k, t] of this.seen) {
1809
+ if (t <= now || this.seen.size > this.maxEntries) this.seen.delete(k);
1810
+ else break;
1811
+ }
1812
+ }
1813
+ return true;
1814
+ }
1815
+ };
1816
+
1817
+ // src/telephony/telephony.webhooks.ts
1818
+ var EMPTY = { body: "", contentType: "text/plain; charset=utf-8" };
1819
+ var reject = (status) => ({ status, response: EMPTY, events: [], done: Promise.resolve() });
1820
+ var TelephonyWebhooks = class {
1821
+ constructor(telephony, options = telephony.options, hooks = telephony.hooks, now = Date.now) {
1822
+ this.telephony = telephony;
1823
+ this.options = options;
1824
+ this.hooks = hooks;
1825
+ this.now = now;
1826
+ const w = _nullishCoalesce(options.webhook, () => ( {}));
1827
+ this.deduper = _nullishCoalesce(options.deduper, () => ( new MemoryEventDeduper()));
1828
+ this.maxSkewMs = _nullishCoalesce(w.maxSkewMs, () => ( 5 * 6e4));
1829
+ this.answerBudgetMs = _nullishCoalesce(w.answerBudgetMs, () => ( 2500));
1830
+ const texts = { ...DEFAULT_TEXTS, ..._nullishCoalesce(w.texts, () => ( {})) };
1831
+ this.fallback = _nullishCoalesce(w.fallbackAnswer, () => ( { kind: "hangup", message: texts.greetingFallback }));
1832
+ const limit = w.rateLimit === void 0 ? { max: 600, windowMs: 6e4 } : w.rateLimit;
1833
+ if (limit) this.limiter = new (0, _chunkHMHUOXGBcjs.SlidingWindowLimiter)(limit.max, limit.windowMs);
1834
+ }
1835
+ /** Reto de verificación por GET (Meta): `null` si el proveedor no lo soporta o el token no coincide. */
1836
+ challenge(provider, query, ctx = {}) {
1837
+ return this.adapter(provider, ctx).then((a) => _nullishCoalesce(_optionalChain([a, 'optionalAccess', _98 => _98.webhooks, 'access', _99 => _99.challenge, 'optionalCall', _100 => _100(query)]), () => ( null))).catch(() => null);
1838
+ }
1839
+ async adapter(provider, ctx) {
1840
+ try {
1841
+ const scope = ctx.tenantId ? await this.telephony.forTenant(ctx.tenantId) : this.telephony;
1842
+ return scope.adapterNamed(provider);
1843
+ } catch (e7) {
1844
+ return void 0;
1845
+ }
1846
+ }
1847
+ async handle(provider, request, ctx = {}) {
1848
+ const now = this.now();
1849
+ if (this.limiter && !this.limiter.allow(`${provider}|${_nullishCoalesce(ctx.source, () => ( ""))}`, now)) {
1850
+ this.log(`webhook ${provider}: demasiadas peticiones`);
1851
+ return reject(429);
1852
+ }
1853
+ const adapter = await this.adapter(provider, ctx);
1854
+ if (!adapter) return reject(404);
1855
+ let verified = false;
1856
+ try {
1857
+ verified = adapter.webhooks.verify(request);
1858
+ } catch (e8) {
1859
+ verified = false;
1860
+ }
1861
+ if (!verified) {
1862
+ this.log(`webhook ${provider}: firma inv\xE1lida`);
1863
+ return reject(403);
1864
+ }
1865
+ let parsed;
1866
+ try {
1867
+ parsed = adapter.webhooks.parse(request);
1868
+ } catch (e9) {
1869
+ return reject(400);
1870
+ }
1871
+ const accepted = [];
1872
+ const hadIncoming = parsed.some((e) => e.type === TELEPHONY_EVENTS.CALL_INCOMING);
1873
+ for (const event of parsed) {
1874
+ if (event.occurredAt !== void 0 && Math.abs(now - event.occurredAt) > this.maxSkewMs) {
1875
+ this.log(`webhook ${provider}: evento fuera de ventana (${event.type})`);
1876
+ continue;
1877
+ }
1878
+ if (!await this.deduper.firstSeen(`${provider}:${_nullishCoalesce(ctx.tenantId, () => ( ""))}:${event.id}`, now)) continue;
1879
+ const tenantId = await _asyncNullishCoalesce(ctx.tenantId, async () => ( await this.resolveTenant(event)));
1880
+ if (tenantId === null) continue;
1881
+ accepted.push(tenantId ? { ...event, tenantId } : event);
1882
+ }
1883
+ const background = [];
1884
+ let incoming;
1885
+ for (const event of accepted) {
1886
+ await this.recordKeyword(event);
1887
+ const run = Promise.resolve().then(() => _optionalChain([this, 'access', _101 => _101.hooks, 'access', _102 => _102.onEvent, 'optionalCall', _103 => _103(event)]));
1888
+ if (event.type === TELEPHONY_EVENTS.CALL_INCOMING && !incoming) {
1889
+ incoming = run;
1890
+ run.catch(() => void 0);
1891
+ } else {
1892
+ background.push(run.then(() => void 0, (e) => this.fail(e, event)));
1893
+ }
1894
+ }
1895
+ let response = adapter.webhooks.acknowledge();
1896
+ if (hadIncoming && !incoming) {
1897
+ response = this.buildAnswer(adapter, this.fallback, response);
1898
+ }
1899
+ if (incoming) {
1900
+ const first = accepted.find((e) => e.type === TELEPHONY_EVENTS.CALL_INCOMING);
1901
+ const instruction = await this.within(incoming, first);
1902
+ response = this.buildAnswer(adapter, _nullishCoalesce(instruction, () => ( this.fallback)), response);
1903
+ }
1904
+ return { status: 200, response, events: accepted, done: Promise.all(background).then(() => void 0) };
1905
+ }
1906
+ buildAnswer(adapter, instruction, ack) {
1907
+ try {
1908
+ return adapter.voice ? this.telephony.voice.buildAnswer(instruction) : ack;
1909
+ } catch (e10) {
1910
+ return ack;
1911
+ }
1912
+ }
1913
+ /** Espera a `onEvent` como mucho `answerBudgetMs`; falla o plazo vencido = `undefined` (respuesta de respaldo). */
1914
+ async within(run, event) {
1915
+ let timer;
1916
+ const timeout = new Promise((resolve) => {
1917
+ timer = setTimeout(() => resolve("timeout"), this.answerBudgetMs);
1918
+ });
1919
+ try {
1920
+ const winner = await Promise.race([run, timeout]);
1921
+ if (winner === "timeout") {
1922
+ this.log(`llamada entrante: onEvent tard\xF3 m\xE1s de ${this.answerBudgetMs} ms; se usa la respuesta de respaldo`);
1923
+ run.catch((e) => this.fail(e, event));
1924
+ return void 0;
1925
+ }
1926
+ return _nullishCoalesce(winner, () => ( void 0));
1927
+ } catch (e) {
1928
+ this.fail(e, event);
1929
+ return void 0;
1930
+ } finally {
1931
+ if (timer) clearTimeout(timer);
1932
+ }
1933
+ }
1934
+ /** `string` = tenant; `undefined` = no hay `resolveTenant` (se sigue sin tenant); `null` = de nadie (se ignora). */
1935
+ async resolveTenant(event) {
1936
+ if (!this.hooks.resolveTenant) return void 0;
1937
+ const numbers = this.numbersOf(event);
1938
+ if (!numbers.length) return void 0;
1939
+ for (const n of numbers) {
1940
+ const tenant = await this.hooks.resolveTenant(n);
1941
+ if (tenant) return tenant;
1942
+ }
1943
+ this.log(`evento ${event.type} de una l\xEDnea sin due\xF1o (${_chunkHMHUOXGBcjs.redactPhone.call(void 0, numbers[0])}): se ignora`);
1944
+ return null;
1945
+ }
1946
+ numbersOf(event) {
1947
+ switch (event.type) {
1948
+ case TELEPHONY_EVENTS.CALL_INCOMING:
1949
+ case TELEPHONY_EVENTS.SMS_RECEIVED:
1950
+ case TELEPHONY_EVENTS.WHATSAPP_RECEIVED:
1951
+ return [event.to];
1952
+ case TELEPHONY_EVENTS.CALL_STATUS:
1953
+ case TELEPHONY_EVENTS.CALL_ENDED:
1954
+ return [event.to, event.from];
1955
+ default:
1956
+ return [];
1957
+ }
1958
+ }
1959
+ /** STOP/BAJA entrante: la baja queda registrada **antes** de entregar el evento. Obligatorio, no opcional. */
1960
+ async recordKeyword(event) {
1961
+ if (event.type !== TELEPHONY_EVENTS.SMS_RECEIVED && event.type !== TELEPHONY_EVENTS.WHATSAPP_RECEIVED) return;
1962
+ const keyword = _nullishCoalesce(_nullishCoalesce(event.keyword, () => ( classifyKeyword(event.body))), () => ( void 0));
1963
+ if (!keyword || keyword === "help") return;
1964
+ await this.telephony.setOptOut(event.to, event.from, keyword === "opt_out", event.tenantId);
1965
+ }
1966
+ fail(error, event) {
1967
+ try {
1968
+ _optionalChain([this, 'access', _104 => _104.hooks, 'access', _105 => _105.onError, 'optionalCall', _106 => _106(error, event)]);
1969
+ } catch (e11) {
1970
+ }
1971
+ this.log(`onEvent fall\xF3 en ${event.type}: ${error instanceof Error ? error.name : "error"}`);
1972
+ }
1973
+ log(line) {
1974
+ _optionalChain([this, 'access', _107 => _107.options, 'access', _108 => _108.logger, 'optionalCall', _109 => _109(_chunkHMHUOXGBcjs.redactText.call(void 0, `[telephony] ${line}`))]);
1975
+ }
1976
+ };
1977
+
1978
+ // src/telephony/telephony.webhook.controller.ts
1979
+
1980
+ function createTelephonyWebhookController(options) {
1981
+ const base = options.publicBaseUrl.replace(/\/+$/, "");
1982
+ if (!/^https:\/\//.test(base) && !/^http:\/\/(localhost|127\.0\.0\.1)/.test(base)) {
1983
+ throw new Error("createTelephonyWebhookController: `publicBaseUrl` debe ser https:// (o localhost en desarrollo).");
1984
+ }
1985
+ let TelephonyWebhookControllerHost = class {
1986
+ constructor(webhooks) {
1987
+ this.webhooks = webhooks;
1988
+ }
1989
+ async verify(provider, query, res) {
1990
+ const challenge = await this.webhooks.challenge(provider, query);
1991
+ setStatus(res, challenge === null ? 403 : 200);
1992
+ res.type("text/plain");
1993
+ return _nullishCoalesce(challenge, () => ( ""));
1994
+ }
1995
+ handle(provider, req, res) {
1996
+ return this.run(provider, void 0, req, res);
1997
+ }
1998
+ handleTenant(provider, tenantId, req, res) {
1999
+ return this.run(provider, tenantId, req, res);
2000
+ }
2001
+ async run(provider, tenantId, req, res) {
2002
+ const body = req.body;
2003
+ const params = body && typeof body === "object" && !Array.isArray(body) ? Object.fromEntries(Object.entries(body).map(([k, v]) => [k, String(v)])) : void 0;
2004
+ const result = await this.webhooks.handle(
2005
+ provider,
2006
+ {
2007
+ url: `${base}${_nullishCoalesce(_nullishCoalesce(req.originalUrl, () => ( req.url)), () => ( ""))}`,
2008
+ headers: req.headers,
2009
+ rawBody: req.rawBody !== void 0 ? req.rawBody.toString("utf8") : typeof body === "string" ? body : void 0,
2010
+ params
2011
+ },
2012
+ { tenantId, source: req.ip }
2013
+ );
2014
+ setStatus(res, result.status);
2015
+ res.type(result.response.contentType);
2016
+ return result.response.body;
2017
+ }
2018
+ };
2019
+ _chunkLRX7AMSScjs.__decorateClass.call(void 0, [
2020
+ _common.Get.call(void 0, ":provider"),
2021
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 0, _common.Param.call(void 0, "provider")),
2022
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 1, _common.Query.call(void 0, )),
2023
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 2, _common.Res.call(void 0, { passthrough: true }))
2024
+ ], TelephonyWebhookControllerHost.prototype, "verify", 1);
2025
+ _chunkLRX7AMSScjs.__decorateClass.call(void 0, [
2026
+ _common.Post.call(void 0, ":provider"),
2027
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 0, _common.Param.call(void 0, "provider")),
2028
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 1, _common.Req.call(void 0, )),
2029
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 2, _common.Res.call(void 0, { passthrough: true }))
2030
+ ], TelephonyWebhookControllerHost.prototype, "handle", 1);
2031
+ _chunkLRX7AMSScjs.__decorateClass.call(void 0, [
2032
+ _common.Post.call(void 0, ":provider/:tenantId"),
2033
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 0, _common.Param.call(void 0, "provider")),
2034
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 1, _common.Param.call(void 0, "tenantId")),
2035
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 2, _common.Req.call(void 0, )),
2036
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 3, _common.Res.call(void 0, { passthrough: true }))
2037
+ ], TelephonyWebhookControllerHost.prototype, "handleTenant", 1);
2038
+ TelephonyWebhookControllerHost = _chunkLRX7AMSScjs.__decorateClass.call(void 0, [
2039
+ _common.Controller.call(void 0, _nullishCoalesce(options.path, () => ( "telephony/webhooks"))),
2040
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 0, _common.Inject.call(void 0, TELEPHONY_WEBHOOKS))
2041
+ ], TelephonyWebhookControllerHost);
2042
+ return TelephonyWebhookControllerHost;
2043
+ }
2044
+ function setStatus(res, code) {
2045
+ _optionalChain([(_nullishCoalesce(res.status, () => ( res.code))), 'optionalAccess', _110 => _110.call, 'call', _111 => _111(res, code)]);
2046
+ }
2047
+
2048
+ // src/telephony/telephony.module.ts
2049
+
2050
+ var env = (key) => process.env[key] || void 0;
2051
+ function resolveTelephonyOptions(options = {}) {
2052
+ const areaCode = env("TWILIO_AREA_CODE");
2053
+ const fallbacks = _optionalChain([env, 'call', _112 => _112("TELEPHONY_FALLBACKS"), 'optionalAccess', _113 => _113.split, 'call', _114 => _114(","), 'access', _115 => _115.map, 'call', _116 => _116((s) => s.trim()), 'access', _117 => _117.filter, 'call', _118 => _118(Boolean)]);
2054
+ return {
2055
+ ...options,
2056
+ provider: _nullishCoalesce(options.provider, () => ( env("TELEPHONY_PROVIDER"))),
2057
+ fallbacks: _nullishCoalesce(options.fallbacks, () => ( fallbacks)),
2058
+ twilio: _nullishCoalesce(options.twilio, () => ( (env("TWILIO_ACCOUNT_SID") ? {
2059
+ accountSid: env("TWILIO_ACCOUNT_SID"),
2060
+ authToken: _nullishCoalesce(env("TWILIO_AUTH_TOKEN"), () => ( "")),
2061
+ bundleSid: env("TWILIO_BUNDLE_SID"),
2062
+ addressSid: env("TWILIO_ADDRESS_SID"),
2063
+ areaCode: areaCode && /^\d{2,3}$/.test(areaCode) ? areaCode : void 0,
2064
+ baseUrl: env("TWILIO_BASE_URL"),
2065
+ whatsappFrom: env("TWILIO_WHATSAPP_FROM")
2066
+ } : void 0)))
2067
+ };
2068
+ }
2069
+ var isClass = (v) => typeof v === "function";
2070
+ function hooksProvider(hooks) {
2071
+ if (!hooks) return { provide: TELEPHONY_HOOKS, useValue: {} };
2072
+ return isClass(hooks) ? { provide: TELEPHONY_HOOKS, useClass: hooks } : { provide: TELEPHONY_HOOKS, useValue: hooks };
2073
+ }
2074
+ var core = [
2075
+ {
2076
+ provide: TELEPHONY,
2077
+ useFactory: (options, hooks) => new Telephony(resolveTelephonyOptions(options), hooks),
2078
+ inject: [TELEPHONY_OPTIONS, TELEPHONY_HOOKS]
2079
+ },
2080
+ { provide: Telephony, useExisting: TELEPHONY },
2081
+ { provide: TELEPHONY_WEBHOOKS, useFactory: (t) => new TelephonyWebhooks(t), inject: [TELEPHONY] },
2082
+ { provide: TelephonyWebhooks, useExisting: TELEPHONY_WEBHOOKS }
2083
+ ];
2084
+ var exported = [TELEPHONY, Telephony, TELEPHONY_OPTIONS, TELEPHONY_HOOKS, TELEPHONY_WEBHOOKS, TelephonyWebhooks];
2085
+ var TelephonyModule = class {
2086
+ static forRoot(options = {}, extras = {}) {
2087
+ return {
2088
+ module: TelephonyModule,
2089
+ imports: _nullishCoalesce(extras.imports, () => ( [])),
2090
+ providers: [{ provide: TELEPHONY_OPTIONS, useValue: options }, hooksProvider(extras.hooks), ...core],
2091
+ exports: exported
2092
+ };
2093
+ }
2094
+ static forRootAsync(config) {
2095
+ return {
2096
+ module: TelephonyModule,
2097
+ imports: _nullishCoalesce(config.imports, () => ( [])),
2098
+ providers: [
2099
+ { provide: TELEPHONY_OPTIONS, useFactory: config.useFactory, inject: _nullishCoalesce(config.inject, () => ( [])) },
2100
+ hooksProvider(config.hooks),
2101
+ ...core
2102
+ ],
2103
+ exports: exported
2104
+ };
2105
+ }
2106
+ };
2107
+ TelephonyModule = exports.TelephonyModule = _chunkLRX7AMSScjs.__decorateClass.call(void 0, [
2108
+ _common.Global.call(void 0, ),
2109
+ _common.Module.call(void 0, {})
2110
+ ], TelephonyModule);
2111
+
2112
+ // src/telephony/rules/call-token.ts
2113
+
2114
+ var DEFAULT_CALL_TOKEN_TTL_MS = 10 * 6e4;
2115
+ var b64url = (buf) => buf.toString("base64url");
2116
+ var mac = (payload, secret) => b64url(_crypto.createHmac.call(void 0, "sha256", secret).update(payload).digest());
2117
+ function signCallToken(claims, secret, now = Date.now(), ttlMs = DEFAULT_CALL_TOKEN_TTL_MS) {
2118
+ if (!secret) throw new Error("signCallToken: falta el secreto.");
2119
+ const payload = b64url(
2120
+ Buffer.from(JSON.stringify({ c: claims.callId, t: claims.tenantId, a: claims.actorId, e: now + ttlMs }))
2121
+ );
2122
+ return `${payload}.${mac(payload, secret)}`;
2123
+ }
2124
+ function verifyCallToken(token, secret, now = Date.now()) {
2125
+ if (!token || !secret) return null;
2126
+ const parts = token.split(".");
2127
+ if (parts.length !== 2) return null;
2128
+ const [payload, signature] = parts;
2129
+ if (!payload || !signature || !_chunk2RQINZCRcjs.constantTimeEqual.call(void 0, mac(payload, secret), signature)) return null;
2130
+ try {
2131
+ const d = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
2132
+ if (typeof d.c !== "string" || typeof d.t !== "string" || typeof d.a !== "string") return null;
2133
+ if (!d.c || !d.t || !d.a || typeof d.e !== "number" || !(d.e > now)) return null;
2134
+ return { callId: d.c, tenantId: d.t, actorId: d.a };
2135
+ } catch (e12) {
2136
+ return null;
2137
+ }
2138
+ }
2139
+ function verifyCallTokenFor(token, secret, expected, now = Date.now()) {
2140
+ const claims = verifyCallToken(token, secret, now);
2141
+ if (!claims) return null;
2142
+ if (!_chunk2RQINZCRcjs.constantTimeEqual.call(void 0, claims.callId, expected.callId)) return null;
2143
+ if (expected.tenantId !== void 0 && !_chunk2RQINZCRcjs.constantTimeEqual.call(void 0, claims.tenantId, expected.tenantId)) return null;
2144
+ return claims;
2145
+ }
2146
+
2147
+ // src/telephony/rules/call-limits.ts
2148
+ var DEFAULT_CALL_LIMITS = {
2149
+ maxTurns: 40,
2150
+ maxSeconds: 8 * 60,
2151
+ maxConcurrentPerLine: 3,
2152
+ maxCallsPerCaller: 6,
2153
+ maxCallsPerHiddenCaller: 30,
2154
+ callerWindowMs: 60 * 6e4
2155
+ };
2156
+ var CallLimiter = class {
2157
+ constructor(limits = {}) {
2158
+ this.active = /* @__PURE__ */ new Map();
2159
+ this.byCaller = /* @__PURE__ */ new Map();
2160
+ this.limits = { ...DEFAULT_CALL_LIMITS, ...limits };
2161
+ }
2162
+ /**
2163
+ * ¿Entra esta llamada con IA? `null` = sí (y queda registrada); si no, la razón. Repetir el mismo `callId` no
2164
+ * cuenta dos veces (los proveedores reintentan los webhooks).
2165
+ */
2166
+ enter(call, now = Date.now()) {
2167
+ this.sweep(now);
2168
+ if (this.active.has(call.callId)) return null;
2169
+ let concurrent = 0;
2170
+ for (const a of this.active.values()) if (a.lineId === call.lineId) concurrent++;
2171
+ if (concurrent >= this.limits.maxConcurrentPerLine) return "concurrent";
2172
+ const hidden = !call.caller || call.caller.replace(/\D/g, "").length < 6;
2173
+ const key = `${call.lineId}|${hidden ? "hidden" : call.caller}`;
2174
+ const previous = (_nullishCoalesce(this.byCaller.get(key), () => ( []))).filter((t) => t > now - this.limits.callerWindowMs);
2175
+ const cap = hidden ? this.limits.maxCallsPerHiddenCaller : this.limits.maxCallsPerCaller;
2176
+ if (previous.length >= cap) {
2177
+ this.byCaller.set(key, previous);
2178
+ return "caller";
2179
+ }
2180
+ previous.push(now);
2181
+ this.byCaller.set(key, previous);
2182
+ this.active.set(call.callId, { lineId: call.lineId, until: now + (this.limits.maxSeconds + 120) * 1e3 });
2183
+ return null;
2184
+ }
2185
+ /** La llamada terminó: libera su lugar. */
2186
+ leave(callId) {
2187
+ this.active.delete(callId);
2188
+ }
2189
+ sweep(now) {
2190
+ for (const [id, a] of this.active) if (a.until <= now) this.active.delete(id);
2191
+ if (this.byCaller.size > 5e3) {
2192
+ for (const [key, times] of this.byCaller) {
2193
+ if (times.every((t) => t <= now - this.limits.callerWindowMs)) this.byCaller.delete(key);
2194
+ }
2195
+ }
2196
+ }
2197
+ };
2198
+ var isOverTurnLimit = (turnNumber, limits = DEFAULT_CALL_LIMITS) => turnNumber > limits.maxTurns;
2199
+ var isOverDuration = (elapsedSeconds, limits = DEFAULT_CALL_LIMITS) => elapsedSeconds >= limits.maxSeconds;
2200
+
2201
+
2202
+
2203
+
2204
+
2205
+
2206
+
2207
+
2208
+
2209
+
2210
+
2211
+
2212
+
2213
+
2214
+
2215
+
2216
+
2217
+
2218
+
2219
+
2220
+
2221
+
2222
+
2223
+
2224
+
2225
+
2226
+
2227
+
2228
+
2229
+
2230
+
2231
+
2232
+
2233
+
2234
+
2235
+
2236
+
2237
+
2238
+
2239
+
2240
+
2241
+
2242
+
2243
+
2244
+
2245
+
2246
+
2247
+
2248
+
2249
+
2250
+
2251
+
2252
+
2253
+
2254
+
2255
+
2256
+
2257
+
2258
+
2259
+
2260
+
2261
+
2262
+
2263
+
2264
+
2265
+
2266
+
2267
+
2268
+
2269
+ exports.BLOCKED_MX_PREFIXES = BLOCKED_MX_PREFIXES; exports.BUILT_IN_PROVIDERS = BUILT_IN_PROVIDERS; exports.CallLimiter = CallLimiter; exports.DEFAULT_BLOCKED_PREFIXES = DEFAULT_BLOCKED_PREFIXES; exports.DEFAULT_CALL_LIMITS = DEFAULT_CALL_LIMITS; exports.DEFAULT_CALL_TOKEN_TTL_MS = DEFAULT_CALL_TOKEN_TTL_MS; exports.DEFAULT_TEXTS = DEFAULT_TEXTS; exports.DestinationNotAllowedException = DestinationNotAllowedException; exports.GateRejectedError = GateRejectedError; exports.HANDOFF_DATA = _chunkHMHUOXGBcjs.HANDOFF_DATA; exports.HELP_KEYWORDS = HELP_KEYWORDS; exports.InvalidMessageException = InvalidMessageException; exports.MAX_SMS_BODY = MAX_SMS_BODY; exports.MemoryEventDeduper = MemoryEventDeduper; exports.MemoryOptOutStore = MemoryOptOutStore; exports.MetaWhatsAppTelephony = MetaWhatsAppTelephony; exports.OPT_IN_KEYWORDS = OPT_IN_KEYWORDS; exports.OPT_OUT_KEYWORDS = OPT_OUT_KEYWORDS; exports.ProviderGate = ProviderGate; exports.RecipientOptedOutException = RecipientOptedOutException; exports.SimulatedTelephony = SimulatedTelephony; exports.SlidingWindowLimiter = _chunkHMHUOXGBcjs.SlidingWindowLimiter; exports.TELEPHONY = TELEPHONY; exports.TELEPHONY_EVENTS = TELEPHONY_EVENTS; exports.TELEPHONY_HOOKS = TELEPHONY_HOOKS; exports.TELEPHONY_OPTIONS = TELEPHONY_OPTIONS; exports.TELEPHONY_PORT_VERSION = TELEPHONY_PORT_VERSION; exports.TELEPHONY_WEBHOOKS = TELEPHONY_WEBHOOKS; exports.Telephony = Telephony; exports.TelephonyLimitExceededException = TelephonyLimitExceededException; exports.TelephonyModule = TelephonyModule; exports.TelephonyProviderException = TelephonyProviderException; exports.TelephonyRegistry = TelephonyRegistry; exports.TelephonyWebhooks = TelephonyWebhooks; exports.TenantNotConfiguredException = TenantNotConfiguredException; exports.TtlCache = TtlCache; exports.TwilioTelephony = TwilioTelephony; exports.UnsupportedCapabilityException = UnsupportedCapabilityException; exports.UsageCounter = UsageCounter; exports.billableMinutes = billableMinutes; exports.checkDestination = checkDestination; exports.classifyKeyword = classifyKeyword; exports.createProviderHttp = createProviderHttp; exports.createRedactingLogger = _chunkHMHUOXGBcjs.createRedactingLogger; exports.createTelephonyWebhookController = createTelephonyWebhookController; exports.escapeXml = escapeXml; exports.isAllowedDialDestination = isAllowedDialDestination; exports.isE164 = isE164; exports.isHandoffRequested = _chunkHMHUOXGBcjs.isHandoffRequested; exports.isOverDuration = isOverDuration; exports.isOverTurnLimit = isOverTurnLimit; exports.normalizeE164 = normalizeE164; exports.providerError = providerError; exports.redactPhone = _chunkHMHUOXGBcjs.redactPhone; exports.redactPhonesInText = _chunkHMHUOXGBcjs.redactPhonesInText; exports.redactText = _chunkHMHUOXGBcjs.redactText; exports.resolveTelephonyOptions = resolveTelephonyOptions; exports.sanitizeDialDestination = sanitizeDialDestination; exports.sanitizeMessageBody = sanitizeMessageBody; exports.sanitizeTemplateVariable = sanitizeTemplateVariable; exports.signCallToken = signCallToken; exports.simulatedSignature = simulatedSignature; exports.stripChannelPrefix = stripChannelPrefix; exports.stripControl = stripControl; exports.toE164Mexico = toE164Mexico; exports.twilioSignature = twilioSignature; exports.verifyCallToken = verifyCallToken; exports.verifyCallTokenFor = verifyCallTokenFor;