@theokit/gateway-whatsapp 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -77,20 +77,31 @@ function resolveParties(key, remoteJid) {
77
77
  const fromPhone = normalizeWhatsAppId(senderJid);
78
78
  const channelId = normalizeWhatsAppId(remoteJid);
79
79
  if (fromPhone.length === 0 || channelId.length === 0) return void 0;
80
- return { fromPhone, channelId, isGroup };
80
+ return { fromPhone, channelId, channelJid: remoteJid, isGroup };
81
81
  }
82
- function isDispatchable(key, remoteJid) {
83
- if (key.fromMe === true) return false;
84
- return remoteJid !== STATUS_BROADCAST_JID;
82
+ function isDispatchable(key, remoteJid, wamid, ctx) {
83
+ if (remoteJid === STATUS_BROADCAST_JID) return "no";
84
+ if (key.fromMe !== true) return "yes";
85
+ const selfJids = ctx?.selfJids;
86
+ if (selfJids === void 0 || selfJids.size === 0) return "no";
87
+ if (!selfJids.has(normalizeWhatsAppId(remoteJid))) return "no";
88
+ return ctx?.sentWamids?.has(wamid) === true ? "no" : "yes-from-self";
85
89
  }
86
- function normalizeBaileysMessage(raw) {
87
- const envelope = asObject(raw);
90
+ function addressingOf(envelope) {
88
91
  const key = envelope === void 0 ? void 0 : asObject(envelope.key);
89
92
  if (key === void 0) return void 0;
90
93
  const remoteJid = asText(key.remoteJid);
91
94
  const wamid = asText(key.id);
92
95
  if (remoteJid === void 0 || wamid === void 0) return void 0;
93
- if (!isDispatchable(key, remoteJid)) return void 0;
96
+ return { key, remoteJid, wamid };
97
+ }
98
+ function normalizeBaileysMessage(raw, ctx) {
99
+ const envelope = asObject(raw);
100
+ const addressed = addressingOf(envelope);
101
+ if (addressed === void 0) return void 0;
102
+ const { key, remoteJid, wamid } = addressed;
103
+ const verdict = isDispatchable(key, remoteJid, wamid, ctx);
104
+ if (verdict === "no") return void 0;
94
105
  const text = extractText(envelope?.message);
95
106
  if (text === void 0) return void 0;
96
107
  const parties = resolveParties(key, remoteJid);
@@ -103,10 +114,12 @@ function normalizeBaileysMessage(raw) {
103
114
  fromPhone: parties.fromPhone,
104
115
  conversationType: parties.isGroup ? "group" : "dm",
105
116
  channelId: parties.channelId,
117
+ channelJid: parties.channelJid,
106
118
  text,
107
119
  receivedAt: seconds * 1e3,
108
120
  backend: "baileys",
109
121
  raw,
122
+ ...verdict === "yes-from-self" ? { fromSelf: true } : {},
110
123
  ...contactName !== void 0 ? { contactName } : {}
111
124
  };
112
125
  }
@@ -276,6 +289,8 @@ function endQuietly(socket) {
276
289
  }
277
290
  var DEFAULT_CONNECT_TIMEOUT_MS = 6e4;
278
291
  var DEFAULT_SEND_TIMEOUT_MS = 3e4;
292
+ var UNROUTABLE = "__unroutable__";
293
+ var SENT_WAMID_WINDOW = 256;
279
294
  var WhatsAppBaileysBackend = class {
280
295
  constructor(opts) {
281
296
  this.opts = opts;
@@ -310,6 +325,54 @@ var WhatsAppBaileysBackend = class {
310
325
  * `rules/error-handling.md` § 3: fail clear, and log with enough context to act.
311
326
  */
312
327
  lastCloseError;
328
+ /** The pairing, as a caller may ask for it. Never handed out mutable. */
329
+ pairingState = { status: "idle" };
330
+ /**
331
+ * The JIDs that ARE this account, normalised. Empty until a socket reports who it logged in as.
332
+ *
333
+ * Empty means "not learned yet", and `isDispatchable` reads that as refusing everything this
334
+ * account sent — the same behaviour as before self-chat support existed. A backend that
335
+ * guessed here would answer in a stranger's conversation.
336
+ */
337
+ selfJids = /* @__PURE__ */ new Set();
338
+ /**
339
+ * Ids this backend sent, most recent last. This is what stops the agent answering itself.
340
+ *
341
+ * Bounded because it is a loop guard, not a log: an unbounded set on a long-lived socket is a
342
+ * leak, and nothing needs to recognise an echo from an hour ago — WhatsApp delivers our own
343
+ * message back within seconds or not at all.
344
+ */
345
+ sentWamids = /* @__PURE__ */ new Set();
346
+ /** Record one id we sent, evicting the oldest once the window is full. @internal */
347
+ rememberSent(wamid) {
348
+ this.sentWamids.add(wamid);
349
+ while (this.sentWamids.size > SENT_WAMID_WINDOW) {
350
+ const oldest = this.sentWamids.values().next();
351
+ if (oldest.done === true) break;
352
+ this.sentWamids.delete(oldest.value);
353
+ }
354
+ }
355
+ /**
356
+ * Learn which JIDs are this account, from the socket that just logged in.
357
+ *
358
+ * Both forms are recorded: the phone JID and the LID. The self-chat is addressed by LID —
359
+ * measured on a real account, where a note-to-self arrived on `231116569108705@lid` while the
360
+ * account's phone JID was `553598838687` — so recording only one leaves the self-chat
361
+ * unrecognised and the feature silently off.
362
+ *
363
+ * @internal
364
+ */
365
+ learnSelfJids(socket) {
366
+ const user = socket.user;
367
+ const ids = [user?.id, user?.lid].filter((id) => typeof id === "string" && id.length > 0).map((id) => normalizeWhatsAppId(id)).filter((id) => id.length > 0);
368
+ this.selfJids = new Set(ids);
369
+ if (process.env.THEOKIT_WHATSAPP_TRACE === "1") {
370
+ process.stderr.write(
371
+ `[whatsapp-baileys][trace] selfJids learned: ${ids.length === 0 ? "(none)" : ids.join(", ")}
372
+ `
373
+ );
374
+ }
375
+ }
313
376
  inboundHandler;
314
377
  statusHandler;
315
378
  /**
@@ -322,6 +385,14 @@ var WhatsAppBaileysBackend = class {
322
385
  * the failure it guards against is a message delivered to the wrong person.
323
386
  */
324
387
  sendQueue = Promise.resolve();
388
+ /**
389
+ * What WhatsApp answered about each recipient, for the life of the session.
390
+ *
391
+ * Holds the routable JID, or {@link UNROUTABLE} for a number the server does not know. Both are
392
+ * worth remembering: a second send to a number that does not exist should refuse as fast as the
393
+ * first, without another round-trip.
394
+ */
395
+ jidCache = /* @__PURE__ */ new Map();
325
396
  /**
326
397
  * Open the socket and wait for it to report `open`.
327
398
  *
@@ -366,20 +437,68 @@ var WhatsAppBaileysBackend = class {
366
437
  }
367
438
  if (this.socket !== void 0 && this.socket !== socket) endQuietly(this.socket);
368
439
  this.socket = socket;
440
+ this.learnSelfJids(socket);
369
441
  this.connected = true;
370
442
  return true;
371
443
  }
444
+ /**
445
+ * What the pairing is doing right now.
446
+ *
447
+ * Read it as often as a screen needs; it is a snapshot, not a subscription.
448
+ */
449
+ get pairing() {
450
+ return this.pairingState;
451
+ }
372
452
  /** Build a socket through the injected factory, or the real one. @internal */
373
453
  async buildSocket() {
374
454
  const factory = this.opts.socketFactory ?? createBaileysSocket;
375
455
  return factory({
376
456
  sessionDir: this.opts.sessionDir,
377
- ...this.opts.onQr !== void 0 ? { onQr: this.opts.onQr } : {}
457
+ // ALWAYS supplied, even when the caller wants none: a backend that only forwards cannot
458
+ // answer `pairing`, and the caller's own handler still runs, so wiring one costs nothing.
459
+ onQr: (qr) => {
460
+ this.pairingState = { status: "awaiting_scan", qr, qrAt: Date.now() };
461
+ this.opts.onQr?.(qr);
462
+ }
463
+ });
464
+ }
465
+ /**
466
+ * Trace one inbound batch BEFORE any filter, when `THEOKIT_WHATSAPP_TRACE=1`.
467
+ *
468
+ * Two independent filters can discard an envelope — the batch `type` here and `fromMe` inside
469
+ * `normalizeBaileysMessage` — and from outside, both look identical: nothing happens. Telling
470
+ * them apart by reading the code is guessing; this is how you find out which one fired.
471
+ *
472
+ * Deliberately content-free. A Baileys session pairs a REAL account carrying real
473
+ * conversations, so the trace records shape (type, direction, group, has-text) and the last
474
+ * four digits of the jid, never the message and never a full contact number.
475
+ *
476
+ * @internal
477
+ */
478
+ traceBatch(payload) {
479
+ if (process.env.THEOKIT_WHATSAPP_TRACE !== "1") return;
480
+ const messages = payload.messages ?? [];
481
+ const rows = messages.map((raw) => {
482
+ const key = raw?.key ?? {};
483
+ const jid = typeof key.remoteJid === "string" ? key.remoteJid : "";
484
+ const message = raw?.message;
485
+ return [
486
+ `fromMe=${String(key.fromMe === true)}`,
487
+ `jid=\u2026${jid.replace(/\D/g, "").slice(-4)}`,
488
+ `group=${String(jid.endsWith("@g.us"))}`,
489
+ `hasMessage=${String(message !== null && message !== void 0)}`
490
+ ].join(" ");
378
491
  });
492
+ process.stderr.write(
493
+ `[whatsapp-baileys][trace] upsert type=${payload.type ?? "(none)"} n=${messages.length}` + (rows.length === 0 ? "\n" : `
494
+ ${rows.join("\n ")}
495
+ `)
496
+ );
379
497
  }
380
498
  /** Route this socket's inbound batches into the handler, while it is still current. @internal */
381
499
  subscribeInbound(socket, isCurrent) {
382
500
  socket.ev.on("messages.upsert", (payload) => {
501
+ this.traceBatch(payload);
383
502
  if (payload.type !== void 0 && payload.type !== "notify") return;
384
503
  if (!isCurrent()) return;
385
504
  for (const raw of payload.messages ?? []) this.dispatchInbound(raw);
@@ -406,12 +525,14 @@ var WhatsAppBaileysBackend = class {
406
525
  socket.ev.on("connection.update", (update) => {
407
526
  if (!isCurrent()) return;
408
527
  if (update.connection === "open") {
528
+ this.pairingState = { status: "connected" };
409
529
  settle(true);
410
530
  return;
411
531
  }
412
532
  if (update.connection !== "close") return;
413
533
  this.lastCloseError = update.lastDisconnect?.error;
414
534
  this.connected = false;
535
+ this.pairingState = { status: "closed" };
415
536
  if (this.socket === socket) this.socket = void 0;
416
537
  endQuietly(socket);
417
538
  settle(false);
@@ -520,10 +641,20 @@ var WhatsAppBaileysBackend = class {
520
641
  inFlight: Promise.resolve()
521
642
  };
522
643
  }
523
- const jid = `${message.to}@${message.isGroup ? "g.us" : "s.whatsapp.net"}`;
524
644
  const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;
525
- const inFlight = socket.sendMessage(jid, { text: message.text });
526
- const result = this.raceSend(inFlight, timeoutMs).then((outcome) => {
645
+ const send = this.resolveJid(socket, message).then(
646
+ async (jid) => jid === void 0 ? UNROUTABLE : await socket.sendMessage(jid, { text: message.text })
647
+ );
648
+ const result = this.raceSend(send, timeoutMs).then((outcome) => {
649
+ if (outcome === UNROUTABLE) {
650
+ return {
651
+ ok: false,
652
+ error: {
653
+ code: "undeliverable",
654
+ message: `WhatsApp does not route to "${message.to}" \u2014 the number is not registered, or not in the form this account can reach. Nothing was sent.`
655
+ }
656
+ };
657
+ }
527
658
  if (outcome === "timeout") {
528
659
  return {
529
660
  ok: false,
@@ -534,6 +665,7 @@ var WhatsAppBaileysBackend = class {
534
665
  };
535
666
  }
536
667
  const wamid = outcome?.key?.id;
668
+ if (wamid !== void 0) this.rememberSent(wamid);
537
669
  return wamid !== void 0 ? { ok: true, wamid } : { ok: true };
538
670
  }).catch((err) => ({
539
671
  ok: false,
@@ -542,7 +674,41 @@ var WhatsAppBaileysBackend = class {
542
674
  message: err instanceof Error ? err.message : String(err)
543
675
  }
544
676
  }));
545
- return { result, inFlight };
677
+ return { result, inFlight: send };
678
+ }
679
+ /**
680
+ * The JID WhatsApp routes this message to, or `undefined` when it routes to nobody.
681
+ *
682
+ * A group id is not a phone number and `onWhatsApp` answers about numbers, so groups pass
683
+ * straight through — asking would refuse every group message.
684
+ *
685
+ * The answer is cached for the life of the session. It is a fact about a number's registration,
686
+ * which does not change while a socket lives, and paying a round-trip per message would make
687
+ * every send slower for something already known.
688
+ *
689
+ * A socket without `onWhatsApp` — an older Baileys, or a fake predating this — sends to the
690
+ * number as given, which is the behaviour from before #82. Refusing on a missing capability
691
+ * would turn an upgrade problem into an outage.
692
+ */
693
+ async resolveJid(socket, message) {
694
+ if (message.to.includes("@")) return message.to;
695
+ if (message.isGroup) return `${message.to}@g.us`;
696
+ if (socket.onWhatsApp === void 0) return `${message.to}@s.whatsapp.net`;
697
+ const cached = this.jidCache.get(message.to);
698
+ if (cached !== void 0) return cached === UNROUTABLE ? void 0 : cached;
699
+ let answer;
700
+ try {
701
+ answer = await socket.onWhatsApp(message.to);
702
+ } catch {
703
+ return `${message.to}@s.whatsapp.net`;
704
+ }
705
+ const entry = answer?.[0];
706
+ if (entry?.exists !== true || entry.jid === void 0 || entry.jid === "") {
707
+ this.jidCache.set(message.to, UNROUTABLE);
708
+ return void 0;
709
+ }
710
+ this.jidCache.set(message.to, entry.jid);
711
+ return entry.jid;
546
712
  }
547
713
  /** Subscribe to inbound events. EC-H: a second call REPLACES the first. */
548
714
  onInbound(handler) {
@@ -577,7 +743,10 @@ var WhatsAppBaileysBackend = class {
577
743
  dispatchInbound(raw) {
578
744
  const handler = this.inboundHandler;
579
745
  if (handler === void 0) return;
580
- const event = normalizeBaileysMessage(raw);
746
+ const event = normalizeBaileysMessage(raw, {
747
+ selfJids: this.selfJids,
748
+ sentWamids: this.sentWamids
749
+ });
581
750
  if (event === void 0) return;
582
751
  void handler(event).catch((err) => {
583
752
  const message = err instanceof Error ? err.message : String(err);
@@ -1467,6 +1636,30 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends BasePlatformAdapter {
1467
1636
  connected = false;
1468
1637
  handler;
1469
1638
  statusHandler;
1639
+ /** Whether the "this platform carries no format flag" warning has already been emitted. */
1640
+ warnedAboutFormat = false;
1641
+ /**
1642
+ * Say, once, that a declared `format` has nowhere to go on this platform.
1643
+ *
1644
+ * WhatsApp's emphasis is INLINE — `*bold*`, `_italic_` — carried in the message text itself,
1645
+ * with no field on the request to set and no escape sequence to suppress it. So a caller
1646
+ * declaring `markdown` has already put the syntax in the text, and one declaring `html` is
1647
+ * asking for something the platform does not have.
1648
+ *
1649
+ * Reading the field is what turns a silent discard into a stated one — the swallowed-error
1650
+ * shape `rules/error-handling.md` refuses.
1651
+ *
1652
+ * @internal
1653
+ */
1654
+ warnFormatUnsupported(format) {
1655
+ if (format === void 0 || format === "plain") return;
1656
+ if (this.warnedAboutFormat) return;
1657
+ this.warnedAboutFormat = true;
1658
+ process.stderr.write(
1659
+ `[whatsapp] format="${format}" was declared, and WhatsApp cannot carry it as a flag \u2014 its emphasis is inline in the text. Sending as-is; this is logged once.
1660
+ `
1661
+ );
1662
+ }
1470
1663
  // EC-H: track unsubscribe handles so onInbound REPLACES instead of stacks.
1471
1664
  inboundUnsubscribe;
1472
1665
  statusUnsubscribe;
@@ -1610,6 +1803,7 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends BasePlatformAdapter {
1610
1803
  if (out.text.length === 0) {
1611
1804
  return { ok: false, error: { code: "empty_text", message: "Empty text rejected." } };
1612
1805
  }
1806
+ this.warnFormatUnsupported(out.format);
1613
1807
  const parts = splitForWhatsApp(out.text);
1614
1808
  if (parts.length === 0) {
1615
1809
  return {
@@ -1641,6 +1835,7 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends BasePlatformAdapter {
1641
1835
  * first thing a mistyped allowlist causes is an operator wondering why the bot went mute.
1642
1836
  */
1643
1837
  isRefusedBySenderAllowlist(inbound) {
1838
+ if (inbound.fromSelf === true) return false;
1644
1839
  if (this.allowedSenders === void 0) return false;
1645
1840
  if (isSenderAllowed(inbound.fromPhone, this.allowedSenders)) return false;
1646
1841
  process.stderr.write(
@@ -1672,6 +1867,7 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends BasePlatformAdapter {
1672
1867
  wamid: inbound.wamid,
1673
1868
  phoneNumberId: inbound.phoneNumberId,
1674
1869
  contactName: inbound.contactName,
1870
+ channelJid: inbound.channelJid,
1675
1871
  backend: inbound.backend,
1676
1872
  raw: inbound.raw
1677
1873
  }
@@ -1711,6 +1907,15 @@ var WhatsAppAdapter = class _WhatsAppAdapter extends BasePlatformAdapter {
1711
1907
  }
1712
1908
  };
1713
1909
  }
1910
+ /**
1911
+ * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
1912
+ *
1913
+ * One line over `runHandler`, which owns the containment: a handler is user code, its throw is
1914
+ * named as the handler's failure rather than the platform's, and delivery continues.
1915
+ */
1916
+ async deliver(event) {
1917
+ return this.runHandler(this.handler, event);
1918
+ }
1714
1919
  };
1715
1920
 
1716
1921
  export { ConfigurationError, LineBuffer, WhatsAppAdapter, WhatsAppBaileysBackend, WhatsAppBridgeError, WhatsAppCloudBackend, WhatsAppConnectTimeoutError, WhatsAppWebBackend, createBaileysSocket, defaultBridgeScriptPath, digitsOnly, formatCommand, mapWhatsAppCloudError, mapWhatsAppWebError, normalizeInboundMessages, normalizeStatusReceipts, parseEvent, parseWebhookPayload, splitForWhatsApp, verifyWebhookSignature, verifyWebhookSubscription };