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