@theokit/gateway-whatsapp 0.1.2 → 0.3.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.cjs CHANGED
@@ -2,9 +2,10 @@
2
2
 
3
3
  var gateway = require('@theokit/gateway');
4
4
  var crypto = require('crypto');
5
- var path = require('path');
6
- var child_process = require('child_process');
7
5
  var fs = require('fs');
6
+ var path2 = require('path');
7
+ var url = require('url');
8
+ var child_process = require('child_process');
8
9
 
9
10
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
10
11
  function _interopNamespace(e) {
@@ -26,156 +27,156 @@ function _interopNamespace(e) {
26
27
  }
27
28
 
28
29
  var crypto__namespace = /*#__PURE__*/_interopNamespace(crypto);
29
- var path__namespace = /*#__PURE__*/_interopNamespace(path);
30
30
  var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
31
+ var path2__namespace = /*#__PURE__*/_interopNamespace(path2);
31
32
 
32
33
  // src/adapter.ts
33
- var WHATSAPP_MAX_TEXT = 4096;
34
- function splitForWhatsApp(text) {
35
- return gateway.chunkText(text, {
36
- limit: WHATSAPP_MAX_TEXT,
37
- boundaries: ["\n\n", "\n", " "],
38
- lastResort: "last-boundary",
39
- surrogateGuard: true,
40
- stripLeading: /^\s+/,
41
- trimParts: true
42
- });
34
+
35
+ // src/allowlist.ts
36
+ var WILDCARD = "*";
37
+ function normalizeWhatsAppId(value) {
38
+ const withoutDevice = value.replace(/:[^@]*(?=@)/, "");
39
+ const withoutDomain = withoutDevice.replace(/@.*$/, "");
40
+ return withoutDomain.replace(/\D/g, "");
41
+ }
42
+ function parseAllowedSenders(raw) {
43
+ const entries = (raw ?? "").split(",").map((entry) => entry.trim()).map((entry) => entry === WILDCARD ? WILDCARD : normalizeWhatsAppId(entry)).filter((entry) => entry.length > 0);
44
+ return new Set(entries);
45
+ }
46
+ function isSenderAllowed(senderId, allowed) {
47
+ const normalized = normalizeWhatsAppId(senderId);
48
+ if (normalized.length === 0) return false;
49
+ if (allowed.size === 0) return false;
50
+ if (allowed.has(WILDCARD)) return true;
51
+ return allowed.has(normalized);
43
52
  }
44
53
 
45
- // src/adapter.ts
46
- function digitsOnly(s) {
47
- return s.replace(/[^\d]/g, "");
54
+ // src/backend/baileys/normalize.ts
55
+ var STATUS_BROADCAST_JID = "status@broadcast";
56
+ var WRAPPER_KEYS = [
57
+ "ephemeralMessage",
58
+ "viewOnceMessage",
59
+ "viewOnceMessageV2",
60
+ "documentWithCaptionMessage"
61
+ ];
62
+ var MAX_WRAPPER_DEPTH = 3;
63
+ function asObject(value) {
64
+ return typeof value === "object" && value !== null ? value : void 0;
48
65
  }
49
- var PHONE_RUN = /[\d][\d+\-().  ]*[\d]|[\d]/g;
50
- function phoneRuns(s) {
51
- return (s.match(PHONE_RUN) ?? []).map(digitsOnly).filter((d) => d.length > 0);
66
+ function asText(value) {
67
+ return typeof value === "string" && value.length > 0 ? value : void 0;
52
68
  }
53
- var WhatsAppAdapter = class extends gateway.BasePlatformAdapter {
54
- platform = "whatsapp";
55
- backendImpl;
56
- requireMention;
57
- botPhoneId;
58
- /** Mirrors the sibling adapters: guards connect() against opening a second session. */
59
- connected = false;
60
- handler;
61
- statusHandler;
62
- // EC-H: track unsubscribe handles so onInbound REPLACES instead of stacks.
63
- inboundUnsubscribe;
64
- statusUnsubscribe;
65
- /** Construct from a pre-built backend (used by the static factories + tests). */
66
- constructor(backendImpl, opts = {}) {
67
- super();
68
- this.backendImpl = backendImpl;
69
- this.requireMention = opts.requireMention ?? true;
70
- this.botPhoneId = digitsOnly(opts.botPhoneId ?? "");
71
- }
72
- /** Escape hatch (D180-style) for advanced features. */
73
- getBackend() {
74
- return this.backendImpl;
75
- }
76
- async connect() {
77
- if (this.connected) return true;
78
- const ok = await this.backendImpl.connect();
79
- this.connected = ok;
80
- return ok;
81
- }
82
- async disconnect() {
83
- this.connected = false;
84
- this.inboundUnsubscribe?.();
85
- this.inboundUnsubscribe = void 0;
86
- this.statusUnsubscribe?.();
87
- this.statusUnsubscribe = void 0;
88
- this.handler = void 0;
89
- this.statusHandler = void 0;
90
- await this.backendImpl.disconnect();
91
- }
92
- async sendMessage(out) {
93
- if (out.text.length === 0) {
94
- return { ok: false, error: { code: "empty_text", message: "Empty text rejected." } };
95
- }
96
- const parts = splitForWhatsApp(out.text);
97
- if (parts.length === 0) {
98
- return {
99
- ok: false,
100
- error: { code: "empty_text", message: "Text reduced to zero parts after splitting." }
101
- };
102
- }
103
- let lastWamid;
104
- const isGroup = out.channel.type === "group";
105
- for (const part of parts) {
106
- const r = await this.backendImpl.send({ to: out.channel.id, isGroup, text: part });
107
- if (!r.ok) {
108
- return {
109
- ok: false,
110
- error: { code: r.error?.code ?? "unknown", message: r.error?.message ?? "Send failed." }
111
- };
112
- }
113
- lastWamid = r.wamid;
114
- }
115
- return lastWamid !== void 0 ? { ok: true, messageId: lastWamid } : { ok: true };
69
+ function extractText(message, depth = 0) {
70
+ if (message === void 0 || depth > MAX_WRAPPER_DEPTH) return void 0;
71
+ const direct = asText(message.conversation);
72
+ if (direct !== void 0) return direct;
73
+ const extended = asObject(message.extendedTextMessage);
74
+ const fromExtended = extended === void 0 ? void 0 : asText(extended.text);
75
+ if (fromExtended !== void 0) return fromExtended;
76
+ for (const wrapper of WRAPPER_KEYS) {
77
+ const inner = asObject(message[wrapper]);
78
+ const nested = inner === void 0 ? void 0 : asObject(inner.message);
79
+ const text = extractText(nested, depth + 1);
80
+ if (text !== void 0) return text;
116
81
  }
117
- /** D309 + EC-7: group filter with digit-only normalization. */
118
- shouldDropGroupMessage(inbound) {
119
- if (inbound.conversationType !== "group" || !this.requireMention) return false;
120
- if (this.botPhoneId.length === 0) return true;
121
- return !phoneRuns(inbound.text).some((run) => run.includes(this.botPhoneId));
82
+ return void 0;
83
+ }
84
+ function toSeconds(timestamp) {
85
+ if (typeof timestamp === "number") return timestamp;
86
+ if (typeof timestamp === "string") {
87
+ const parsed = Number(timestamp);
88
+ return Number.isFinite(parsed) ? parsed : void 0;
122
89
  }
123
- toMessageEvent(inbound) {
124
- return {
125
- id: inbound.wamid,
126
- platform: "whatsapp",
127
- sender: { id: inbound.fromPhone, displayName: inbound.contactName },
128
- channel: { id: inbound.channelId, type: inbound.conversationType },
129
- text: inbound.text,
130
- receivedAt: inbound.receivedAt,
131
- whatsapp: {
132
- wamid: inbound.wamid,
133
- phoneNumberId: inbound.phoneNumberId,
134
- contactName: inbound.contactName,
135
- backend: inbound.backend,
136
- raw: inbound.raw
137
- }
138
- };
90
+ const asLong = asObject(timestamp);
91
+ if (asLong !== void 0 && typeof asLong.toNumber === "function") {
92
+ const parsed = asLong.toNumber();
93
+ return typeof parsed === "number" && Number.isFinite(parsed) ? parsed : void 0;
139
94
  }
140
- onInbound(handler) {
141
- this.inboundUnsubscribe?.();
142
- this.handler = handler;
143
- this.inboundUnsubscribe = this.backendImpl.onInbound(async (inbound) => {
144
- if (!this.handler) return;
145
- if (this.shouldDropGroupMessage(inbound)) return;
146
- await this.handler(this.toMessageEvent(inbound));
147
- });
148
- return () => {
149
- this.inboundUnsubscribe?.();
150
- this.inboundUnsubscribe = void 0;
151
- this.handler = void 0;
152
- };
95
+ return void 0;
96
+ }
97
+ function resolveParties(key, remoteJid) {
98
+ const isGroup = remoteJid.endsWith("@g.us");
99
+ const senderJid = isGroup ? asText(key.participant) : remoteJid;
100
+ if (senderJid === void 0) return void 0;
101
+ const fromPhone = normalizeWhatsAppId(senderJid);
102
+ const channelId = normalizeWhatsAppId(remoteJid);
103
+ if (fromPhone.length === 0 || channelId.length === 0) return void 0;
104
+ return { fromPhone, channelId, isGroup };
105
+ }
106
+ function isDispatchable(key, remoteJid) {
107
+ if (key.fromMe === true) return false;
108
+ return remoteJid !== STATUS_BROADCAST_JID;
109
+ }
110
+ function normalizeBaileysMessage(raw) {
111
+ const envelope = asObject(raw);
112
+ const key = envelope === void 0 ? void 0 : asObject(envelope.key);
113
+ if (key === void 0) return void 0;
114
+ const remoteJid = asText(key.remoteJid);
115
+ const wamid = asText(key.id);
116
+ if (remoteJid === void 0 || wamid === void 0) return void 0;
117
+ if (!isDispatchable(key, remoteJid)) return void 0;
118
+ const text = extractText(envelope?.message);
119
+ if (text === void 0) return void 0;
120
+ const parties = resolveParties(key, remoteJid);
121
+ if (parties === void 0) return void 0;
122
+ const seconds = toSeconds(envelope?.messageTimestamp);
123
+ if (seconds === void 0) return void 0;
124
+ const contactName = asText(envelope?.pushName);
125
+ return {
126
+ wamid,
127
+ fromPhone: parties.fromPhone,
128
+ conversationType: parties.isGroup ? "group" : "dm",
129
+ channelId: parties.channelId,
130
+ text,
131
+ receivedAt: seconds * 1e3,
132
+ backend: "baileys",
133
+ raw,
134
+ ...contactName !== void 0 ? { contactName } : {}
135
+ };
136
+ }
137
+ var ConfigurationError = class extends gateway.GatewayConfigurationError {
138
+ name = "ConfigurationError";
139
+ constructor(opts) {
140
+ super("gateway-whatsapp", opts);
153
141
  }
154
- /** Status receipts (sent/delivered/read/failed). Adapter-specific (D307). */
155
- onStatusReceipt(handler) {
156
- this.statusUnsubscribe?.();
157
- this.statusHandler = handler;
158
- this.statusUnsubscribe = this.backendImpl.onStatusReceipt(async (r) => {
159
- await this.statusHandler?.(r);
160
- });
161
- return () => {
162
- this.statusUnsubscribe?.();
163
- this.statusUnsubscribe = void 0;
164
- this.statusHandler = void 0;
165
- };
142
+ };
143
+ var WhatsAppBridgeError = class extends Error {
144
+ name = "WhatsAppBridgeError";
145
+ /** Cause as named by the bridge, when it could name one. */
146
+ code;
147
+ constructor(message, code) {
148
+ super(`WhatsApp web bridge could not start: ${message}`);
149
+ this.code = code;
166
150
  }
167
151
  };
168
-
169
- // src/errors.ts
170
152
  var WhatsAppConnectTimeoutError = class extends Error {
171
153
  constructor(timeoutMs) {
172
154
  super(`WhatsApp web bridge connect timed out after ${timeoutMs}ms (QR code not scanned?)`);
173
155
  this.name = "WhatsAppConnectTimeoutError";
174
156
  }
175
157
  };
158
+ var RATE_LIMIT_CODES = /* @__PURE__ */ new Set([
159
+ 4,
160
+ // the app reached its API call rate limit
161
+ 80007,
162
+ // the WhatsApp Business Account reached its rate limit
163
+ 130429
164
+ // Cloud API message throughput reached
165
+ ]);
166
+ var UNDELIVERABLE_CODES = /* @__PURE__ */ new Set([
167
+ 130403,
168
+ // the business has blocked this user
169
+ 131026
170
+ // no WhatsApp account, terms not accepted, or an outdated client
171
+ ]);
172
+ var SESSION_WINDOW_EXPIRED_CODE = 131047;
173
+ var RECIPIENT_NOT_ALLOWLISTED_CODE = 131030;
176
174
  function cloudErrorCode(status, errCode) {
177
175
  if (errCode === 190 || status === 401) return "auth_failed";
178
- if (errCode === 130 || errCode === 131 || status === 429) return "rate_limit";
176
+ if (RATE_LIMIT_CODES.has(errCode) || status === 429) return "rate_limit";
177
+ if (errCode === SESSION_WINDOW_EXPIRED_CODE) return "session_window_expired";
178
+ if (errCode === RECIPIENT_NOT_ALLOWLISTED_CODE) return "recipient_not_allowlisted";
179
+ if (UNDELIVERABLE_CODES.has(errCode)) return "undeliverable";
179
180
  if (status === 400 || errCode === 100) return "invalid_request";
180
181
  if (status >= 500) return "server_error";
181
182
  return "unknown";
@@ -187,6 +188,18 @@ function mapWhatsAppCloudError(status, body) {
187
188
  const code = cloudErrorCode(status, errCode);
188
189
  if (code === "auth_failed") return { code, message: `Bearer token rejected: ${errMsg}` };
189
190
  if (code === "rate_limit") return { code, message: `Throttled: ${errMsg}` };
191
+ if (code === "recipient_not_allowlisted") {
192
+ return {
193
+ code,
194
+ message: `Recipient is not on this number's allowed list \u2014 register it under the phone number in the app's WhatsApp API setup before sending: ${errMsg}`
195
+ };
196
+ }
197
+ if (code === "session_window_expired") {
198
+ return {
199
+ code,
200
+ message: `Outside the 24-hour service window \u2014 send an approved template instead: ${errMsg}`
201
+ };
202
+ }
190
203
  return { code, message: errMsg };
191
204
  }
192
205
  function mapWhatsAppWebError(ipcError) {
@@ -206,6 +219,398 @@ function mapWhatsAppWebError(ipcError) {
206
219
  return { code: "unknown", message: msg };
207
220
  }
208
221
 
222
+ // src/backend/baileys/socket.ts
223
+ function member(mod, name) {
224
+ const asDefault = mod.default;
225
+ const fromDefault = asDefault !== void 0 && typeof asDefault === "object" ? asDefault[name] : void 0;
226
+ return fromDefault ?? mod[name];
227
+ }
228
+ async function createBaileysSocket(opts) {
229
+ const specifier = opts.specifier ?? "baileys";
230
+ let mod;
231
+ try {
232
+ mod = await import(
233
+ /* @vite-ignore */
234
+ specifier
235
+ );
236
+ } catch (err) {
237
+ throw new ConfigurationError({
238
+ code: "peer_missing",
239
+ message: `gateway-whatsapp: ${specifier} is not installed. Run \`pnpm add baileys\` to use the baileys backend. (${err instanceof Error ? err.message : String(err)})`
240
+ });
241
+ }
242
+ const makeSocket = member(
243
+ mod,
244
+ "makeWASocket"
245
+ );
246
+ const useAuthState = member(mod, "useMultiFileAuthState");
247
+ const fetchVersion = member(
248
+ mod,
249
+ "fetchLatestBaileysVersion"
250
+ );
251
+ for (const [name, value] of [
252
+ ["makeWASocket", makeSocket],
253
+ ["useMultiFileAuthState", useAuthState]
254
+ ]) {
255
+ if (typeof value !== "function") {
256
+ throw new ConfigurationError({
257
+ code: "peer_incompatible",
258
+ message: `gateway-whatsapp: ${specifier} is installed but does not export ${name} as a function. Expected a function, got ${typeof value}. The baileys backend expects the peer range declared in @theokit/gateway-whatsapp.`
259
+ });
260
+ }
261
+ }
262
+ const { state, saveCreds } = await useAuthState(opts.sessionDir);
263
+ const version = typeof fetchVersion === "function" ? (await fetchVersion()).version : void 0;
264
+ const socket = makeSocket({
265
+ auth: state,
266
+ printQRInTerminal: false,
267
+ markOnlineOnConnect: false,
268
+ syncFullHistory: false,
269
+ browser: ["theokit-gateway", "chrome", "1.0.0"],
270
+ ...version !== void 0 ? { version } : {}
271
+ });
272
+ const onQr = opts.onQr ?? ((qr) => {
273
+ process.stderr.write(
274
+ `
275
+ [whatsapp-baileys] Scan this QR with WhatsApp \u2014 Settings, Linked devices, Link a device:
276
+ ${qr}
277
+
278
+ `
279
+ );
280
+ });
281
+ socket.ev.on("connection.update", (update) => {
282
+ if (typeof update.qr === "string" && update.qr.length > 0) onQr(update.qr);
283
+ });
284
+ socket.ev.on("creds.update", () => {
285
+ void saveCreds().catch((err) => {
286
+ const message = err instanceof Error ? err.message : String(err);
287
+ process.stderr.write(`[whatsapp-baileys] could not persist credentials: ${message}
288
+ `);
289
+ });
290
+ });
291
+ return socket;
292
+ }
293
+
294
+ // src/backend/baileys/index.ts
295
+ function endQuietly(socket) {
296
+ try {
297
+ socket.end?.();
298
+ } catch {
299
+ }
300
+ }
301
+ var DEFAULT_CONNECT_TIMEOUT_MS = 6e4;
302
+ var DEFAULT_SEND_TIMEOUT_MS = 3e4;
303
+ var WhatsAppBaileysBackend = class {
304
+ constructor(opts) {
305
+ this.opts = opts;
306
+ }
307
+ opts;
308
+ kind = "baileys";
309
+ socket;
310
+ connected = false;
311
+ /** Guards a concurrent second `connect()` from opening a second live session. */
312
+ connecting;
313
+ /**
314
+ * Which connection attempt is current.
315
+ *
316
+ * Bumped by every `connect()` and every `disconnect()`. A socket from a superseded attempt
317
+ * checks it before touching any state, which is what stops an abandoned socket delivering
318
+ * inbound or flipping `connected` under a live one.
319
+ */
320
+ generation = 0;
321
+ /**
322
+ * How to end a connection attempt that is still awaiting `open`.
323
+ *
324
+ * Retirement by generation makes an attempt's listeners silent, which is not the same as
325
+ * making the attempt finish. One entry per in-flight attempt; `disconnect()` calls them so
326
+ * the attempt settles now instead of at its timeout.
327
+ */
328
+ pendingAttempts = /* @__PURE__ */ new Set();
329
+ /**
330
+ * Why the socket last closed, as Baileys reported it.
331
+ *
332
+ * Kept because `connect()` returning `false` cannot distinguish a network blip from a
333
+ * session the operator unlinked from their phone — and only one of those is worth retrying.
334
+ * `rules/error-handling.md` § 3: fail clear, and log with enough context to act.
335
+ */
336
+ lastCloseError;
337
+ inboundHandler;
338
+ statusHandler;
339
+ /**
340
+ * Serialises outbound sends (ADR D320).
341
+ *
342
+ * Both peer gateways studied do this, and one records that concurrent sends on a single
343
+ * socket can misdeliver to the wrong chat. We have NOT measured that in our own code — we
344
+ * have never run a Baileys socket — so this is precaution rather than a reproduction of our
345
+ * own bug, and saying so is the point. It is kept because the cost is one promise chain and
346
+ * the failure it guards against is a message delivered to the wrong person.
347
+ */
348
+ sendQueue = Promise.resolve();
349
+ /**
350
+ * Open the socket and wait for it to report `open`.
351
+ *
352
+ * Idempotent, and safe against a concurrent second call: the in-flight promise is shared
353
+ * rather than a second socket being built. WhatsApp's own adapter shipped without that
354
+ * guard once and opened two live sessions.
355
+ */
356
+ async connect() {
357
+ if (this.connected) return true;
358
+ if (this.connecting !== void 0) return this.connecting;
359
+ const attempt = this.openSocket();
360
+ this.connecting = attempt;
361
+ try {
362
+ return await attempt;
363
+ } finally {
364
+ if (this.connecting === attempt) this.connecting = void 0;
365
+ }
366
+ }
367
+ /** @internal */
368
+ async openSocket() {
369
+ const generation = ++this.generation;
370
+ const socket = await this.buildSocket();
371
+ const isCurrent = () => this.generation === generation;
372
+ if (!isCurrent()) {
373
+ endQuietly(socket);
374
+ return false;
375
+ }
376
+ this.subscribeInbound(socket, isCurrent);
377
+ const timeoutMs = this.opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
378
+ const openedOk = await this.raceOpen(socket, isCurrent, timeoutMs);
379
+ if (!isCurrent()) {
380
+ endQuietly(socket);
381
+ return false;
382
+ }
383
+ if (!openedOk) {
384
+ this.reportConnectFailure(timeoutMs);
385
+ this.generation += 1;
386
+ endQuietly(socket);
387
+ this.socket = void 0;
388
+ this.connected = false;
389
+ return false;
390
+ }
391
+ if (this.socket !== void 0 && this.socket !== socket) endQuietly(this.socket);
392
+ this.socket = socket;
393
+ this.connected = true;
394
+ return true;
395
+ }
396
+ /** Build a socket through the injected factory, or the real one. @internal */
397
+ async buildSocket() {
398
+ const factory = this.opts.socketFactory ?? createBaileysSocket;
399
+ return factory({
400
+ sessionDir: this.opts.sessionDir,
401
+ ...this.opts.onQr !== void 0 ? { onQr: this.opts.onQr } : {}
402
+ });
403
+ }
404
+ /** Route this socket's inbound batches into the handler, while it is still current. @internal */
405
+ subscribeInbound(socket, isCurrent) {
406
+ socket.ev.on("messages.upsert", (payload) => {
407
+ if (payload.type !== void 0 && payload.type !== "notify") return;
408
+ if (!isCurrent()) return;
409
+ for (const raw of payload.messages ?? []) this.dispatchInbound(raw);
410
+ });
411
+ }
412
+ /**
413
+ * Wait for this socket to report `open`, or for something to end the attempt.
414
+ *
415
+ * Three things can settle it: the socket opens, the socket closes, or the timeout fires — and
416
+ * a fourth, `disconnect()`, reaches it through `pendingAttempts`. That last one is why the
417
+ * resolver is registered rather than merely closed over: retiring an attempt by generation
418
+ * makes its listeners no-ops, INCLUDING the one that would settle this, so without a way in
419
+ * from outside the only thing left able to finish it was the timeout.
420
+ *
421
+ * @internal
422
+ */
423
+ async raceOpen(socket, isCurrent, timeoutMs) {
424
+ let settle = () => void 0;
425
+ const opened = new Promise((resolve2) => {
426
+ settle = resolve2;
427
+ });
428
+ const abandon = () => settle(false);
429
+ this.pendingAttempts.add(abandon);
430
+ socket.ev.on("connection.update", (update) => {
431
+ if (!isCurrent()) return;
432
+ if (update.connection === "open") {
433
+ settle(true);
434
+ return;
435
+ }
436
+ if (update.connection !== "close") return;
437
+ this.lastCloseError = update.lastDisconnect?.error;
438
+ this.connected = false;
439
+ if (this.socket === socket) this.socket = void 0;
440
+ endQuietly(socket);
441
+ settle(false);
442
+ });
443
+ const timer = setTimeout(() => settle(false), timeoutMs);
444
+ try {
445
+ return await opened;
446
+ } finally {
447
+ clearTimeout(timer);
448
+ this.pendingAttempts.delete(abandon);
449
+ }
450
+ }
451
+ /**
452
+ * Say why the connection did not open.
453
+ *
454
+ * A bare `false` tells an operator nothing, and the two causes want opposite responses: a
455
+ * blip is worth retrying, an unlinked device can only be fixed by re-pairing, and a
456
+ * supervisor that cannot tell them apart retries forever against a dead session.
457
+ *
458
+ * @internal
459
+ */
460
+ reportConnectFailure(timeoutMs) {
461
+ const error = this.lastCloseError;
462
+ const cause = error === void 0 ? `no 'open' within ${timeoutMs}ms` : error instanceof Error ? error.message : String(error);
463
+ process.stderr.write(`[whatsapp-baileys] connect failed: ${cause}
464
+ `);
465
+ }
466
+ /** Close the socket. Idempotent, and safe when never connected. */
467
+ async disconnect() {
468
+ this.generation += 1;
469
+ this.connected = false;
470
+ this.connecting = void 0;
471
+ for (const abandon of this.pendingAttempts) abandon();
472
+ this.pendingAttempts.clear();
473
+ const socket = this.socket;
474
+ this.socket = void 0;
475
+ this.inboundHandler = void 0;
476
+ this.statusHandler = void 0;
477
+ if (socket !== void 0) endQuietly(socket);
478
+ }
479
+ /**
480
+ * Send one text message.
481
+ *
482
+ * Queued behind any send already in flight (D320), and raced against a timeout whose
483
+ * expiry reports **undetermined** delivery rather than failure (D321). A local timeout says
484
+ * the acknowledgement did not arrive, not that the message did not — so this never
485
+ * retries, because a retry after a slow ack duplicates the message.
486
+ */
487
+ async send(message) {
488
+ let settled = Promise.resolve();
489
+ const run = this.sendQueue.then(
490
+ () => {
491
+ const attempt = this.sendNow(message);
492
+ settled = attempt.inFlight;
493
+ return attempt.result;
494
+ },
495
+ () => {
496
+ const attempt = this.sendNow(message);
497
+ settled = attempt.inFlight;
498
+ return attempt.result;
499
+ }
500
+ );
501
+ this.sendQueue = run.then(
502
+ () => settled.catch(() => void 0),
503
+ () => settled.catch(() => void 0)
504
+ );
505
+ return run;
506
+ }
507
+ /**
508
+ * Race one send against the send timeout.
509
+ *
510
+ * Separated so `sendNow` reads as the three outcomes it has — delivered, undetermined,
511
+ * refused — rather than as promise plumbing.
512
+ *
513
+ * @internal
514
+ */
515
+ async raceSend(inFlight, timeoutMs) {
516
+ let timer;
517
+ const timeout = new Promise((resolve2) => {
518
+ timer = setTimeout(() => resolve2("timeout"), timeoutMs);
519
+ });
520
+ try {
521
+ return await Promise.race([inFlight, timeout]);
522
+ } finally {
523
+ if (timer !== void 0) clearTimeout(timer);
524
+ }
525
+ }
526
+ /**
527
+ * One send attempt.
528
+ *
529
+ * Returns two promises deliberately. `result` is what the caller is told — it settles on
530
+ * the timeout. `inFlight` settles when the socket is actually free again, which is what the
531
+ * queue must wait for: a timeout does not cancel `sendMessage`, so releasing the queue on
532
+ * the timeout would put two sends on one socket.
533
+ *
534
+ * @internal
535
+ */
536
+ sendNow(message) {
537
+ const socket = this.socket;
538
+ if (!this.connected || socket === void 0) {
539
+ return {
540
+ result: Promise.resolve({
541
+ ok: false,
542
+ error: { code: "not_connected", message: "Baileys backend is not connected." }
543
+ }),
544
+ inFlight: Promise.resolve()
545
+ };
546
+ }
547
+ const jid = `${message.to}@${message.isGroup ? "g.us" : "s.whatsapp.net"}`;
548
+ const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;
549
+ const inFlight = socket.sendMessage(jid, { text: message.text });
550
+ const result = this.raceSend(inFlight, timeoutMs).then((outcome) => {
551
+ if (outcome === "timeout") {
552
+ return {
553
+ ok: false,
554
+ error: {
555
+ code: "timeout",
556
+ message: `No acknowledgement after ${timeoutMs}ms \u2014 delivery is undetermined. Not retried: the message may already have been delivered.`
557
+ }
558
+ };
559
+ }
560
+ const wamid = outcome?.key?.id;
561
+ return wamid !== void 0 ? { ok: true, wamid } : { ok: true };
562
+ }).catch((err) => ({
563
+ ok: false,
564
+ error: {
565
+ code: "server_error",
566
+ message: err instanceof Error ? err.message : String(err)
567
+ }
568
+ }));
569
+ return { result, inFlight };
570
+ }
571
+ /** Subscribe to inbound events. EC-H: a second call REPLACES the first. */
572
+ onInbound(handler) {
573
+ this.inboundHandler = handler;
574
+ return () => {
575
+ if (this.inboundHandler === handler) this.inboundHandler = void 0;
576
+ };
577
+ }
578
+ /**
579
+ * Subscribe to delivery receipts. EC-H: a second call REPLACES the first.
580
+ *
581
+ * Declared for the interface; Baileys reports receipts on `messages.update`, which v1 does
582
+ * not consume. Registering a handler is accepted and it is never called — stated here
583
+ * rather than left for a consumer to discover from silence.
584
+ */
585
+ onStatusReceipt(handler) {
586
+ this.statusHandler = handler;
587
+ return () => {
588
+ if (this.statusHandler === handler) this.statusHandler = void 0;
589
+ };
590
+ }
591
+ /**
592
+ * Normalise one envelope and hand it to the handler.
593
+ *
594
+ * The promise is floated because the Baileys listener is synchronous — but with a `catch`,
595
+ * because a bare `void` on a rejecting promise ends the process under Node's default, which
596
+ * is what killed two adapters in this package (#41). A handler is user code; its failure is
597
+ * named as the handler's and delivery continues.
598
+ *
599
+ * @internal
600
+ */
601
+ dispatchInbound(raw) {
602
+ const handler = this.inboundHandler;
603
+ if (handler === void 0) return;
604
+ const event = normalizeBaileysMessage(raw);
605
+ if (event === void 0) return;
606
+ void handler(event).catch((err) => {
607
+ const message = err instanceof Error ? err.message : String(err);
608
+ process.stderr.write(`[whatsapp-baileys] handler threw: ${message}
609
+ `);
610
+ });
611
+ }
612
+ };
613
+
209
614
  // src/backend/cloud/client.ts
210
615
  var WhatsAppCloudClient = class {
211
616
  constructor(opts) {
@@ -231,6 +636,104 @@ var WhatsAppCloudClient = class {
231
636
  type: "text",
232
637
  text: { body, preview_url: false }
233
638
  };
639
+ return this.postMessage(req);
640
+ }
641
+ /**
642
+ * Send an approved template.
643
+ *
644
+ * The only message type Meta accepts outside the 24-hour service window, and so the only way to
645
+ * reach someone who has not written first — every notification, and every unattended check of
646
+ * whether this integration still works. Free-form text to a cold recipient is refused with
647
+ * `131047`, which the error mapper now surfaces as `session_window_expired`.
648
+ *
649
+ * `components` is omitted from the payload when absent rather than sent empty: Meta rejects
650
+ * `components: []` on a template that declares no variables, so the two are not equivalent.
651
+ *
652
+ * Deliberately NOT on the `WhatsAppBackend` interface. The web backend drives WhatsApp Web,
653
+ * which has no concept of templates, and widening the shared contract would hand it a method it
654
+ * can only throw from.
655
+ */
656
+ async sendTemplate(to, templateName, languageCode, components) {
657
+ const req = {
658
+ messaging_product: "whatsapp",
659
+ recipient_type: "individual",
660
+ to,
661
+ type: "template",
662
+ template: {
663
+ name: templateName,
664
+ language: { code: languageCode },
665
+ ...components !== void 0 && components.length > 0 ? { components } : {}
666
+ }
667
+ };
668
+ return this.postMessage(req);
669
+ }
670
+ /**
671
+ * Ask Meta whether this credential can actually act as this phone number.
672
+ *
673
+ * `connect()` used to answer that question with `return true`, so a wrong, expired or revoked
674
+ * token reported success at startup and surfaced as messages that silently never arrived —
675
+ * the worst failure mode a gateway has, because there is nothing in a log to see. The first
676
+ * live run of the WhatsApp suite caught it (#58); 209 unit tests could not, because a fake
677
+ * backend always accepts.
678
+ *
679
+ * It reads the phone number itself rather than `/me`, and that choice is the point: a token
680
+ * can be perfectly valid and still have no access to THIS phone number id, which is the
681
+ * likelier misconfiguration of the two. Checking only the token would wave it through.
682
+ *
683
+ * Returns a result rather than a boolean, and never throws — `connect()` is specified to
684
+ * return false rather than throw, and the reason has to survive the trip: `auth_failed` and
685
+ * `rate_limit` ask a supervisor for opposite responses.
686
+ */
687
+ async verifyCredentials() {
688
+ let response;
689
+ try {
690
+ response = await this.fetchImpl(this.baseUrl, {
691
+ method: "GET",
692
+ headers: { authorization: `Bearer ${this.opts.accessToken}` }
693
+ });
694
+ } catch (cause) {
695
+ return {
696
+ ok: false,
697
+ error: {
698
+ code: "server_error",
699
+ message: `Network error: ${cause instanceof Error ? cause.message : String(cause)}`
700
+ }
701
+ };
702
+ }
703
+ const body = await response.json().catch(() => void 0);
704
+ if (!response.ok) {
705
+ return { ok: false, error: mapWhatsAppCloudError(response.status, body ?? {}) };
706
+ }
707
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
708
+ return {
709
+ ok: false,
710
+ error: {
711
+ code: "unknown",
712
+ message: `Meta answered ${response.status} with a body this client could not read.`
713
+ }
714
+ };
715
+ }
716
+ if (body.error !== void 0) {
717
+ return { ok: false, error: mapWhatsAppCloudError(response.status, body) };
718
+ }
719
+ if (String(body.id) !== this.opts.phoneNumberId) {
720
+ return {
721
+ ok: false,
722
+ error: {
723
+ code: "invalid_request",
724
+ message: `Credential is valid but resolves to node ${String(body.id)}, not the configured phoneNumberId ${this.opts.phoneNumberId}. A WhatsApp Business Account id in place of a phone number id looks exactly like this.`
725
+ }
726
+ };
727
+ }
728
+ return { ok: true };
729
+ }
730
+ /**
731
+ * POST one message envelope and turn Meta's answer into a `WhatsAppSendResult`.
732
+ *
733
+ * Shared by every send: how to reach the endpoint, how to authenticate, and how to read the
734
+ * reply is one piece of knowledge, and it was about to have a second copy.
735
+ */
736
+ async postMessage(req) {
234
737
  let response;
235
738
  try {
236
739
  response = await this.fetchImpl(`${this.baseUrl}/messages`, {
@@ -382,6 +885,28 @@ function metaStatusToReceipt(s) {
382
885
  var WhatsAppCloudBackend = class {
383
886
  kind = "cloud";
384
887
  client;
888
+ /** Verified once by `connect()`; cleared by `disconnect()`. */
889
+ connected = false;
890
+ /**
891
+ * The verification currently in flight, shared by every caller that arrives during it.
892
+ *
893
+ * A flag alone only guards callers that arrive AFTER one finished — two simultaneous
894
+ * `connect()` calls would each ask Meta, which is one wasted round-trip at startup and a
895
+ * rate-limit source under a supervisor that health-checks on a schedule. Cleared when it
896
+ * settles, so a failed attempt does not become a permanent refusal: a transient blip must stay
897
+ * distinguishable from a revoked token.
898
+ */
899
+ connecting;
900
+ /**
901
+ * Which connection attempt is current.
902
+ *
903
+ * Bumped by every `connect()` and every `disconnect()`. Without it a verify that was still in
904
+ * flight when `disconnect()` ran would set `connected` back to true as it resolved, and every
905
+ * later `connect()` would short-circuit on a flag no live check stands behind — the field's own
906
+ * comment claims `disconnect()` clears it, and it did not. Same guard the Baileys backend
907
+ * carries, for the same reason.
908
+ */
909
+ generation = 0;
385
910
  appSecret;
386
911
  inboundHandler;
387
912
  statusHandler;
@@ -395,26 +920,103 @@ var WhatsAppCloudBackend = class {
395
920
  this.appSecret = opts.appSecret;
396
921
  }
397
922
  // Cloud has no persistent connection — webhook is push, send is HTTP.
923
+ /**
924
+ * Confirm with Meta that this credential can act as this phone number.
925
+ *
926
+ * This used to be `return true`. A consumer with a wrong, expired or revoked token got success
927
+ * at startup and found out from messages that silently never arrived — no error, no log,
928
+ * nothing to alert on, which is the worst failure mode a gateway has. The first live run of the
929
+ * WhatsApp suite caught it (#58); no unit test could, because a fake backend always accepts.
930
+ *
931
+ * Idempotent, like every sibling: verified once, then cached. Re-asking on every call would
932
+ * turn a supervisor's health check into a rate-limit source against Meta.
933
+ *
934
+ * Returns false rather than throwing — the contract each sibling adapter is tested against,
935
+ * because a throw at startup takes the whole runner down with it. The reason goes to stderr
936
+ * first: told only "false", a supervisor cannot tell a revoked token, which needs a human,
937
+ * from a rate limit, which needs a wait.
938
+ */
398
939
  async connect() {
940
+ if (this.connected) return true;
941
+ if (this.connecting !== void 0) return this.connecting;
942
+ const attempt = this.verifyOnce(++this.generation);
943
+ this.connecting = attempt;
944
+ try {
945
+ return await attempt;
946
+ } finally {
947
+ if (this.connecting === attempt) this.connecting = void 0;
948
+ }
949
+ }
950
+ /** One credential check, mapped to the boolean `connect()` is contracted to return. @internal */
951
+ async verifyOnce(generation) {
952
+ const check = await this.client.verifyCredentials();
953
+ if (!check.ok) {
954
+ process.stderr.write(
955
+ `[whatsapp-cloud] connect failed: ${check.error?.code ?? "unknown"} \u2014 ${check.error?.message ?? "no reason given"}
956
+ `
957
+ );
958
+ return false;
959
+ }
960
+ if (this.generation !== generation) return false;
961
+ this.connected = true;
399
962
  return true;
400
963
  }
401
964
  async disconnect() {
965
+ this.generation += 1;
966
+ this.connected = false;
967
+ this.connecting = void 0;
402
968
  this.inboundHandler = void 0;
403
969
  this.statusHandler = void 0;
404
970
  }
405
971
  async send(message) {
972
+ if (!this.connected) {
973
+ return {
974
+ ok: false,
975
+ error: {
976
+ code: "not_connected",
977
+ message: "Cloud backend is not connected \u2014 call connect()."
978
+ }
979
+ };
980
+ }
406
981
  return this.client.sendText(message.to, message.text, message.isGroup);
407
982
  }
983
+ /**
984
+ * Send an approved template to `to`.
985
+ *
986
+ * Cloud-only, and deliberately absent from the `WhatsAppBackend` interface: WhatsApp Web has no
987
+ * concept of templates, so putting this on the shared contract would hand the web backend a
988
+ * method it could only throw from. A consumer reaches it by holding the backend directly.
989
+ *
990
+ * This is the only way to message someone outside the 24-hour service window — every
991
+ * notification, and every unattended check that this integration still works. Free-form text to
992
+ * a cold recipient comes back as `session_window_expired`.
993
+ *
994
+ * @param templateName Name of a template already approved on the WhatsApp Business account.
995
+ * @param languageCode Locale of the approved template, e.g. `en_US`, `pt_BR`.
996
+ * @param components Values for the template's variables; omit for a template that takes none.
997
+ */
998
+ async sendTemplate(to, templateName, languageCode, components) {
999
+ if (!this.connected) {
1000
+ return {
1001
+ ok: false,
1002
+ error: {
1003
+ code: "not_connected",
1004
+ message: "Cloud backend is not connected \u2014 call connect()."
1005
+ }
1006
+ };
1007
+ }
1008
+ return this.client.sendTemplate(to, templateName, languageCode, components);
1009
+ }
408
1010
  onInbound(handler) {
409
1011
  this.inboundHandler = handler;
410
1012
  return () => {
411
- this.inboundHandler = void 0;
1013
+ if (this.inboundHandler === handler) this.inboundHandler = void 0;
412
1014
  };
413
1015
  }
414
1016
  onStatusReceipt(handler) {
415
1017
  this.statusHandler = handler;
416
1018
  return () => {
417
- this.statusHandler = void 0;
1019
+ if (this.statusHandler === handler) this.statusHandler = void 0;
418
1020
  };
419
1021
  }
420
1022
  /**
@@ -428,25 +1030,52 @@ var WhatsAppCloudBackend = class {
428
1030
  if (!verifyWebhookSignature(rawBody, signatureHeader, this.appSecret)) {
429
1031
  return false;
430
1032
  }
431
- const json = JSON.parse(
432
- typeof rawBody === "string" ? rawBody : rawBody.toString("utf8")
433
- );
1033
+ const json = this.parseBody(rawBody);
1034
+ if (json === void 0) return false;
434
1035
  const envelope = parseWebhookPayload(json);
435
1036
  if (envelope === null) return true;
436
- const inbounds = normalizeInboundMessages(envelope);
437
- for (const event of inbounds) {
438
- if (this.inboundHandler !== void 0) {
439
- await this.inboundHandler(event);
440
- }
1037
+ for (const event of normalizeInboundMessages(envelope)) {
1038
+ if (this.inboundHandler === void 0) continue;
1039
+ await this.dispatchContained(() => this.inboundHandler?.(event), "handler");
441
1040
  }
442
- const statuses = normalizeStatusReceipts(envelope);
443
- for (const receipt of statuses) {
444
- if (this.statusHandler !== void 0) {
445
- await this.statusHandler(receipt);
446
- }
1041
+ for (const receipt of normalizeStatusReceipts(envelope)) {
1042
+ if (this.statusHandler === void 0) continue;
1043
+ await this.dispatchContained(() => this.statusHandler?.(receipt), "status handler");
447
1044
  }
448
1045
  return true;
449
1046
  }
1047
+ /**
1048
+ * Parse a signed webhook body, or report `undefined` when it is not JSON.
1049
+ *
1050
+ * The method's contract is true/false; the route calling it has no reason to expect a throw.
1051
+ */
1052
+ parseBody(rawBody) {
1053
+ try {
1054
+ return JSON.parse(typeof rawBody === "string" ? rawBody : rawBody.toString("utf8"));
1055
+ } catch (err) {
1056
+ const m = err instanceof Error ? err.message : String(err);
1057
+ process.stderr.write(`[whatsapp-cloud] webhook body is not JSON: ${m}
1058
+ `);
1059
+ return void 0;
1060
+ }
1061
+ }
1062
+ /**
1063
+ * Run one user callback and contain its failure.
1064
+ *
1065
+ * Meta batches several messages, and their delivery receipts, into a single webhook. Awaiting a
1066
+ * handler with nothing around it made one throw skip every remaining message in the payload —
1067
+ * and reject `handleWebhookPayload`, so the caller's route answered 500 and Meta redelivered the
1068
+ * whole batch, replaying the messages that HAD succeeded (#41).
1069
+ */
1070
+ async dispatchContained(run, what) {
1071
+ try {
1072
+ await run();
1073
+ } catch (err) {
1074
+ const m = err instanceof Error ? err.message : String(err);
1075
+ process.stderr.write(`[whatsapp-cloud] ${what} threw: ${m}
1076
+ `);
1077
+ }
1078
+ }
450
1079
  };
451
1080
 
452
1081
  // src/backend/web/ipc.ts
@@ -485,10 +1114,10 @@ var LineBuffer = class {
485
1114
  };
486
1115
  var BRIDGE_PROCESS_TAG = "whatsapp-web-bridge";
487
1116
  function pidFilePath(theokitHome, sessionId) {
488
- return path__namespace.join(theokitHome, `whatsapp-bridge-${sessionId}.pid`);
1117
+ return path2__namespace.join(theokitHome, `whatsapp-bridge-${sessionId}.pid`);
489
1118
  }
490
1119
  function defaultTheokitHome() {
491
- return process.env.THEOKIT_HOME ?? path__namespace.join(process.env.HOME ?? "/tmp", ".theokit");
1120
+ return process.env.THEOKIT_HOME ?? path2__namespace.join(process.env.HOME ?? "/tmp", ".theokit");
492
1121
  }
493
1122
  function pidBelongsToOurBridge(pid) {
494
1123
  try {
@@ -591,8 +1220,8 @@ function waitForExit(child, timeoutMs) {
591
1220
  }
592
1221
 
593
1222
  // src/backend/web/index.ts
594
- var DEFAULT_CONNECT_TIMEOUT_MS = 12e4;
595
- var DEFAULT_SEND_TIMEOUT_MS = 3e4;
1223
+ var DEFAULT_CONNECT_TIMEOUT_MS2 = 12e4;
1224
+ var DEFAULT_SEND_TIMEOUT_MS2 = 3e4;
596
1225
  var WhatsAppWebBackend = class {
597
1226
  constructor(opts) {
598
1227
  this.opts = opts;
@@ -604,6 +1233,8 @@ var WhatsAppWebBackend = class {
604
1233
  inboundHandler;
605
1234
  statusHandler;
606
1235
  pending = /* @__PURE__ */ new Map();
1236
+ /** Rejects an in-flight `connect()` when the bridge reports it cannot start. */
1237
+ connectRejectors = [];
607
1238
  msgIdCounter = 0;
608
1239
  botPhone;
609
1240
  connected = false;
@@ -636,22 +1267,27 @@ var WhatsAppWebBackend = class {
636
1267
  if (this.connected) return true;
637
1268
  this.handle = this.spawnBridgeHandle();
638
1269
  this.wireStdout();
639
- const timeoutMs = this.opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
640
- const ready = new Promise((resolve2) => this.readyResolvers.push(resolve2));
1270
+ const timeoutMs = this.opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS2;
1271
+ const ready = new Promise((resolve2, reject) => {
1272
+ this.readyResolvers.push(resolve2);
1273
+ this.connectRejectors.push(reject);
1274
+ });
641
1275
  let timer;
642
1276
  const timeout = new Promise((_resolve, reject) => {
643
1277
  timer = setTimeout(() => reject(new WhatsAppConnectTimeoutError(timeoutMs)), timeoutMs);
644
1278
  });
645
1279
  try {
646
1280
  const phone = await Promise.race([ready, timeout]);
647
- if (timer !== void 0) clearTimeout(timer);
648
1281
  this.botPhone = phone;
649
1282
  this.connected = true;
650
1283
  return true;
651
1284
  } catch (err) {
652
- if (timer !== void 0) clearTimeout(timer);
653
1285
  await this.cleanupHandle();
654
1286
  throw err;
1287
+ } finally {
1288
+ if (timer !== void 0) clearTimeout(timer);
1289
+ this.readyResolvers = [];
1290
+ this.connectRejectors = [];
655
1291
  }
656
1292
  }
657
1293
  async disconnect() {
@@ -671,13 +1307,14 @@ var WhatsAppWebBackend = class {
671
1307
  }
672
1308
  this.pending.clear();
673
1309
  this.readyResolvers = [];
1310
+ this.connectRejectors = [];
674
1311
  }
675
1312
  async send(message) {
676
1313
  if (!this.connected || this.handle === void 0 || this.handle.child.stdin === null) {
677
- return { ok: false, error: { code: "server_error", message: "Bridge not connected." } };
1314
+ return { ok: false, error: { code: "not_connected", message: "Bridge not connected." } };
678
1315
  }
679
1316
  const msgId = `out-${++this.msgIdCounter}`;
680
- const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;
1317
+ const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS2;
681
1318
  return new Promise((resolve2) => {
682
1319
  const timer = setTimeout(() => {
683
1320
  this.pending.delete(msgId);
@@ -704,13 +1341,13 @@ var WhatsAppWebBackend = class {
704
1341
  onInbound(handler) {
705
1342
  this.inboundHandler = handler;
706
1343
  return () => {
707
- this.inboundHandler = void 0;
1344
+ if (this.inboundHandler === handler) this.inboundHandler = void 0;
708
1345
  };
709
1346
  }
710
1347
  onStatusReceipt(handler) {
711
1348
  this.statusHandler = handler;
712
1349
  return () => {
713
- this.statusHandler = void 0;
1350
+ if (this.statusHandler === handler) this.statusHandler = void 0;
714
1351
  };
715
1352
  }
716
1353
  handleReady(event) {
@@ -730,7 +1367,27 @@ var WhatsAppWebBackend = class {
730
1367
  backend: "web",
731
1368
  raw: event
732
1369
  };
733
- void this.inboundHandler(normalized);
1370
+ void this.inboundHandler(normalized).catch((err) => {
1371
+ const m = err instanceof Error ? err.message : String(err);
1372
+ process.stderr.write(`[whatsapp-web] handler threw: ${m}
1373
+ `);
1374
+ });
1375
+ }
1376
+ /**
1377
+ * A bridge that reported a failure has failed — say so now, not in two minutes.
1378
+ *
1379
+ * This used to write the message to stderr and return. `connect()` races only the `ready`
1380
+ * promise against the timeout, so a bridge that told us exactly what was wrong and exited
1381
+ * still cost the caller the full `connectTimeoutMs` and surfaced as a timeout — the one
1382
+ * error that carries no information. The diagnosis was printed where nothing could act on
1383
+ * it, which is the swallowing `rules/error-handling.md` § 5 names.
1384
+ */
1385
+ handleBridgeError(event) {
1386
+ process.stderr.write(`[whatsapp-web bridge] ${event.message}
1387
+ `);
1388
+ const failure = new WhatsAppBridgeError(event.message, event.code);
1389
+ for (const reject of this.connectRejectors) reject(failure);
1390
+ this.connectRejectors = [];
734
1391
  }
735
1392
  handleSendAck(event) {
736
1393
  const pending = this.pending.get(event.msgId);
@@ -750,6 +1407,10 @@ var WhatsAppWebBackend = class {
750
1407
  status: event.status,
751
1408
  recipient: event.recipient,
752
1409
  timestamp: event.timestamp || Date.now()
1410
+ }).catch((err) => {
1411
+ const m = err instanceof Error ? err.message : String(err);
1412
+ process.stderr.write(`[whatsapp-web] status handler threw: ${m}
1413
+ `);
753
1414
  });
754
1415
  }
755
1416
  dispatch(event) {
@@ -767,24 +1428,325 @@ var WhatsAppWebBackend = class {
767
1428
  this.handleStatus(event);
768
1429
  return;
769
1430
  case "error":
770
- process.stderr.write(`[whatsapp-web bridge] ${event.message}
771
- `);
1431
+ this.handleBridgeError(event);
772
1432
  return;
773
1433
  }
774
1434
  }
775
1435
  };
776
1436
  function defaultBridgeScriptPath() {
777
- return path__namespace.resolve(
778
- path__namespace.dirname(new URL((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))).pathname),
779
- "../../bridge/whatsapp-web-bridge.mjs"
780
- );
1437
+ const here = path2__namespace.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));
1438
+ const candidates = [
1439
+ // Bundled: dist/index.js beside dist/bridge/
1440
+ path2__namespace.resolve(here, "bridge/whatsapp-web-bridge.mjs"),
1441
+ // Source: src/backend/web/index.ts up two to src/
1442
+ path2__namespace.resolve(here, "../../bridge/whatsapp-web-bridge.mjs")
1443
+ ];
1444
+ const found = candidates.find((candidate) => fs.existsSync(candidate));
1445
+ if (found === void 0) {
1446
+ throw new WhatsAppBridgeError(
1447
+ `bridge script not found. Looked in: ${candidates.join(", ")}. Pass \`bridgeScriptPath\` explicitly if the package layout differs.`,
1448
+ "bridge_script_missing"
1449
+ );
1450
+ }
1451
+ return found;
1452
+ }
1453
+ var WHATSAPP_MAX_TEXT = 4096;
1454
+ function splitForWhatsApp(text) {
1455
+ return gateway.chunkText(text, {
1456
+ limit: WHATSAPP_MAX_TEXT,
1457
+ boundaries: ["\n\n", "\n", " "],
1458
+ lastResort: "last-boundary",
1459
+ surrogateGuard: true,
1460
+ stripLeading: /^\s+/,
1461
+ trimParts: true
1462
+ });
781
1463
  }
782
1464
 
1465
+ // src/adapter.ts
1466
+ function requireNonEmpty(entries) {
1467
+ for (const [name, value] of entries) {
1468
+ if (value === void 0 || value.trim().length === 0) {
1469
+ throw new ConfigurationError({
1470
+ code: "missing_option",
1471
+ message: `gateway-whatsapp: ${name} is required and must not be empty.`
1472
+ });
1473
+ }
1474
+ }
1475
+ }
1476
+ function digitsOnly(s) {
1477
+ return s.replace(/[^\d]/g, "");
1478
+ }
1479
+ var PHONE_RUN = /[\d][\d+\-().  ]*[\d]|[\d]/g;
1480
+ function phoneRuns(s) {
1481
+ return (s.match(PHONE_RUN) ?? []).map(digitsOnly).filter((d) => d.length > 0);
1482
+ }
1483
+ var WhatsAppAdapter = class _WhatsAppAdapter extends gateway.BasePlatformAdapter {
1484
+ platform = "whatsapp";
1485
+ backendImpl;
1486
+ requireMention;
1487
+ botPhoneId;
1488
+ /** `undefined` = no allowlist configured; a set = configured, and enforced fail-closed. */
1489
+ allowedSenders;
1490
+ /** Mirrors the sibling adapters: guards connect() against opening a second session. */
1491
+ connected = false;
1492
+ handler;
1493
+ statusHandler;
1494
+ // EC-H: track unsubscribe handles so onInbound REPLACES instead of stacks.
1495
+ inboundUnsubscribe;
1496
+ statusUnsubscribe;
1497
+ /**
1498
+ * Build an adapter from a discriminated configuration.
1499
+ *
1500
+ * The entry point for configuration that arrives as **data** — read from a file, an
1501
+ * environment, or a tenant record — where the backend is a string rather than a decision
1502
+ * made in code. `fromCloud` / `fromWeb` are the direct forms when the choice is already
1503
+ * known at the call site.
1504
+ *
1505
+ * This is what `WhatsAppAdapterOptions` exists for. Until it had this consumer the union
1506
+ * was exported, documented and inert, which is the defect #47 was filed about, and the
1507
+ * first attempt at closing that issue left it inert — the factories took the config halves
1508
+ * directly and never the union.
1509
+ *
1510
+ * @throws {ConfigurationError} when a required option is missing or empty.
1511
+ * @public
1512
+ */
1513
+ static from(options, common = {}) {
1514
+ switch (options.backend) {
1515
+ case "cloud":
1516
+ return _WhatsAppAdapter.fromCloud(options.cloud, common);
1517
+ case "web":
1518
+ return _WhatsAppAdapter.fromWeb(options.web, common);
1519
+ case "baileys":
1520
+ return _WhatsAppAdapter.fromBaileys(options.baileys, common);
1521
+ }
1522
+ }
1523
+ /**
1524
+ * Build a Baileys adapter.
1525
+ *
1526
+ * Unofficial, and no amount of code changes that: it automates a WhatsApp Web session,
1527
+ * which Meta's terms do not sanction and which can get a number banned. Use a number
1528
+ * created for this, never a personal one. Prefer {@link WhatsAppAdapter.fromCloud} unless
1529
+ * the number has no Cloud API access.
1530
+ *
1531
+ * Unlike {@link WhatsAppAdapter.fromWeb} it embeds no browser — it speaks the multi-device
1532
+ * protocol over a WebSocket. `baileys` is an optional peer dependency; it is loaded lazily
1533
+ * at connect, so a consumer who never calls this never needs it installed.
1534
+ *
1535
+ * `botPhoneId` has nothing to default from here, so leaving it unset while `requireMention`
1536
+ * is on (its default) drops every group message. The adapter logs when it does.
1537
+ *
1538
+ * @throws {ConfigurationError} when `sessionDir` is missing or empty.
1539
+ * @public
1540
+ */
1541
+ static fromBaileys(baileys, opts = {}) {
1542
+ requireNonEmpty([["sessionDir", baileys.sessionDir]]);
1543
+ return new _WhatsAppAdapter(
1544
+ new WhatsAppBaileysBackend({
1545
+ sessionDir: baileys.sessionDir,
1546
+ ...baileys.connectTimeoutMs !== void 0 ? { connectTimeoutMs: baileys.connectTimeoutMs } : {},
1547
+ ...baileys.sendTimeoutMs !== void 0 ? { sendTimeoutMs: baileys.sendTimeoutMs } : {},
1548
+ ...baileys.onQr !== void 0 ? { onQr: baileys.onQr } : {}
1549
+ }),
1550
+ opts
1551
+ );
1552
+ }
1553
+ /**
1554
+ * Build a Cloud-API adapter.
1555
+ *
1556
+ * The construction path this package's docblock has named since it was written, and which
1557
+ * did not exist until #47 — a consumer following the only guidance the package gave wrote
1558
+ * code that would not compile.
1559
+ *
1560
+ * Prefer it over the constructor: it keeps `WhatsAppCloudBackend` an implementation detail
1561
+ * of this package rather than something every consumer imports and assembles.
1562
+ *
1563
+ * @throws {ConfigurationError} when a required credential is missing or empty.
1564
+ * @public
1565
+ */
1566
+ static fromCloud(cloud, opts = {}) {
1567
+ requireNonEmpty([
1568
+ ["accessToken", cloud.accessToken],
1569
+ ["phoneNumberId", cloud.phoneNumberId]
1570
+ ]);
1571
+ if (cloud.apiVersion !== void 0) {
1572
+ requireNonEmpty([["apiVersion", cloud.apiVersion]]);
1573
+ }
1574
+ return new _WhatsAppAdapter(
1575
+ new WhatsAppCloudBackend({
1576
+ accessToken: cloud.accessToken,
1577
+ phoneNumberId: cloud.phoneNumberId,
1578
+ appSecret: cloud.appSecret,
1579
+ ...cloud.apiVersion !== void 0 ? { apiVersion: cloud.apiVersion } : {}
1580
+ }),
1581
+ { ...opts, botPhoneId: opts.botPhoneId ?? cloud.phoneNumberId }
1582
+ );
1583
+ }
1584
+ /**
1585
+ * Build a WhatsApp-Web adapter.
1586
+ *
1587
+ * Unofficial: it drives a real WhatsApp Web session through a browser, which Meta's terms
1588
+ * do not sanction and which can get a number banned. It also needs a browser this package
1589
+ * does not install. Prefer {@link WhatsAppAdapter.fromCloud} unless the number has no
1590
+ * Cloud API access.
1591
+ *
1592
+ * @throws {ConfigurationError} when `sessionId` is missing or empty.
1593
+ * @public
1594
+ */
1595
+ static fromWeb(web, opts = {}) {
1596
+ requireNonEmpty([["sessionId", web.sessionId]]);
1597
+ return new _WhatsAppAdapter(
1598
+ new WhatsAppWebBackend({
1599
+ sessionId: web.sessionId,
1600
+ ...web.bridgeScriptPath !== void 0 ? { bridgeScriptPath: web.bridgeScriptPath } : {}
1601
+ }),
1602
+ opts
1603
+ );
1604
+ }
1605
+ /** Construct from a pre-built backend. Prefer the factories; this is for tests and for a custom backend. */
1606
+ constructor(backendImpl, opts = {}) {
1607
+ super();
1608
+ this.backendImpl = backendImpl;
1609
+ this.requireMention = opts.requireMention ?? true;
1610
+ this.botPhoneId = digitsOnly(opts.botPhoneId ?? "");
1611
+ this.allowedSenders = opts.allowedSenders === void 0 ? void 0 : parseAllowedSenders(opts.allowedSenders);
1612
+ }
1613
+ /** Escape hatch (D180-style) for advanced features. */
1614
+ getBackend() {
1615
+ return this.backendImpl;
1616
+ }
1617
+ async connect() {
1618
+ if (this.connected) return true;
1619
+ const ok = await this.backendImpl.connect();
1620
+ this.connected = ok;
1621
+ return ok;
1622
+ }
1623
+ async disconnect() {
1624
+ this.connected = false;
1625
+ this.inboundUnsubscribe?.();
1626
+ this.inboundUnsubscribe = void 0;
1627
+ this.statusUnsubscribe?.();
1628
+ this.statusUnsubscribe = void 0;
1629
+ this.handler = void 0;
1630
+ this.statusHandler = void 0;
1631
+ await this.backendImpl.disconnect();
1632
+ }
1633
+ async sendMessage(out) {
1634
+ if (out.text.length === 0) {
1635
+ return { ok: false, error: { code: "empty_text", message: "Empty text rejected." } };
1636
+ }
1637
+ const parts = splitForWhatsApp(out.text);
1638
+ if (parts.length === 0) {
1639
+ return {
1640
+ ok: false,
1641
+ error: { code: "empty_text", message: "Text reduced to zero parts after splitting." }
1642
+ };
1643
+ }
1644
+ let lastWamid;
1645
+ const isGroup = out.channel.type === "group";
1646
+ for (const part of parts) {
1647
+ const r = await this.backendImpl.send({ to: out.channel.id, isGroup, text: part });
1648
+ if (!r.ok) {
1649
+ return {
1650
+ ok: false,
1651
+ error: { code: r.error?.code ?? "unknown", message: r.error?.message ?? "Send failed." }
1652
+ };
1653
+ }
1654
+ lastWamid = r.wamid;
1655
+ }
1656
+ return lastWamid !== void 0 ? { ok: true, messageId: lastWamid } : { ok: true };
1657
+ }
1658
+ /**
1659
+ * Is this sender refused by a configured allowlist?
1660
+ *
1661
+ * Runs before the group/mention filter because it answers a different question: that one asks
1662
+ * whether a message was meant for us, this one asks whether the sender may reach us at all.
1663
+ *
1664
+ * The refusal is logged. A silent drop is indistinguishable from a broken gateway, and the
1665
+ * first thing a mistyped allowlist causes is an operator wondering why the bot went mute.
1666
+ */
1667
+ isRefusedBySenderAllowlist(inbound) {
1668
+ if (this.allowedSenders === void 0) return false;
1669
+ if (isSenderAllowed(inbound.fromPhone, this.allowedSenders)) return false;
1670
+ process.stderr.write(
1671
+ `[whatsapp] dropped inbound from "${inbound.fromPhone}" \u2014 not in the configured allowlist
1672
+ `
1673
+ );
1674
+ return true;
1675
+ }
1676
+ /** D309 + EC-7: group filter with digit-only normalization. */
1677
+ shouldDropGroupMessage(inbound) {
1678
+ if (inbound.conversationType !== "group" || !this.requireMention) return false;
1679
+ if (this.botPhoneId.length === 0) {
1680
+ process.stderr.write(
1681
+ "[whatsapp] dropping every group message: requireMention is on and botPhoneId is unset\n"
1682
+ );
1683
+ return true;
1684
+ }
1685
+ return !phoneRuns(inbound.text).some((run) => run.includes(this.botPhoneId));
1686
+ }
1687
+ toMessageEvent(inbound) {
1688
+ return {
1689
+ id: inbound.wamid,
1690
+ platform: "whatsapp",
1691
+ sender: { id: inbound.fromPhone, displayName: inbound.contactName },
1692
+ channel: { id: inbound.channelId, type: inbound.conversationType },
1693
+ text: inbound.text,
1694
+ receivedAt: inbound.receivedAt,
1695
+ whatsapp: {
1696
+ wamid: inbound.wamid,
1697
+ phoneNumberId: inbound.phoneNumberId,
1698
+ contactName: inbound.contactName,
1699
+ backend: inbound.backend,
1700
+ raw: inbound.raw
1701
+ }
1702
+ };
1703
+ }
1704
+ onInbound(handler) {
1705
+ this.inboundUnsubscribe?.();
1706
+ this.handler = handler;
1707
+ const off = this.backendImpl.onInbound(async (inbound) => {
1708
+ if (!this.handler) return;
1709
+ if (this.isRefusedBySenderAllowlist(inbound)) return;
1710
+ if (this.shouldDropGroupMessage(inbound)) return;
1711
+ await this.handler(this.toMessageEvent(inbound));
1712
+ });
1713
+ this.inboundUnsubscribe = off;
1714
+ return () => {
1715
+ if (this.handler === handler) {
1716
+ this.handler = void 0;
1717
+ off();
1718
+ this.inboundUnsubscribe = void 0;
1719
+ }
1720
+ };
1721
+ }
1722
+ /** Status receipts (sent/delivered/read/failed). Adapter-specific (D307). */
1723
+ onStatusReceipt(handler) {
1724
+ this.statusUnsubscribe?.();
1725
+ this.statusHandler = handler;
1726
+ const off = this.backendImpl.onStatusReceipt(async (r) => {
1727
+ await this.statusHandler?.(r);
1728
+ });
1729
+ this.statusUnsubscribe = off;
1730
+ return () => {
1731
+ if (this.statusHandler === handler) {
1732
+ this.statusHandler = void 0;
1733
+ off();
1734
+ this.statusUnsubscribe = void 0;
1735
+ }
1736
+ };
1737
+ }
1738
+ };
1739
+
1740
+ exports.ConfigurationError = ConfigurationError;
783
1741
  exports.LineBuffer = LineBuffer;
784
1742
  exports.WhatsAppAdapter = WhatsAppAdapter;
1743
+ exports.WhatsAppBaileysBackend = WhatsAppBaileysBackend;
1744
+ exports.WhatsAppBridgeError = WhatsAppBridgeError;
785
1745
  exports.WhatsAppCloudBackend = WhatsAppCloudBackend;
786
1746
  exports.WhatsAppConnectTimeoutError = WhatsAppConnectTimeoutError;
787
1747
  exports.WhatsAppWebBackend = WhatsAppWebBackend;
1748
+ exports.createBaileysSocket = createBaileysSocket;
1749
+ exports.defaultBridgeScriptPath = defaultBridgeScriptPath;
788
1750
  exports.digitsOnly = digitsOnly;
789
1751
  exports.formatCommand = formatCommand;
790
1752
  exports.mapWhatsAppCloudError = mapWhatsAppCloudError;