@theokit/gateway-whatsapp 0.1.2 → 0.2.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,154 @@ 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();
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;
91
81
  }
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 };
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;
116
89
  }
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));
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;
122
94
  }
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
- };
139
- }
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;
176
173
  function cloudErrorCode(status, errCode) {
177
174
  if (errCode === 190 || status === 401) return "auth_failed";
178
- if (errCode === 130 || errCode === 131 || status === 429) return "rate_limit";
175
+ if (RATE_LIMIT_CODES.has(errCode) || status === 429) return "rate_limit";
176
+ if (errCode === SESSION_WINDOW_EXPIRED_CODE) return "session_window_expired";
177
+ if (UNDELIVERABLE_CODES.has(errCode)) return "undeliverable";
179
178
  if (status === 400 || errCode === 100) return "invalid_request";
180
179
  if (status >= 500) return "server_error";
181
180
  return "unknown";
@@ -187,6 +186,12 @@ function mapWhatsAppCloudError(status, body) {
187
186
  const code = cloudErrorCode(status, errCode);
188
187
  if (code === "auth_failed") return { code, message: `Bearer token rejected: ${errMsg}` };
189
188
  if (code === "rate_limit") return { code, message: `Throttled: ${errMsg}` };
189
+ if (code === "session_window_expired") {
190
+ return {
191
+ code,
192
+ message: `Outside the 24-hour service window \u2014 send an approved template instead: ${errMsg}`
193
+ };
194
+ }
190
195
  return { code, message: errMsg };
191
196
  }
192
197
  function mapWhatsAppWebError(ipcError) {
@@ -206,6 +211,398 @@ function mapWhatsAppWebError(ipcError) {
206
211
  return { code: "unknown", message: msg };
207
212
  }
208
213
 
214
+ // src/backend/baileys/socket.ts
215
+ function member(mod, name) {
216
+ const asDefault = mod.default;
217
+ const fromDefault = asDefault !== void 0 && typeof asDefault === "object" ? asDefault[name] : void 0;
218
+ return fromDefault ?? mod[name];
219
+ }
220
+ async function createBaileysSocket(opts) {
221
+ const specifier = opts.specifier ?? "baileys";
222
+ let mod;
223
+ try {
224
+ mod = await import(
225
+ /* @vite-ignore */
226
+ specifier
227
+ );
228
+ } catch (err) {
229
+ throw new ConfigurationError({
230
+ code: "peer_missing",
231
+ message: `gateway-whatsapp: ${specifier} is not installed. Run \`pnpm add baileys\` to use the baileys backend. (${err instanceof Error ? err.message : String(err)})`
232
+ });
233
+ }
234
+ const makeSocket = member(
235
+ mod,
236
+ "makeWASocket"
237
+ );
238
+ const useAuthState = member(mod, "useMultiFileAuthState");
239
+ const fetchVersion = member(
240
+ mod,
241
+ "fetchLatestBaileysVersion"
242
+ );
243
+ for (const [name, value] of [
244
+ ["makeWASocket", makeSocket],
245
+ ["useMultiFileAuthState", useAuthState]
246
+ ]) {
247
+ if (typeof value !== "function") {
248
+ throw new ConfigurationError({
249
+ code: "peer_incompatible",
250
+ 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.`
251
+ });
252
+ }
253
+ }
254
+ const { state, saveCreds } = await useAuthState(opts.sessionDir);
255
+ const version = typeof fetchVersion === "function" ? (await fetchVersion()).version : void 0;
256
+ const socket = makeSocket({
257
+ auth: state,
258
+ printQRInTerminal: false,
259
+ markOnlineOnConnect: false,
260
+ syncFullHistory: false,
261
+ browser: ["theokit-gateway", "chrome", "1.0.0"],
262
+ ...version !== void 0 ? { version } : {}
263
+ });
264
+ const onQr = opts.onQr ?? ((qr) => {
265
+ process.stderr.write(
266
+ `
267
+ [whatsapp-baileys] Scan this QR with WhatsApp \u2014 Settings, Linked devices, Link a device:
268
+ ${qr}
269
+
270
+ `
271
+ );
272
+ });
273
+ socket.ev.on("connection.update", (update) => {
274
+ if (typeof update.qr === "string" && update.qr.length > 0) onQr(update.qr);
275
+ });
276
+ socket.ev.on("creds.update", () => {
277
+ void saveCreds().catch((err) => {
278
+ const message = err instanceof Error ? err.message : String(err);
279
+ process.stderr.write(`[whatsapp-baileys] could not persist credentials: ${message}
280
+ `);
281
+ });
282
+ });
283
+ return socket;
284
+ }
285
+
286
+ // src/backend/baileys/index.ts
287
+ function endQuietly(socket) {
288
+ try {
289
+ socket.end?.();
290
+ } catch {
291
+ }
292
+ }
293
+ var DEFAULT_CONNECT_TIMEOUT_MS = 6e4;
294
+ var DEFAULT_SEND_TIMEOUT_MS = 3e4;
295
+ var WhatsAppBaileysBackend = class {
296
+ constructor(opts) {
297
+ this.opts = opts;
298
+ }
299
+ opts;
300
+ kind = "baileys";
301
+ socket;
302
+ connected = false;
303
+ /** Guards a concurrent second `connect()` from opening a second live session. */
304
+ connecting;
305
+ /**
306
+ * Which connection attempt is current.
307
+ *
308
+ * Bumped by every `connect()` and every `disconnect()`. A socket from a superseded attempt
309
+ * checks it before touching any state, which is what stops an abandoned socket delivering
310
+ * inbound or flipping `connected` under a live one.
311
+ */
312
+ generation = 0;
313
+ /**
314
+ * How to end a connection attempt that is still awaiting `open`.
315
+ *
316
+ * Retirement by generation makes an attempt's listeners silent, which is not the same as
317
+ * making the attempt finish. One entry per in-flight attempt; `disconnect()` calls them so
318
+ * the attempt settles now instead of at its timeout.
319
+ */
320
+ pendingAttempts = /* @__PURE__ */ new Set();
321
+ /**
322
+ * Why the socket last closed, as Baileys reported it.
323
+ *
324
+ * Kept because `connect()` returning `false` cannot distinguish a network blip from a
325
+ * session the operator unlinked from their phone — and only one of those is worth retrying.
326
+ * `rules/error-handling.md` § 3: fail clear, and log with enough context to act.
327
+ */
328
+ lastCloseError;
329
+ inboundHandler;
330
+ statusHandler;
331
+ /**
332
+ * Serialises outbound sends (ADR D320).
333
+ *
334
+ * Both peer gateways studied do this, and one records that concurrent sends on a single
335
+ * socket can misdeliver to the wrong chat. We have NOT measured that in our own code — we
336
+ * have never run a Baileys socket — so this is precaution rather than a reproduction of our
337
+ * own bug, and saying so is the point. It is kept because the cost is one promise chain and
338
+ * the failure it guards against is a message delivered to the wrong person.
339
+ */
340
+ sendQueue = Promise.resolve();
341
+ /**
342
+ * Open the socket and wait for it to report `open`.
343
+ *
344
+ * Idempotent, and safe against a concurrent second call: the in-flight promise is shared
345
+ * rather than a second socket being built. WhatsApp's own adapter shipped without that
346
+ * guard once and opened two live sessions.
347
+ */
348
+ async connect() {
349
+ if (this.connected) return true;
350
+ if (this.connecting !== void 0) return this.connecting;
351
+ const attempt = this.openSocket();
352
+ this.connecting = attempt;
353
+ try {
354
+ return await attempt;
355
+ } finally {
356
+ if (this.connecting === attempt) this.connecting = void 0;
357
+ }
358
+ }
359
+ /** @internal */
360
+ async openSocket() {
361
+ const generation = ++this.generation;
362
+ const socket = await this.buildSocket();
363
+ const isCurrent = () => this.generation === generation;
364
+ if (!isCurrent()) {
365
+ endQuietly(socket);
366
+ return false;
367
+ }
368
+ this.subscribeInbound(socket, isCurrent);
369
+ const timeoutMs = this.opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
370
+ const openedOk = await this.raceOpen(socket, isCurrent, timeoutMs);
371
+ if (!isCurrent()) {
372
+ endQuietly(socket);
373
+ return false;
374
+ }
375
+ if (!openedOk) {
376
+ this.reportConnectFailure(timeoutMs);
377
+ this.generation += 1;
378
+ endQuietly(socket);
379
+ this.socket = void 0;
380
+ this.connected = false;
381
+ return false;
382
+ }
383
+ if (this.socket !== void 0 && this.socket !== socket) endQuietly(this.socket);
384
+ this.socket = socket;
385
+ this.connected = true;
386
+ return true;
387
+ }
388
+ /** Build a socket through the injected factory, or the real one. @internal */
389
+ async buildSocket() {
390
+ const factory = this.opts.socketFactory ?? createBaileysSocket;
391
+ return factory({
392
+ sessionDir: this.opts.sessionDir,
393
+ ...this.opts.onQr !== void 0 ? { onQr: this.opts.onQr } : {}
394
+ });
395
+ }
396
+ /** Route this socket's inbound batches into the handler, while it is still current. @internal */
397
+ subscribeInbound(socket, isCurrent) {
398
+ socket.ev.on("messages.upsert", (payload) => {
399
+ if (payload.type !== void 0 && payload.type !== "notify") return;
400
+ if (!isCurrent()) return;
401
+ for (const raw of payload.messages ?? []) this.dispatchInbound(raw);
402
+ });
403
+ }
404
+ /**
405
+ * Wait for this socket to report `open`, or for something to end the attempt.
406
+ *
407
+ * Three things can settle it: the socket opens, the socket closes, or the timeout fires — and
408
+ * a fourth, `disconnect()`, reaches it through `pendingAttempts`. That last one is why the
409
+ * resolver is registered rather than merely closed over: retiring an attempt by generation
410
+ * makes its listeners no-ops, INCLUDING the one that would settle this, so without a way in
411
+ * from outside the only thing left able to finish it was the timeout.
412
+ *
413
+ * @internal
414
+ */
415
+ async raceOpen(socket, isCurrent, timeoutMs) {
416
+ let settle = () => void 0;
417
+ const opened = new Promise((resolve2) => {
418
+ settle = resolve2;
419
+ });
420
+ const abandon = () => settle(false);
421
+ this.pendingAttempts.add(abandon);
422
+ socket.ev.on("connection.update", (update) => {
423
+ if (!isCurrent()) return;
424
+ if (update.connection === "open") {
425
+ settle(true);
426
+ return;
427
+ }
428
+ if (update.connection !== "close") return;
429
+ this.lastCloseError = update.lastDisconnect?.error;
430
+ this.connected = false;
431
+ if (this.socket === socket) this.socket = void 0;
432
+ endQuietly(socket);
433
+ settle(false);
434
+ });
435
+ const timer = setTimeout(() => settle(false), timeoutMs);
436
+ try {
437
+ return await opened;
438
+ } finally {
439
+ clearTimeout(timer);
440
+ this.pendingAttempts.delete(abandon);
441
+ }
442
+ }
443
+ /**
444
+ * Say why the connection did not open.
445
+ *
446
+ * A bare `false` tells an operator nothing, and the two causes want opposite responses: a
447
+ * blip is worth retrying, an unlinked device can only be fixed by re-pairing, and a
448
+ * supervisor that cannot tell them apart retries forever against a dead session.
449
+ *
450
+ * @internal
451
+ */
452
+ reportConnectFailure(timeoutMs) {
453
+ const error = this.lastCloseError;
454
+ const cause = error === void 0 ? `no 'open' within ${timeoutMs}ms` : error instanceof Error ? error.message : String(error);
455
+ process.stderr.write(`[whatsapp-baileys] connect failed: ${cause}
456
+ `);
457
+ }
458
+ /** Close the socket. Idempotent, and safe when never connected. */
459
+ async disconnect() {
460
+ this.generation += 1;
461
+ this.connected = false;
462
+ this.connecting = void 0;
463
+ for (const abandon of this.pendingAttempts) abandon();
464
+ this.pendingAttempts.clear();
465
+ const socket = this.socket;
466
+ this.socket = void 0;
467
+ this.inboundHandler = void 0;
468
+ this.statusHandler = void 0;
469
+ if (socket !== void 0) endQuietly(socket);
470
+ }
471
+ /**
472
+ * Send one text message.
473
+ *
474
+ * Queued behind any send already in flight (D320), and raced against a timeout whose
475
+ * expiry reports **undetermined** delivery rather than failure (D321). A local timeout says
476
+ * the acknowledgement did not arrive, not that the message did not — so this never
477
+ * retries, because a retry after a slow ack duplicates the message.
478
+ */
479
+ async send(message) {
480
+ let settled = Promise.resolve();
481
+ const run = this.sendQueue.then(
482
+ () => {
483
+ const attempt = this.sendNow(message);
484
+ settled = attempt.inFlight;
485
+ return attempt.result;
486
+ },
487
+ () => {
488
+ const attempt = this.sendNow(message);
489
+ settled = attempt.inFlight;
490
+ return attempt.result;
491
+ }
492
+ );
493
+ this.sendQueue = run.then(
494
+ () => settled.catch(() => void 0),
495
+ () => settled.catch(() => void 0)
496
+ );
497
+ return run;
498
+ }
499
+ /**
500
+ * Race one send against the send timeout.
501
+ *
502
+ * Separated so `sendNow` reads as the three outcomes it has — delivered, undetermined,
503
+ * refused — rather than as promise plumbing.
504
+ *
505
+ * @internal
506
+ */
507
+ async raceSend(inFlight, timeoutMs) {
508
+ let timer;
509
+ const timeout = new Promise((resolve2) => {
510
+ timer = setTimeout(() => resolve2("timeout"), timeoutMs);
511
+ });
512
+ try {
513
+ return await Promise.race([inFlight, timeout]);
514
+ } finally {
515
+ if (timer !== void 0) clearTimeout(timer);
516
+ }
517
+ }
518
+ /**
519
+ * One send attempt.
520
+ *
521
+ * Returns two promises deliberately. `result` is what the caller is told — it settles on
522
+ * the timeout. `inFlight` settles when the socket is actually free again, which is what the
523
+ * queue must wait for: a timeout does not cancel `sendMessage`, so releasing the queue on
524
+ * the timeout would put two sends on one socket.
525
+ *
526
+ * @internal
527
+ */
528
+ sendNow(message) {
529
+ const socket = this.socket;
530
+ if (!this.connected || socket === void 0) {
531
+ return {
532
+ result: Promise.resolve({
533
+ ok: false,
534
+ error: { code: "server_error", message: "Baileys backend is not connected." }
535
+ }),
536
+ inFlight: Promise.resolve()
537
+ };
538
+ }
539
+ const jid = `${message.to}@${message.isGroup ? "g.us" : "s.whatsapp.net"}`;
540
+ const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;
541
+ const inFlight = socket.sendMessage(jid, { text: message.text });
542
+ const result = this.raceSend(inFlight, timeoutMs).then((outcome) => {
543
+ if (outcome === "timeout") {
544
+ return {
545
+ ok: false,
546
+ error: {
547
+ code: "timeout",
548
+ message: `No acknowledgement after ${timeoutMs}ms \u2014 delivery is undetermined. Not retried: the message may already have been delivered.`
549
+ }
550
+ };
551
+ }
552
+ const wamid = outcome?.key?.id;
553
+ return wamid !== void 0 ? { ok: true, wamid } : { ok: true };
554
+ }).catch((err) => ({
555
+ ok: false,
556
+ error: {
557
+ code: "server_error",
558
+ message: err instanceof Error ? err.message : String(err)
559
+ }
560
+ }));
561
+ return { result, inFlight };
562
+ }
563
+ /** Subscribe to inbound events. EC-H: a second call REPLACES the first. */
564
+ onInbound(handler) {
565
+ this.inboundHandler = handler;
566
+ return () => {
567
+ if (this.inboundHandler === handler) this.inboundHandler = void 0;
568
+ };
569
+ }
570
+ /**
571
+ * Subscribe to delivery receipts. EC-H: a second call REPLACES the first.
572
+ *
573
+ * Declared for the interface; Baileys reports receipts on `messages.update`, which v1 does
574
+ * not consume. Registering a handler is accepted and it is never called — stated here
575
+ * rather than left for a consumer to discover from silence.
576
+ */
577
+ onStatusReceipt(handler) {
578
+ this.statusHandler = handler;
579
+ return () => {
580
+ if (this.statusHandler === handler) this.statusHandler = void 0;
581
+ };
582
+ }
583
+ /**
584
+ * Normalise one envelope and hand it to the handler.
585
+ *
586
+ * The promise is floated because the Baileys listener is synchronous — but with a `catch`,
587
+ * because a bare `void` on a rejecting promise ends the process under Node's default, which
588
+ * is what killed two adapters in this package (#41). A handler is user code; its failure is
589
+ * named as the handler's and delivery continues.
590
+ *
591
+ * @internal
592
+ */
593
+ dispatchInbound(raw) {
594
+ const handler = this.inboundHandler;
595
+ if (handler === void 0) return;
596
+ const event = normalizeBaileysMessage(raw);
597
+ if (event === void 0) return;
598
+ void handler(event).catch((err) => {
599
+ const message = err instanceof Error ? err.message : String(err);
600
+ process.stderr.write(`[whatsapp-baileys] handler threw: ${message}
601
+ `);
602
+ });
603
+ }
604
+ };
605
+
209
606
  // src/backend/cloud/client.ts
210
607
  var WhatsAppCloudClient = class {
211
608
  constructor(opts) {
@@ -231,6 +628,44 @@ var WhatsAppCloudClient = class {
231
628
  type: "text",
232
629
  text: { body, preview_url: false }
233
630
  };
631
+ return this.postMessage(req);
632
+ }
633
+ /**
634
+ * Send an approved template.
635
+ *
636
+ * The only message type Meta accepts outside the 24-hour service window, and so the only way to
637
+ * reach someone who has not written first — every notification, and every unattended check of
638
+ * whether this integration still works. Free-form text to a cold recipient is refused with
639
+ * `131047`, which the error mapper now surfaces as `session_window_expired`.
640
+ *
641
+ * `components` is omitted from the payload when absent rather than sent empty: Meta rejects
642
+ * `components: []` on a template that declares no variables, so the two are not equivalent.
643
+ *
644
+ * Deliberately NOT on the `WhatsAppBackend` interface. The web backend drives WhatsApp Web,
645
+ * which has no concept of templates, and widening the shared contract would hand it a method it
646
+ * can only throw from.
647
+ */
648
+ async sendTemplate(to, templateName, languageCode, components) {
649
+ const req = {
650
+ messaging_product: "whatsapp",
651
+ recipient_type: "individual",
652
+ to,
653
+ type: "template",
654
+ template: {
655
+ name: templateName,
656
+ language: { code: languageCode },
657
+ ...components !== void 0 && components.length > 0 ? { components } : {}
658
+ }
659
+ };
660
+ return this.postMessage(req);
661
+ }
662
+ /**
663
+ * POST one message envelope and turn Meta's answer into a `WhatsAppSendResult`.
664
+ *
665
+ * Shared by every send: how to reach the endpoint, how to authenticate, and how to read the
666
+ * reply is one piece of knowledge, and it was about to have a second copy.
667
+ */
668
+ async postMessage(req) {
234
669
  let response;
235
670
  try {
236
671
  response = await this.fetchImpl(`${this.baseUrl}/messages`, {
@@ -405,16 +840,34 @@ var WhatsAppCloudBackend = class {
405
840
  async send(message) {
406
841
  return this.client.sendText(message.to, message.text, message.isGroup);
407
842
  }
843
+ /**
844
+ * Send an approved template to `to`.
845
+ *
846
+ * Cloud-only, and deliberately absent from the `WhatsAppBackend` interface: WhatsApp Web has no
847
+ * concept of templates, so putting this on the shared contract would hand the web backend a
848
+ * method it could only throw from. A consumer reaches it by holding the backend directly.
849
+ *
850
+ * This is the only way to message someone outside the 24-hour service window — every
851
+ * notification, and every unattended check that this integration still works. Free-form text to
852
+ * a cold recipient comes back as `session_window_expired`.
853
+ *
854
+ * @param templateName Name of a template already approved on the WhatsApp Business account.
855
+ * @param languageCode Locale of the approved template, e.g. `en_US`, `pt_BR`.
856
+ * @param components Values for the template's variables; omit for a template that takes none.
857
+ */
858
+ async sendTemplate(to, templateName, languageCode, components) {
859
+ return this.client.sendTemplate(to, templateName, languageCode, components);
860
+ }
408
861
  onInbound(handler) {
409
862
  this.inboundHandler = handler;
410
863
  return () => {
411
- this.inboundHandler = void 0;
864
+ if (this.inboundHandler === handler) this.inboundHandler = void 0;
412
865
  };
413
866
  }
414
867
  onStatusReceipt(handler) {
415
868
  this.statusHandler = handler;
416
869
  return () => {
417
- this.statusHandler = void 0;
870
+ if (this.statusHandler === handler) this.statusHandler = void 0;
418
871
  };
419
872
  }
420
873
  /**
@@ -428,25 +881,52 @@ var WhatsAppCloudBackend = class {
428
881
  if (!verifyWebhookSignature(rawBody, signatureHeader, this.appSecret)) {
429
882
  return false;
430
883
  }
431
- const json = JSON.parse(
432
- typeof rawBody === "string" ? rawBody : rawBody.toString("utf8")
433
- );
884
+ const json = this.parseBody(rawBody);
885
+ if (json === void 0) return false;
434
886
  const envelope = parseWebhookPayload(json);
435
887
  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
- }
888
+ for (const event of normalizeInboundMessages(envelope)) {
889
+ if (this.inboundHandler === void 0) continue;
890
+ await this.dispatchContained(() => this.inboundHandler?.(event), "handler");
441
891
  }
442
- const statuses = normalizeStatusReceipts(envelope);
443
- for (const receipt of statuses) {
444
- if (this.statusHandler !== void 0) {
445
- await this.statusHandler(receipt);
446
- }
892
+ for (const receipt of normalizeStatusReceipts(envelope)) {
893
+ if (this.statusHandler === void 0) continue;
894
+ await this.dispatchContained(() => this.statusHandler?.(receipt), "status handler");
447
895
  }
448
896
  return true;
449
897
  }
898
+ /**
899
+ * Parse a signed webhook body, or report `undefined` when it is not JSON.
900
+ *
901
+ * The method's contract is true/false; the route calling it has no reason to expect a throw.
902
+ */
903
+ parseBody(rawBody) {
904
+ try {
905
+ return JSON.parse(typeof rawBody === "string" ? rawBody : rawBody.toString("utf8"));
906
+ } catch (err) {
907
+ const m = err instanceof Error ? err.message : String(err);
908
+ process.stderr.write(`[whatsapp-cloud] webhook body is not JSON: ${m}
909
+ `);
910
+ return void 0;
911
+ }
912
+ }
913
+ /**
914
+ * Run one user callback and contain its failure.
915
+ *
916
+ * Meta batches several messages, and their delivery receipts, into a single webhook. Awaiting a
917
+ * handler with nothing around it made one throw skip every remaining message in the payload —
918
+ * and reject `handleWebhookPayload`, so the caller's route answered 500 and Meta redelivered the
919
+ * whole batch, replaying the messages that HAD succeeded (#41).
920
+ */
921
+ async dispatchContained(run, what) {
922
+ try {
923
+ await run();
924
+ } catch (err) {
925
+ const m = err instanceof Error ? err.message : String(err);
926
+ process.stderr.write(`[whatsapp-cloud] ${what} threw: ${m}
927
+ `);
928
+ }
929
+ }
450
930
  };
451
931
 
452
932
  // src/backend/web/ipc.ts
@@ -485,10 +965,10 @@ var LineBuffer = class {
485
965
  };
486
966
  var BRIDGE_PROCESS_TAG = "whatsapp-web-bridge";
487
967
  function pidFilePath(theokitHome, sessionId) {
488
- return path__namespace.join(theokitHome, `whatsapp-bridge-${sessionId}.pid`);
968
+ return path2__namespace.join(theokitHome, `whatsapp-bridge-${sessionId}.pid`);
489
969
  }
490
970
  function defaultTheokitHome() {
491
- return process.env.THEOKIT_HOME ?? path__namespace.join(process.env.HOME ?? "/tmp", ".theokit");
971
+ return process.env.THEOKIT_HOME ?? path2__namespace.join(process.env.HOME ?? "/tmp", ".theokit");
492
972
  }
493
973
  function pidBelongsToOurBridge(pid) {
494
974
  try {
@@ -591,8 +1071,8 @@ function waitForExit(child, timeoutMs) {
591
1071
  }
592
1072
 
593
1073
  // src/backend/web/index.ts
594
- var DEFAULT_CONNECT_TIMEOUT_MS = 12e4;
595
- var DEFAULT_SEND_TIMEOUT_MS = 3e4;
1074
+ var DEFAULT_CONNECT_TIMEOUT_MS2 = 12e4;
1075
+ var DEFAULT_SEND_TIMEOUT_MS2 = 3e4;
596
1076
  var WhatsAppWebBackend = class {
597
1077
  constructor(opts) {
598
1078
  this.opts = opts;
@@ -604,6 +1084,8 @@ var WhatsAppWebBackend = class {
604
1084
  inboundHandler;
605
1085
  statusHandler;
606
1086
  pending = /* @__PURE__ */ new Map();
1087
+ /** Rejects an in-flight `connect()` when the bridge reports it cannot start. */
1088
+ connectRejectors = [];
607
1089
  msgIdCounter = 0;
608
1090
  botPhone;
609
1091
  connected = false;
@@ -636,22 +1118,27 @@ var WhatsAppWebBackend = class {
636
1118
  if (this.connected) return true;
637
1119
  this.handle = this.spawnBridgeHandle();
638
1120
  this.wireStdout();
639
- const timeoutMs = this.opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
640
- const ready = new Promise((resolve2) => this.readyResolvers.push(resolve2));
1121
+ const timeoutMs = this.opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS2;
1122
+ const ready = new Promise((resolve2, reject) => {
1123
+ this.readyResolvers.push(resolve2);
1124
+ this.connectRejectors.push(reject);
1125
+ });
641
1126
  let timer;
642
1127
  const timeout = new Promise((_resolve, reject) => {
643
1128
  timer = setTimeout(() => reject(new WhatsAppConnectTimeoutError(timeoutMs)), timeoutMs);
644
1129
  });
645
1130
  try {
646
1131
  const phone = await Promise.race([ready, timeout]);
647
- if (timer !== void 0) clearTimeout(timer);
648
1132
  this.botPhone = phone;
649
1133
  this.connected = true;
650
1134
  return true;
651
1135
  } catch (err) {
652
- if (timer !== void 0) clearTimeout(timer);
653
1136
  await this.cleanupHandle();
654
1137
  throw err;
1138
+ } finally {
1139
+ if (timer !== void 0) clearTimeout(timer);
1140
+ this.readyResolvers = [];
1141
+ this.connectRejectors = [];
655
1142
  }
656
1143
  }
657
1144
  async disconnect() {
@@ -671,13 +1158,14 @@ var WhatsAppWebBackend = class {
671
1158
  }
672
1159
  this.pending.clear();
673
1160
  this.readyResolvers = [];
1161
+ this.connectRejectors = [];
674
1162
  }
675
1163
  async send(message) {
676
1164
  if (!this.connected || this.handle === void 0 || this.handle.child.stdin === null) {
677
1165
  return { ok: false, error: { code: "server_error", message: "Bridge not connected." } };
678
1166
  }
679
1167
  const msgId = `out-${++this.msgIdCounter}`;
680
- const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;
1168
+ const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS2;
681
1169
  return new Promise((resolve2) => {
682
1170
  const timer = setTimeout(() => {
683
1171
  this.pending.delete(msgId);
@@ -704,13 +1192,13 @@ var WhatsAppWebBackend = class {
704
1192
  onInbound(handler) {
705
1193
  this.inboundHandler = handler;
706
1194
  return () => {
707
- this.inboundHandler = void 0;
1195
+ if (this.inboundHandler === handler) this.inboundHandler = void 0;
708
1196
  };
709
1197
  }
710
1198
  onStatusReceipt(handler) {
711
1199
  this.statusHandler = handler;
712
1200
  return () => {
713
- this.statusHandler = void 0;
1201
+ if (this.statusHandler === handler) this.statusHandler = void 0;
714
1202
  };
715
1203
  }
716
1204
  handleReady(event) {
@@ -730,7 +1218,27 @@ var WhatsAppWebBackend = class {
730
1218
  backend: "web",
731
1219
  raw: event
732
1220
  };
733
- void this.inboundHandler(normalized);
1221
+ void this.inboundHandler(normalized).catch((err) => {
1222
+ const m = err instanceof Error ? err.message : String(err);
1223
+ process.stderr.write(`[whatsapp-web] handler threw: ${m}
1224
+ `);
1225
+ });
1226
+ }
1227
+ /**
1228
+ * A bridge that reported a failure has failed — say so now, not in two minutes.
1229
+ *
1230
+ * This used to write the message to stderr and return. `connect()` races only the `ready`
1231
+ * promise against the timeout, so a bridge that told us exactly what was wrong and exited
1232
+ * still cost the caller the full `connectTimeoutMs` and surfaced as a timeout — the one
1233
+ * error that carries no information. The diagnosis was printed where nothing could act on
1234
+ * it, which is the swallowing `rules/error-handling.md` § 5 names.
1235
+ */
1236
+ handleBridgeError(event) {
1237
+ process.stderr.write(`[whatsapp-web bridge] ${event.message}
1238
+ `);
1239
+ const failure = new WhatsAppBridgeError(event.message, event.code);
1240
+ for (const reject of this.connectRejectors) reject(failure);
1241
+ this.connectRejectors = [];
734
1242
  }
735
1243
  handleSendAck(event) {
736
1244
  const pending = this.pending.get(event.msgId);
@@ -750,6 +1258,10 @@ var WhatsAppWebBackend = class {
750
1258
  status: event.status,
751
1259
  recipient: event.recipient,
752
1260
  timestamp: event.timestamp || Date.now()
1261
+ }).catch((err) => {
1262
+ const m = err instanceof Error ? err.message : String(err);
1263
+ process.stderr.write(`[whatsapp-web] status handler threw: ${m}
1264
+ `);
753
1265
  });
754
1266
  }
755
1267
  dispatch(event) {
@@ -767,24 +1279,325 @@ var WhatsAppWebBackend = class {
767
1279
  this.handleStatus(event);
768
1280
  return;
769
1281
  case "error":
770
- process.stderr.write(`[whatsapp-web bridge] ${event.message}
771
- `);
1282
+ this.handleBridgeError(event);
772
1283
  return;
773
1284
  }
774
1285
  }
775
1286
  };
776
1287
  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
- );
1288
+ 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))));
1289
+ const candidates = [
1290
+ // Bundled: dist/index.js beside dist/bridge/
1291
+ path2__namespace.resolve(here, "bridge/whatsapp-web-bridge.mjs"),
1292
+ // Source: src/backend/web/index.ts up two to src/
1293
+ path2__namespace.resolve(here, "../../bridge/whatsapp-web-bridge.mjs")
1294
+ ];
1295
+ const found = candidates.find((candidate) => fs.existsSync(candidate));
1296
+ if (found === void 0) {
1297
+ throw new WhatsAppBridgeError(
1298
+ `bridge script not found. Looked in: ${candidates.join(", ")}. Pass \`bridgeScriptPath\` explicitly if the package layout differs.`,
1299
+ "bridge_script_missing"
1300
+ );
1301
+ }
1302
+ return found;
1303
+ }
1304
+ var WHATSAPP_MAX_TEXT = 4096;
1305
+ function splitForWhatsApp(text) {
1306
+ return gateway.chunkText(text, {
1307
+ limit: WHATSAPP_MAX_TEXT,
1308
+ boundaries: ["\n\n", "\n", " "],
1309
+ lastResort: "last-boundary",
1310
+ surrogateGuard: true,
1311
+ stripLeading: /^\s+/,
1312
+ trimParts: true
1313
+ });
781
1314
  }
782
1315
 
1316
+ // src/adapter.ts
1317
+ function requireNonEmpty(entries) {
1318
+ for (const [name, value] of entries) {
1319
+ if (value === void 0 || value.trim().length === 0) {
1320
+ throw new ConfigurationError({
1321
+ code: "missing_option",
1322
+ message: `gateway-whatsapp: ${name} is required and must not be empty.`
1323
+ });
1324
+ }
1325
+ }
1326
+ }
1327
+ function digitsOnly(s) {
1328
+ return s.replace(/[^\d]/g, "");
1329
+ }
1330
+ var PHONE_RUN = /[\d][\d+\-().  ]*[\d]|[\d]/g;
1331
+ function phoneRuns(s) {
1332
+ return (s.match(PHONE_RUN) ?? []).map(digitsOnly).filter((d) => d.length > 0);
1333
+ }
1334
+ var WhatsAppAdapter = class _WhatsAppAdapter extends gateway.BasePlatformAdapter {
1335
+ platform = "whatsapp";
1336
+ backendImpl;
1337
+ requireMention;
1338
+ botPhoneId;
1339
+ /** `undefined` = no allowlist configured; a set = configured, and enforced fail-closed. */
1340
+ allowedSenders;
1341
+ /** Mirrors the sibling adapters: guards connect() against opening a second session. */
1342
+ connected = false;
1343
+ handler;
1344
+ statusHandler;
1345
+ // EC-H: track unsubscribe handles so onInbound REPLACES instead of stacks.
1346
+ inboundUnsubscribe;
1347
+ statusUnsubscribe;
1348
+ /**
1349
+ * Build an adapter from a discriminated configuration.
1350
+ *
1351
+ * The entry point for configuration that arrives as **data** — read from a file, an
1352
+ * environment, or a tenant record — where the backend is a string rather than a decision
1353
+ * made in code. `fromCloud` / `fromWeb` are the direct forms when the choice is already
1354
+ * known at the call site.
1355
+ *
1356
+ * This is what `WhatsAppAdapterOptions` exists for. Until it had this consumer the union
1357
+ * was exported, documented and inert, which is the defect #47 was filed about, and the
1358
+ * first attempt at closing that issue left it inert — the factories took the config halves
1359
+ * directly and never the union.
1360
+ *
1361
+ * @throws {ConfigurationError} when a required option is missing or empty.
1362
+ * @public
1363
+ */
1364
+ static from(options, common = {}) {
1365
+ switch (options.backend) {
1366
+ case "cloud":
1367
+ return _WhatsAppAdapter.fromCloud(options.cloud, common);
1368
+ case "web":
1369
+ return _WhatsAppAdapter.fromWeb(options.web, common);
1370
+ case "baileys":
1371
+ return _WhatsAppAdapter.fromBaileys(options.baileys, common);
1372
+ }
1373
+ }
1374
+ /**
1375
+ * Build a Baileys adapter.
1376
+ *
1377
+ * Unofficial, and no amount of code changes that: it automates a WhatsApp Web session,
1378
+ * which Meta's terms do not sanction and which can get a number banned. Use a number
1379
+ * created for this, never a personal one. Prefer {@link WhatsAppAdapter.fromCloud} unless
1380
+ * the number has no Cloud API access.
1381
+ *
1382
+ * Unlike {@link WhatsAppAdapter.fromWeb} it embeds no browser — it speaks the multi-device
1383
+ * protocol over a WebSocket. `baileys` is an optional peer dependency; it is loaded lazily
1384
+ * at connect, so a consumer who never calls this never needs it installed.
1385
+ *
1386
+ * `botPhoneId` has nothing to default from here, so leaving it unset while `requireMention`
1387
+ * is on (its default) drops every group message. The adapter logs when it does.
1388
+ *
1389
+ * @throws {ConfigurationError} when `sessionDir` is missing or empty.
1390
+ * @public
1391
+ */
1392
+ static fromBaileys(baileys, opts = {}) {
1393
+ requireNonEmpty([["sessionDir", baileys.sessionDir]]);
1394
+ return new _WhatsAppAdapter(
1395
+ new WhatsAppBaileysBackend({
1396
+ sessionDir: baileys.sessionDir,
1397
+ ...baileys.connectTimeoutMs !== void 0 ? { connectTimeoutMs: baileys.connectTimeoutMs } : {},
1398
+ ...baileys.sendTimeoutMs !== void 0 ? { sendTimeoutMs: baileys.sendTimeoutMs } : {},
1399
+ ...baileys.onQr !== void 0 ? { onQr: baileys.onQr } : {}
1400
+ }),
1401
+ opts
1402
+ );
1403
+ }
1404
+ /**
1405
+ * Build a Cloud-API adapter.
1406
+ *
1407
+ * The construction path this package's docblock has named since it was written, and which
1408
+ * did not exist until #47 — a consumer following the only guidance the package gave wrote
1409
+ * code that would not compile.
1410
+ *
1411
+ * Prefer it over the constructor: it keeps `WhatsAppCloudBackend` an implementation detail
1412
+ * of this package rather than something every consumer imports and assembles.
1413
+ *
1414
+ * @throws {ConfigurationError} when a required credential is missing or empty.
1415
+ * @public
1416
+ */
1417
+ static fromCloud(cloud, opts = {}) {
1418
+ requireNonEmpty([
1419
+ ["accessToken", cloud.accessToken],
1420
+ ["phoneNumberId", cloud.phoneNumberId]
1421
+ ]);
1422
+ if (cloud.apiVersion !== void 0) {
1423
+ requireNonEmpty([["apiVersion", cloud.apiVersion]]);
1424
+ }
1425
+ return new _WhatsAppAdapter(
1426
+ new WhatsAppCloudBackend({
1427
+ accessToken: cloud.accessToken,
1428
+ phoneNumberId: cloud.phoneNumberId,
1429
+ appSecret: cloud.appSecret,
1430
+ ...cloud.apiVersion !== void 0 ? { apiVersion: cloud.apiVersion } : {}
1431
+ }),
1432
+ { ...opts, botPhoneId: opts.botPhoneId ?? cloud.phoneNumberId }
1433
+ );
1434
+ }
1435
+ /**
1436
+ * Build a WhatsApp-Web adapter.
1437
+ *
1438
+ * Unofficial: it drives a real WhatsApp Web session through a browser, which Meta's terms
1439
+ * do not sanction and which can get a number banned. It also needs a browser this package
1440
+ * does not install. Prefer {@link WhatsAppAdapter.fromCloud} unless the number has no
1441
+ * Cloud API access.
1442
+ *
1443
+ * @throws {ConfigurationError} when `sessionId` is missing or empty.
1444
+ * @public
1445
+ */
1446
+ static fromWeb(web, opts = {}) {
1447
+ requireNonEmpty([["sessionId", web.sessionId]]);
1448
+ return new _WhatsAppAdapter(
1449
+ new WhatsAppWebBackend({
1450
+ sessionId: web.sessionId,
1451
+ ...web.bridgeScriptPath !== void 0 ? { bridgeScriptPath: web.bridgeScriptPath } : {}
1452
+ }),
1453
+ opts
1454
+ );
1455
+ }
1456
+ /** Construct from a pre-built backend. Prefer the factories; this is for tests and for a custom backend. */
1457
+ constructor(backendImpl, opts = {}) {
1458
+ super();
1459
+ this.backendImpl = backendImpl;
1460
+ this.requireMention = opts.requireMention ?? true;
1461
+ this.botPhoneId = digitsOnly(opts.botPhoneId ?? "");
1462
+ this.allowedSenders = opts.allowedSenders === void 0 ? void 0 : parseAllowedSenders(opts.allowedSenders);
1463
+ }
1464
+ /** Escape hatch (D180-style) for advanced features. */
1465
+ getBackend() {
1466
+ return this.backendImpl;
1467
+ }
1468
+ async connect() {
1469
+ if (this.connected) return true;
1470
+ const ok = await this.backendImpl.connect();
1471
+ this.connected = ok;
1472
+ return ok;
1473
+ }
1474
+ async disconnect() {
1475
+ this.connected = false;
1476
+ this.inboundUnsubscribe?.();
1477
+ this.inboundUnsubscribe = void 0;
1478
+ this.statusUnsubscribe?.();
1479
+ this.statusUnsubscribe = void 0;
1480
+ this.handler = void 0;
1481
+ this.statusHandler = void 0;
1482
+ await this.backendImpl.disconnect();
1483
+ }
1484
+ async sendMessage(out) {
1485
+ if (out.text.length === 0) {
1486
+ return { ok: false, error: { code: "empty_text", message: "Empty text rejected." } };
1487
+ }
1488
+ const parts = splitForWhatsApp(out.text);
1489
+ if (parts.length === 0) {
1490
+ return {
1491
+ ok: false,
1492
+ error: { code: "empty_text", message: "Text reduced to zero parts after splitting." }
1493
+ };
1494
+ }
1495
+ let lastWamid;
1496
+ const isGroup = out.channel.type === "group";
1497
+ for (const part of parts) {
1498
+ const r = await this.backendImpl.send({ to: out.channel.id, isGroup, text: part });
1499
+ if (!r.ok) {
1500
+ return {
1501
+ ok: false,
1502
+ error: { code: r.error?.code ?? "unknown", message: r.error?.message ?? "Send failed." }
1503
+ };
1504
+ }
1505
+ lastWamid = r.wamid;
1506
+ }
1507
+ return lastWamid !== void 0 ? { ok: true, messageId: lastWamid } : { ok: true };
1508
+ }
1509
+ /**
1510
+ * Is this sender refused by a configured allowlist?
1511
+ *
1512
+ * Runs before the group/mention filter because it answers a different question: that one asks
1513
+ * whether a message was meant for us, this one asks whether the sender may reach us at all.
1514
+ *
1515
+ * The refusal is logged. A silent drop is indistinguishable from a broken gateway, and the
1516
+ * first thing a mistyped allowlist causes is an operator wondering why the bot went mute.
1517
+ */
1518
+ isRefusedBySenderAllowlist(inbound) {
1519
+ if (this.allowedSenders === void 0) return false;
1520
+ if (isSenderAllowed(inbound.fromPhone, this.allowedSenders)) return false;
1521
+ process.stderr.write(
1522
+ `[whatsapp] dropped inbound from "${inbound.fromPhone}" \u2014 not in the configured allowlist
1523
+ `
1524
+ );
1525
+ return true;
1526
+ }
1527
+ /** D309 + EC-7: group filter with digit-only normalization. */
1528
+ shouldDropGroupMessage(inbound) {
1529
+ if (inbound.conversationType !== "group" || !this.requireMention) return false;
1530
+ if (this.botPhoneId.length === 0) {
1531
+ process.stderr.write(
1532
+ "[whatsapp] dropping every group message: requireMention is on and botPhoneId is unset\n"
1533
+ );
1534
+ return true;
1535
+ }
1536
+ return !phoneRuns(inbound.text).some((run) => run.includes(this.botPhoneId));
1537
+ }
1538
+ toMessageEvent(inbound) {
1539
+ return {
1540
+ id: inbound.wamid,
1541
+ platform: "whatsapp",
1542
+ sender: { id: inbound.fromPhone, displayName: inbound.contactName },
1543
+ channel: { id: inbound.channelId, type: inbound.conversationType },
1544
+ text: inbound.text,
1545
+ receivedAt: inbound.receivedAt,
1546
+ whatsapp: {
1547
+ wamid: inbound.wamid,
1548
+ phoneNumberId: inbound.phoneNumberId,
1549
+ contactName: inbound.contactName,
1550
+ backend: inbound.backend,
1551
+ raw: inbound.raw
1552
+ }
1553
+ };
1554
+ }
1555
+ onInbound(handler) {
1556
+ this.inboundUnsubscribe?.();
1557
+ this.handler = handler;
1558
+ const off = this.backendImpl.onInbound(async (inbound) => {
1559
+ if (!this.handler) return;
1560
+ if (this.isRefusedBySenderAllowlist(inbound)) return;
1561
+ if (this.shouldDropGroupMessage(inbound)) return;
1562
+ await this.handler(this.toMessageEvent(inbound));
1563
+ });
1564
+ this.inboundUnsubscribe = off;
1565
+ return () => {
1566
+ if (this.handler === handler) {
1567
+ this.handler = void 0;
1568
+ off();
1569
+ this.inboundUnsubscribe = void 0;
1570
+ }
1571
+ };
1572
+ }
1573
+ /** Status receipts (sent/delivered/read/failed). Adapter-specific (D307). */
1574
+ onStatusReceipt(handler) {
1575
+ this.statusUnsubscribe?.();
1576
+ this.statusHandler = handler;
1577
+ const off = this.backendImpl.onStatusReceipt(async (r) => {
1578
+ await this.statusHandler?.(r);
1579
+ });
1580
+ this.statusUnsubscribe = off;
1581
+ return () => {
1582
+ if (this.statusHandler === handler) {
1583
+ this.statusHandler = void 0;
1584
+ off();
1585
+ this.statusUnsubscribe = void 0;
1586
+ }
1587
+ };
1588
+ }
1589
+ };
1590
+
1591
+ exports.ConfigurationError = ConfigurationError;
783
1592
  exports.LineBuffer = LineBuffer;
784
1593
  exports.WhatsAppAdapter = WhatsAppAdapter;
1594
+ exports.WhatsAppBaileysBackend = WhatsAppBaileysBackend;
1595
+ exports.WhatsAppBridgeError = WhatsAppBridgeError;
785
1596
  exports.WhatsAppCloudBackend = WhatsAppCloudBackend;
786
1597
  exports.WhatsAppConnectTimeoutError = WhatsAppConnectTimeoutError;
787
1598
  exports.WhatsAppWebBackend = WhatsAppWebBackend;
1599
+ exports.createBaileysSocket = createBaileysSocket;
1600
+ exports.defaultBridgeScriptPath = defaultBridgeScriptPath;
788
1601
  exports.digitsOnly = digitsOnly;
789
1602
  exports.formatCommand = formatCommand;
790
1603
  exports.mapWhatsAppCloudError = mapWhatsAppCloudError;