@theokit/gateway-whatsapp 0.1.1 → 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.js CHANGED
@@ -1,165 +1,156 @@
1
- import { 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
10
 
9
- // src/split.ts
10
- var WHATSAPP_MAX_TEXT = 4096;
11
- function findWhatsAppCutPoint(remaining) {
12
- let cut = remaining.lastIndexOf("\n\n", WHATSAPP_MAX_TEXT);
13
- if (cut < WHATSAPP_MAX_TEXT * 0.5) cut = remaining.lastIndexOf("\n", WHATSAPP_MAX_TEXT);
14
- if (cut < WHATSAPP_MAX_TEXT * 0.5) cut = remaining.lastIndexOf(" ", WHATSAPP_MAX_TEXT);
15
- if (cut <= 0) cut = WHATSAPP_MAX_TEXT;
16
- if (cut < remaining.length) {
17
- const code = remaining.charCodeAt(cut);
18
- if (code >= 56320 && code <= 57343) cut -= 1;
19
- }
20
- return cut <= 0 ? WHATSAPP_MAX_TEXT : cut;
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, "");
21
17
  }
22
- function splitForWhatsApp(text) {
23
- if (text.length <= WHATSAPP_MAX_TEXT) {
24
- const single = text.trim();
25
- return single.length > 0 ? [single] : [];
26
- }
27
- const chunks = [];
28
- let remaining = text;
29
- while (remaining.length > WHATSAPP_MAX_TEXT) {
30
- const cut = findWhatsAppCutPoint(remaining);
31
- chunks.push(remaining.slice(0, cut));
32
- remaining = remaining.slice(cut).replace(/^[\s]+/, "");
33
- }
34
- if (remaining.length > 0) chunks.push(remaining);
35
- return chunks.map((p) => p.trim()).filter((p) => p.length > 0);
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);
36
28
  }
37
29
 
38
- // src/adapter.ts
39
- function digitsOnly(s) {
40
- 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;
41
41
  }
42
- var WhatsAppAdapter = class extends BasePlatformAdapter {
43
- platform = "whatsapp";
44
- backendImpl;
45
- requireMention;
46
- botPhoneId;
47
- handler;
48
- statusHandler;
49
- // EC-H: track unsubscribe handles so onInbound REPLACES instead of stacks.
50
- inboundUnsubscribe;
51
- statusUnsubscribe;
52
- /** Construct from a pre-built backend (used by the static factories + tests). */
53
- constructor(backendImpl, opts = {}) {
54
- super();
55
- this.backendImpl = backendImpl;
56
- this.requireMention = opts.requireMention ?? true;
57
- this.botPhoneId = digitsOnly(opts.botPhoneId ?? "");
58
- }
59
- /** Escape hatch (D180-style) for advanced features. */
60
- getBackend() {
61
- return this.backendImpl;
62
- }
63
- async connect() {
64
- return this.backendImpl.connect();
65
- }
66
- async disconnect() {
67
- this.inboundUnsubscribe?.();
68
- this.inboundUnsubscribe = void 0;
69
- this.statusUnsubscribe?.();
70
- this.statusUnsubscribe = void 0;
71
- this.handler = void 0;
72
- this.statusHandler = void 0;
73
- await this.backendImpl.disconnect();
74
- }
75
- async sendMessage(out) {
76
- if (out.text.length === 0) {
77
- return { ok: false, error: { code: "empty_text", message: "Empty text rejected." } };
78
- }
79
- const parts = splitForWhatsApp(out.text);
80
- if (parts.length === 0) {
81
- return {
82
- ok: false,
83
- error: { code: "empty_text", message: "Text reduced to zero parts after splitting." }
84
- };
85
- }
86
- let lastWamid;
87
- const isGroup = out.channel.type === "group";
88
- for (const part of parts) {
89
- const r = await this.backendImpl.send({ to: out.channel.id, isGroup, text: part });
90
- if (!r.ok) {
91
- return {
92
- ok: false,
93
- error: { code: r.error?.code ?? "unknown", message: r.error?.message ?? "Send failed." }
94
- };
95
- }
96
- lastWamid = r.wamid;
97
- }
98
- return lastWamid !== void 0 ? { ok: true, messageId: lastWamid } : { ok: true };
42
+ function asText(value) {
43
+ return typeof value === "string" && value.length > 0 ? value : void 0;
44
+ }
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;
99
57
  }
100
- /** D309 + EC-7: group filter with digit-only normalization. */
101
- shouldDropGroupMessage(inbound) {
102
- if (inbound.conversationType !== "group" || !this.requireMention) return false;
103
- if (this.botPhoneId.length === 0) return true;
104
- const textDigits = digitsOnly(inbound.text);
105
- return !textDigits.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;
106
65
  }
107
- toMessageEvent(inbound) {
108
- return {
109
- id: inbound.wamid,
110
- platform: "whatsapp",
111
- sender: { id: inbound.fromPhone, displayName: inbound.contactName },
112
- channel: { id: inbound.channelId, type: inbound.conversationType },
113
- text: inbound.text,
114
- receivedAt: inbound.receivedAt,
115
- whatsapp: {
116
- wamid: inbound.wamid,
117
- phoneNumberId: inbound.phoneNumberId,
118
- contactName: inbound.contactName,
119
- backend: inbound.backend,
120
- raw: inbound.raw
121
- }
122
- };
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;
123
70
  }
124
- onInbound(handler) {
125
- this.inboundUnsubscribe?.();
126
- this.handler = handler;
127
- this.inboundUnsubscribe = this.backendImpl.onInbound(async (inbound) => {
128
- if (!this.handler) return;
129
- if (this.shouldDropGroupMessage(inbound)) return;
130
- await this.handler(this.toMessageEvent(inbound));
131
- });
132
- return () => {
133
- this.inboundUnsubscribe?.();
134
- this.inboundUnsubscribe = void 0;
135
- this.handler = void 0;
136
- };
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);
137
117
  }
138
- /** Status receipts (sent/delivered/read/failed). Adapter-specific (D307). */
139
- onStatusReceipt(handler) {
140
- this.statusUnsubscribe?.();
141
- this.statusHandler = handler;
142
- this.statusUnsubscribe = this.backendImpl.onStatusReceipt(async (r) => {
143
- await this.statusHandler?.(r);
144
- });
145
- return () => {
146
- this.statusUnsubscribe?.();
147
- this.statusUnsubscribe = void 0;
148
- this.statusHandler = void 0;
149
- };
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;
150
126
  }
151
127
  };
152
-
153
- // src/errors.ts
154
128
  var WhatsAppConnectTimeoutError = class extends Error {
155
129
  constructor(timeoutMs) {
156
130
  super(`WhatsApp web bridge connect timed out after ${timeoutMs}ms (QR code not scanned?)`);
157
131
  this.name = "WhatsAppConnectTimeoutError";
158
132
  }
159
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;
160
149
  function cloudErrorCode(status, errCode) {
161
150
  if (errCode === 190 || status === 401) return "auth_failed";
162
- if (errCode === 130 || errCode === 131 || status === 429) return "rate_limit";
151
+ if (RATE_LIMIT_CODES.has(errCode) || status === 429) return "rate_limit";
152
+ if (errCode === SESSION_WINDOW_EXPIRED_CODE) return "session_window_expired";
153
+ if (UNDELIVERABLE_CODES.has(errCode)) return "undeliverable";
163
154
  if (status === 400 || errCode === 100) return "invalid_request";
164
155
  if (status >= 500) return "server_error";
165
156
  return "unknown";
@@ -171,6 +162,12 @@ function mapWhatsAppCloudError(status, body) {
171
162
  const code = cloudErrorCode(status, errCode);
172
163
  if (code === "auth_failed") return { code, message: `Bearer token rejected: ${errMsg}` };
173
164
  if (code === "rate_limit") return { code, message: `Throttled: ${errMsg}` };
165
+ if (code === "session_window_expired") {
166
+ return {
167
+ code,
168
+ message: `Outside the 24-hour service window \u2014 send an approved template instead: ${errMsg}`
169
+ };
170
+ }
174
171
  return { code, message: errMsg };
175
172
  }
176
173
  function mapWhatsAppWebError(ipcError) {
@@ -190,6 +187,398 @@ function mapWhatsAppWebError(ipcError) {
190
187
  return { code: "unknown", message: msg };
191
188
  }
192
189
 
190
+ // src/backend/baileys/socket.ts
191
+ function member(mod, name) {
192
+ const asDefault = mod.default;
193
+ const fromDefault = asDefault !== void 0 && typeof asDefault === "object" ? asDefault[name] : void 0;
194
+ return fromDefault ?? mod[name];
195
+ }
196
+ async function createBaileysSocket(opts) {
197
+ const specifier = opts.specifier ?? "baileys";
198
+ let mod;
199
+ try {
200
+ mod = await import(
201
+ /* @vite-ignore */
202
+ specifier
203
+ );
204
+ } catch (err) {
205
+ throw new ConfigurationError({
206
+ code: "peer_missing",
207
+ message: `gateway-whatsapp: ${specifier} is not installed. Run \`pnpm add baileys\` to use the baileys backend. (${err instanceof Error ? err.message : String(err)})`
208
+ });
209
+ }
210
+ const makeSocket = member(
211
+ mod,
212
+ "makeWASocket"
213
+ );
214
+ const useAuthState = member(mod, "useMultiFileAuthState");
215
+ const fetchVersion = member(
216
+ mod,
217
+ "fetchLatestBaileysVersion"
218
+ );
219
+ for (const [name, value] of [
220
+ ["makeWASocket", makeSocket],
221
+ ["useMultiFileAuthState", useAuthState]
222
+ ]) {
223
+ if (typeof value !== "function") {
224
+ throw new ConfigurationError({
225
+ code: "peer_incompatible",
226
+ 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.`
227
+ });
228
+ }
229
+ }
230
+ const { state, saveCreds } = await useAuthState(opts.sessionDir);
231
+ const version = typeof fetchVersion === "function" ? (await fetchVersion()).version : void 0;
232
+ const socket = makeSocket({
233
+ auth: state,
234
+ printQRInTerminal: false,
235
+ markOnlineOnConnect: false,
236
+ syncFullHistory: false,
237
+ browser: ["theokit-gateway", "chrome", "1.0.0"],
238
+ ...version !== void 0 ? { version } : {}
239
+ });
240
+ const onQr = opts.onQr ?? ((qr) => {
241
+ process.stderr.write(
242
+ `
243
+ [whatsapp-baileys] Scan this QR with WhatsApp \u2014 Settings, Linked devices, Link a device:
244
+ ${qr}
245
+
246
+ `
247
+ );
248
+ });
249
+ socket.ev.on("connection.update", (update) => {
250
+ if (typeof update.qr === "string" && update.qr.length > 0) onQr(update.qr);
251
+ });
252
+ socket.ev.on("creds.update", () => {
253
+ void saveCreds().catch((err) => {
254
+ const message = err instanceof Error ? err.message : String(err);
255
+ process.stderr.write(`[whatsapp-baileys] could not persist credentials: ${message}
256
+ `);
257
+ });
258
+ });
259
+ return socket;
260
+ }
261
+
262
+ // src/backend/baileys/index.ts
263
+ function endQuietly(socket) {
264
+ try {
265
+ socket.end?.();
266
+ } catch {
267
+ }
268
+ }
269
+ var DEFAULT_CONNECT_TIMEOUT_MS = 6e4;
270
+ var DEFAULT_SEND_TIMEOUT_MS = 3e4;
271
+ var WhatsAppBaileysBackend = class {
272
+ constructor(opts) {
273
+ this.opts = opts;
274
+ }
275
+ opts;
276
+ kind = "baileys";
277
+ socket;
278
+ connected = false;
279
+ /** Guards a concurrent second `connect()` from opening a second live session. */
280
+ connecting;
281
+ /**
282
+ * Which connection attempt is current.
283
+ *
284
+ * Bumped by every `connect()` and every `disconnect()`. A socket from a superseded attempt
285
+ * checks it before touching any state, which is what stops an abandoned socket delivering
286
+ * inbound or flipping `connected` under a live one.
287
+ */
288
+ generation = 0;
289
+ /**
290
+ * How to end a connection attempt that is still awaiting `open`.
291
+ *
292
+ * Retirement by generation makes an attempt's listeners silent, which is not the same as
293
+ * making the attempt finish. One entry per in-flight attempt; `disconnect()` calls them so
294
+ * the attempt settles now instead of at its timeout.
295
+ */
296
+ pendingAttempts = /* @__PURE__ */ new Set();
297
+ /**
298
+ * Why the socket last closed, as Baileys reported it.
299
+ *
300
+ * Kept because `connect()` returning `false` cannot distinguish a network blip from a
301
+ * session the operator unlinked from their phone — and only one of those is worth retrying.
302
+ * `rules/error-handling.md` § 3: fail clear, and log with enough context to act.
303
+ */
304
+ lastCloseError;
305
+ inboundHandler;
306
+ statusHandler;
307
+ /**
308
+ * Serialises outbound sends (ADR D320).
309
+ *
310
+ * Both peer gateways studied do this, and one records that concurrent sends on a single
311
+ * socket can misdeliver to the wrong chat. We have NOT measured that in our own code — we
312
+ * have never run a Baileys socket — so this is precaution rather than a reproduction of our
313
+ * own bug, and saying so is the point. It is kept because the cost is one promise chain and
314
+ * the failure it guards against is a message delivered to the wrong person.
315
+ */
316
+ sendQueue = Promise.resolve();
317
+ /**
318
+ * Open the socket and wait for it to report `open`.
319
+ *
320
+ * Idempotent, and safe against a concurrent second call: the in-flight promise is shared
321
+ * rather than a second socket being built. WhatsApp's own adapter shipped without that
322
+ * guard once and opened two live sessions.
323
+ */
324
+ async connect() {
325
+ if (this.connected) return true;
326
+ if (this.connecting !== void 0) return this.connecting;
327
+ const attempt = this.openSocket();
328
+ this.connecting = attempt;
329
+ try {
330
+ return await attempt;
331
+ } finally {
332
+ if (this.connecting === attempt) this.connecting = void 0;
333
+ }
334
+ }
335
+ /** @internal */
336
+ async openSocket() {
337
+ const generation = ++this.generation;
338
+ const socket = await this.buildSocket();
339
+ const isCurrent = () => this.generation === generation;
340
+ if (!isCurrent()) {
341
+ endQuietly(socket);
342
+ return false;
343
+ }
344
+ this.subscribeInbound(socket, isCurrent);
345
+ const timeoutMs = this.opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
346
+ const openedOk = await this.raceOpen(socket, isCurrent, timeoutMs);
347
+ if (!isCurrent()) {
348
+ endQuietly(socket);
349
+ return false;
350
+ }
351
+ if (!openedOk) {
352
+ this.reportConnectFailure(timeoutMs);
353
+ this.generation += 1;
354
+ endQuietly(socket);
355
+ this.socket = void 0;
356
+ this.connected = false;
357
+ return false;
358
+ }
359
+ if (this.socket !== void 0 && this.socket !== socket) endQuietly(this.socket);
360
+ this.socket = socket;
361
+ this.connected = true;
362
+ return true;
363
+ }
364
+ /** Build a socket through the injected factory, or the real one. @internal */
365
+ async buildSocket() {
366
+ const factory = this.opts.socketFactory ?? createBaileysSocket;
367
+ return factory({
368
+ sessionDir: this.opts.sessionDir,
369
+ ...this.opts.onQr !== void 0 ? { onQr: this.opts.onQr } : {}
370
+ });
371
+ }
372
+ /** Route this socket's inbound batches into the handler, while it is still current. @internal */
373
+ subscribeInbound(socket, isCurrent) {
374
+ socket.ev.on("messages.upsert", (payload) => {
375
+ if (payload.type !== void 0 && payload.type !== "notify") return;
376
+ if (!isCurrent()) return;
377
+ for (const raw of payload.messages ?? []) this.dispatchInbound(raw);
378
+ });
379
+ }
380
+ /**
381
+ * Wait for this socket to report `open`, or for something to end the attempt.
382
+ *
383
+ * Three things can settle it: the socket opens, the socket closes, or the timeout fires — and
384
+ * a fourth, `disconnect()`, reaches it through `pendingAttempts`. That last one is why the
385
+ * resolver is registered rather than merely closed over: retiring an attempt by generation
386
+ * makes its listeners no-ops, INCLUDING the one that would settle this, so without a way in
387
+ * from outside the only thing left able to finish it was the timeout.
388
+ *
389
+ * @internal
390
+ */
391
+ async raceOpen(socket, isCurrent, timeoutMs) {
392
+ let settle = () => void 0;
393
+ const opened = new Promise((resolve2) => {
394
+ settle = resolve2;
395
+ });
396
+ const abandon = () => settle(false);
397
+ this.pendingAttempts.add(abandon);
398
+ socket.ev.on("connection.update", (update) => {
399
+ if (!isCurrent()) return;
400
+ if (update.connection === "open") {
401
+ settle(true);
402
+ return;
403
+ }
404
+ if (update.connection !== "close") return;
405
+ this.lastCloseError = update.lastDisconnect?.error;
406
+ this.connected = false;
407
+ if (this.socket === socket) this.socket = void 0;
408
+ endQuietly(socket);
409
+ settle(false);
410
+ });
411
+ const timer = setTimeout(() => settle(false), timeoutMs);
412
+ try {
413
+ return await opened;
414
+ } finally {
415
+ clearTimeout(timer);
416
+ this.pendingAttempts.delete(abandon);
417
+ }
418
+ }
419
+ /**
420
+ * Say why the connection did not open.
421
+ *
422
+ * A bare `false` tells an operator nothing, and the two causes want opposite responses: a
423
+ * blip is worth retrying, an unlinked device can only be fixed by re-pairing, and a
424
+ * supervisor that cannot tell them apart retries forever against a dead session.
425
+ *
426
+ * @internal
427
+ */
428
+ reportConnectFailure(timeoutMs) {
429
+ const error = this.lastCloseError;
430
+ const cause = error === void 0 ? `no 'open' within ${timeoutMs}ms` : error instanceof Error ? error.message : String(error);
431
+ process.stderr.write(`[whatsapp-baileys] connect failed: ${cause}
432
+ `);
433
+ }
434
+ /** Close the socket. Idempotent, and safe when never connected. */
435
+ async disconnect() {
436
+ this.generation += 1;
437
+ this.connected = false;
438
+ this.connecting = void 0;
439
+ for (const abandon of this.pendingAttempts) abandon();
440
+ this.pendingAttempts.clear();
441
+ const socket = this.socket;
442
+ this.socket = void 0;
443
+ this.inboundHandler = void 0;
444
+ this.statusHandler = void 0;
445
+ if (socket !== void 0) endQuietly(socket);
446
+ }
447
+ /**
448
+ * Send one text message.
449
+ *
450
+ * Queued behind any send already in flight (D320), and raced against a timeout whose
451
+ * expiry reports **undetermined** delivery rather than failure (D321). A local timeout says
452
+ * the acknowledgement did not arrive, not that the message did not — so this never
453
+ * retries, because a retry after a slow ack duplicates the message.
454
+ */
455
+ async send(message) {
456
+ let settled = Promise.resolve();
457
+ const run = this.sendQueue.then(
458
+ () => {
459
+ const attempt = this.sendNow(message);
460
+ settled = attempt.inFlight;
461
+ return attempt.result;
462
+ },
463
+ () => {
464
+ const attempt = this.sendNow(message);
465
+ settled = attempt.inFlight;
466
+ return attempt.result;
467
+ }
468
+ );
469
+ this.sendQueue = run.then(
470
+ () => settled.catch(() => void 0),
471
+ () => settled.catch(() => void 0)
472
+ );
473
+ return run;
474
+ }
475
+ /**
476
+ * Race one send against the send timeout.
477
+ *
478
+ * Separated so `sendNow` reads as the three outcomes it has — delivered, undetermined,
479
+ * refused — rather than as promise plumbing.
480
+ *
481
+ * @internal
482
+ */
483
+ async raceSend(inFlight, timeoutMs) {
484
+ let timer;
485
+ const timeout = new Promise((resolve2) => {
486
+ timer = setTimeout(() => resolve2("timeout"), timeoutMs);
487
+ });
488
+ try {
489
+ return await Promise.race([inFlight, timeout]);
490
+ } finally {
491
+ if (timer !== void 0) clearTimeout(timer);
492
+ }
493
+ }
494
+ /**
495
+ * One send attempt.
496
+ *
497
+ * Returns two promises deliberately. `result` is what the caller is told — it settles on
498
+ * the timeout. `inFlight` settles when the socket is actually free again, which is what the
499
+ * queue must wait for: a timeout does not cancel `sendMessage`, so releasing the queue on
500
+ * the timeout would put two sends on one socket.
501
+ *
502
+ * @internal
503
+ */
504
+ sendNow(message) {
505
+ const socket = this.socket;
506
+ if (!this.connected || socket === void 0) {
507
+ return {
508
+ result: Promise.resolve({
509
+ ok: false,
510
+ error: { code: "server_error", message: "Baileys backend is not connected." }
511
+ }),
512
+ inFlight: Promise.resolve()
513
+ };
514
+ }
515
+ const jid = `${message.to}@${message.isGroup ? "g.us" : "s.whatsapp.net"}`;
516
+ const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;
517
+ const inFlight = socket.sendMessage(jid, { text: message.text });
518
+ const result = this.raceSend(inFlight, timeoutMs).then((outcome) => {
519
+ if (outcome === "timeout") {
520
+ return {
521
+ ok: false,
522
+ error: {
523
+ code: "timeout",
524
+ message: `No acknowledgement after ${timeoutMs}ms \u2014 delivery is undetermined. Not retried: the message may already have been delivered.`
525
+ }
526
+ };
527
+ }
528
+ const wamid = outcome?.key?.id;
529
+ return wamid !== void 0 ? { ok: true, wamid } : { ok: true };
530
+ }).catch((err) => ({
531
+ ok: false,
532
+ error: {
533
+ code: "server_error",
534
+ message: err instanceof Error ? err.message : String(err)
535
+ }
536
+ }));
537
+ return { result, inFlight };
538
+ }
539
+ /** Subscribe to inbound events. EC-H: a second call REPLACES the first. */
540
+ onInbound(handler) {
541
+ this.inboundHandler = handler;
542
+ return () => {
543
+ if (this.inboundHandler === handler) this.inboundHandler = void 0;
544
+ };
545
+ }
546
+ /**
547
+ * Subscribe to delivery receipts. EC-H: a second call REPLACES the first.
548
+ *
549
+ * Declared for the interface; Baileys reports receipts on `messages.update`, which v1 does
550
+ * not consume. Registering a handler is accepted and it is never called — stated here
551
+ * rather than left for a consumer to discover from silence.
552
+ */
553
+ onStatusReceipt(handler) {
554
+ this.statusHandler = handler;
555
+ return () => {
556
+ if (this.statusHandler === handler) this.statusHandler = void 0;
557
+ };
558
+ }
559
+ /**
560
+ * Normalise one envelope and hand it to the handler.
561
+ *
562
+ * The promise is floated because the Baileys listener is synchronous — but with a `catch`,
563
+ * because a bare `void` on a rejecting promise ends the process under Node's default, which
564
+ * is what killed two adapters in this package (#41). A handler is user code; its failure is
565
+ * named as the handler's and delivery continues.
566
+ *
567
+ * @internal
568
+ */
569
+ dispatchInbound(raw) {
570
+ const handler = this.inboundHandler;
571
+ if (handler === void 0) return;
572
+ const event = normalizeBaileysMessage(raw);
573
+ if (event === void 0) return;
574
+ void handler(event).catch((err) => {
575
+ const message = err instanceof Error ? err.message : String(err);
576
+ process.stderr.write(`[whatsapp-baileys] handler threw: ${message}
577
+ `);
578
+ });
579
+ }
580
+ };
581
+
193
582
  // src/backend/cloud/client.ts
194
583
  var WhatsAppCloudClient = class {
195
584
  constructor(opts) {
@@ -215,6 +604,44 @@ var WhatsAppCloudClient = class {
215
604
  type: "text",
216
605
  text: { body, preview_url: false }
217
606
  };
607
+ return this.postMessage(req);
608
+ }
609
+ /**
610
+ * Send an approved template.
611
+ *
612
+ * The only message type Meta accepts outside the 24-hour service window, and so the only way to
613
+ * reach someone who has not written first — every notification, and every unattended check of
614
+ * whether this integration still works. Free-form text to a cold recipient is refused with
615
+ * `131047`, which the error mapper now surfaces as `session_window_expired`.
616
+ *
617
+ * `components` is omitted from the payload when absent rather than sent empty: Meta rejects
618
+ * `components: []` on a template that declares no variables, so the two are not equivalent.
619
+ *
620
+ * Deliberately NOT on the `WhatsAppBackend` interface. The web backend drives WhatsApp Web,
621
+ * which has no concept of templates, and widening the shared contract would hand it a method it
622
+ * can only throw from.
623
+ */
624
+ async sendTemplate(to, templateName, languageCode, components) {
625
+ const req = {
626
+ messaging_product: "whatsapp",
627
+ recipient_type: "individual",
628
+ to,
629
+ type: "template",
630
+ template: {
631
+ name: templateName,
632
+ language: { code: languageCode },
633
+ ...components !== void 0 && components.length > 0 ? { components } : {}
634
+ }
635
+ };
636
+ return this.postMessage(req);
637
+ }
638
+ /**
639
+ * POST one message envelope and turn Meta's answer into a `WhatsAppSendResult`.
640
+ *
641
+ * Shared by every send: how to reach the endpoint, how to authenticate, and how to read the
642
+ * reply is one piece of knowledge, and it was about to have a second copy.
643
+ */
644
+ async postMessage(req) {
218
645
  let response;
219
646
  try {
220
647
  response = await this.fetchImpl(`${this.baseUrl}/messages`, {
@@ -389,16 +816,34 @@ var WhatsAppCloudBackend = class {
389
816
  async send(message) {
390
817
  return this.client.sendText(message.to, message.text, message.isGroup);
391
818
  }
819
+ /**
820
+ * Send an approved template to `to`.
821
+ *
822
+ * Cloud-only, and deliberately absent from the `WhatsAppBackend` interface: WhatsApp Web has no
823
+ * concept of templates, so putting this on the shared contract would hand the web backend a
824
+ * method it could only throw from. A consumer reaches it by holding the backend directly.
825
+ *
826
+ * This is the only way to message someone outside the 24-hour service window — every
827
+ * notification, and every unattended check that this integration still works. Free-form text to
828
+ * a cold recipient comes back as `session_window_expired`.
829
+ *
830
+ * @param templateName Name of a template already approved on the WhatsApp Business account.
831
+ * @param languageCode Locale of the approved template, e.g. `en_US`, `pt_BR`.
832
+ * @param components Values for the template's variables; omit for a template that takes none.
833
+ */
834
+ async sendTemplate(to, templateName, languageCode, components) {
835
+ return this.client.sendTemplate(to, templateName, languageCode, components);
836
+ }
392
837
  onInbound(handler) {
393
838
  this.inboundHandler = handler;
394
839
  return () => {
395
- this.inboundHandler = void 0;
840
+ if (this.inboundHandler === handler) this.inboundHandler = void 0;
396
841
  };
397
842
  }
398
843
  onStatusReceipt(handler) {
399
844
  this.statusHandler = handler;
400
845
  return () => {
401
- this.statusHandler = void 0;
846
+ if (this.statusHandler === handler) this.statusHandler = void 0;
402
847
  };
403
848
  }
404
849
  /**
@@ -412,25 +857,52 @@ var WhatsAppCloudBackend = class {
412
857
  if (!verifyWebhookSignature(rawBody, signatureHeader, this.appSecret)) {
413
858
  return false;
414
859
  }
415
- const json = JSON.parse(
416
- typeof rawBody === "string" ? rawBody : rawBody.toString("utf8")
417
- );
860
+ const json = this.parseBody(rawBody);
861
+ if (json === void 0) return false;
418
862
  const envelope = parseWebhookPayload(json);
419
863
  if (envelope === null) return true;
420
- const inbounds = normalizeInboundMessages(envelope);
421
- for (const event of inbounds) {
422
- if (this.inboundHandler !== void 0) {
423
- await this.inboundHandler(event);
424
- }
864
+ for (const event of normalizeInboundMessages(envelope)) {
865
+ if (this.inboundHandler === void 0) continue;
866
+ await this.dispatchContained(() => this.inboundHandler?.(event), "handler");
425
867
  }
426
- const statuses = normalizeStatusReceipts(envelope);
427
- for (const receipt of statuses) {
428
- if (this.statusHandler !== void 0) {
429
- await this.statusHandler(receipt);
430
- }
868
+ for (const receipt of normalizeStatusReceipts(envelope)) {
869
+ if (this.statusHandler === void 0) continue;
870
+ await this.dispatchContained(() => this.statusHandler?.(receipt), "status handler");
431
871
  }
432
872
  return true;
433
873
  }
874
+ /**
875
+ * Parse a signed webhook body, or report `undefined` when it is not JSON.
876
+ *
877
+ * The method's contract is true/false; the route calling it has no reason to expect a throw.
878
+ */
879
+ parseBody(rawBody) {
880
+ try {
881
+ return JSON.parse(typeof rawBody === "string" ? rawBody : rawBody.toString("utf8"));
882
+ } catch (err) {
883
+ const m = err instanceof Error ? err.message : String(err);
884
+ process.stderr.write(`[whatsapp-cloud] webhook body is not JSON: ${m}
885
+ `);
886
+ return void 0;
887
+ }
888
+ }
889
+ /**
890
+ * Run one user callback and contain its failure.
891
+ *
892
+ * Meta batches several messages, and their delivery receipts, into a single webhook. Awaiting a
893
+ * handler with nothing around it made one throw skip every remaining message in the payload —
894
+ * and reject `handleWebhookPayload`, so the caller's route answered 500 and Meta redelivered the
895
+ * whole batch, replaying the messages that HAD succeeded (#41).
896
+ */
897
+ async dispatchContained(run, what) {
898
+ try {
899
+ await run();
900
+ } catch (err) {
901
+ const m = err instanceof Error ? err.message : String(err);
902
+ process.stderr.write(`[whatsapp-cloud] ${what} threw: ${m}
903
+ `);
904
+ }
905
+ }
434
906
  };
435
907
 
436
908
  // src/backend/web/ipc.ts
@@ -469,10 +941,10 @@ var LineBuffer = class {
469
941
  };
470
942
  var BRIDGE_PROCESS_TAG = "whatsapp-web-bridge";
471
943
  function pidFilePath(theokitHome, sessionId) {
472
- return path.join(theokitHome, `whatsapp-bridge-${sessionId}.pid`);
944
+ return path2.join(theokitHome, `whatsapp-bridge-${sessionId}.pid`);
473
945
  }
474
946
  function defaultTheokitHome() {
475
- return process.env.THEOKIT_HOME ?? path.join(process.env.HOME ?? "/tmp", ".theokit");
947
+ return process.env.THEOKIT_HOME ?? path2.join(process.env.HOME ?? "/tmp", ".theokit");
476
948
  }
477
949
  function pidBelongsToOurBridge(pid) {
478
950
  try {
@@ -575,8 +1047,8 @@ function waitForExit(child, timeoutMs) {
575
1047
  }
576
1048
 
577
1049
  // src/backend/web/index.ts
578
- var DEFAULT_CONNECT_TIMEOUT_MS = 12e4;
579
- var DEFAULT_SEND_TIMEOUT_MS = 3e4;
1050
+ var DEFAULT_CONNECT_TIMEOUT_MS2 = 12e4;
1051
+ var DEFAULT_SEND_TIMEOUT_MS2 = 3e4;
580
1052
  var WhatsAppWebBackend = class {
581
1053
  constructor(opts) {
582
1054
  this.opts = opts;
@@ -588,6 +1060,8 @@ var WhatsAppWebBackend = class {
588
1060
  inboundHandler;
589
1061
  statusHandler;
590
1062
  pending = /* @__PURE__ */ new Map();
1063
+ /** Rejects an in-flight `connect()` when the bridge reports it cannot start. */
1064
+ connectRejectors = [];
591
1065
  msgIdCounter = 0;
592
1066
  botPhone;
593
1067
  connected = false;
@@ -620,22 +1094,27 @@ var WhatsAppWebBackend = class {
620
1094
  if (this.connected) return true;
621
1095
  this.handle = this.spawnBridgeHandle();
622
1096
  this.wireStdout();
623
- const timeoutMs = this.opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
624
- const ready = new Promise((resolve2) => this.readyResolvers.push(resolve2));
1097
+ const timeoutMs = this.opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS2;
1098
+ const ready = new Promise((resolve2, reject) => {
1099
+ this.readyResolvers.push(resolve2);
1100
+ this.connectRejectors.push(reject);
1101
+ });
625
1102
  let timer;
626
1103
  const timeout = new Promise((_resolve, reject) => {
627
1104
  timer = setTimeout(() => reject(new WhatsAppConnectTimeoutError(timeoutMs)), timeoutMs);
628
1105
  });
629
1106
  try {
630
1107
  const phone = await Promise.race([ready, timeout]);
631
- if (timer !== void 0) clearTimeout(timer);
632
1108
  this.botPhone = phone;
633
1109
  this.connected = true;
634
1110
  return true;
635
1111
  } catch (err) {
636
- if (timer !== void 0) clearTimeout(timer);
637
1112
  await this.cleanupHandle();
638
1113
  throw err;
1114
+ } finally {
1115
+ if (timer !== void 0) clearTimeout(timer);
1116
+ this.readyResolvers = [];
1117
+ this.connectRejectors = [];
639
1118
  }
640
1119
  }
641
1120
  async disconnect() {
@@ -655,13 +1134,14 @@ var WhatsAppWebBackend = class {
655
1134
  }
656
1135
  this.pending.clear();
657
1136
  this.readyResolvers = [];
1137
+ this.connectRejectors = [];
658
1138
  }
659
1139
  async send(message) {
660
1140
  if (!this.connected || this.handle === void 0 || this.handle.child.stdin === null) {
661
1141
  return { ok: false, error: { code: "server_error", message: "Bridge not connected." } };
662
1142
  }
663
1143
  const msgId = `out-${++this.msgIdCounter}`;
664
- const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;
1144
+ const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS2;
665
1145
  return new Promise((resolve2) => {
666
1146
  const timer = setTimeout(() => {
667
1147
  this.pending.delete(msgId);
@@ -688,13 +1168,13 @@ var WhatsAppWebBackend = class {
688
1168
  onInbound(handler) {
689
1169
  this.inboundHandler = handler;
690
1170
  return () => {
691
- this.inboundHandler = void 0;
1171
+ if (this.inboundHandler === handler) this.inboundHandler = void 0;
692
1172
  };
693
1173
  }
694
1174
  onStatusReceipt(handler) {
695
1175
  this.statusHandler = handler;
696
1176
  return () => {
697
- this.statusHandler = void 0;
1177
+ if (this.statusHandler === handler) this.statusHandler = void 0;
698
1178
  };
699
1179
  }
700
1180
  handleReady(event) {
@@ -714,7 +1194,27 @@ var WhatsAppWebBackend = class {
714
1194
  backend: "web",
715
1195
  raw: event
716
1196
  };
717
- void this.inboundHandler(normalized);
1197
+ void this.inboundHandler(normalized).catch((err) => {
1198
+ const m = err instanceof Error ? err.message : String(err);
1199
+ process.stderr.write(`[whatsapp-web] handler threw: ${m}
1200
+ `);
1201
+ });
1202
+ }
1203
+ /**
1204
+ * A bridge that reported a failure has failed — say so now, not in two minutes.
1205
+ *
1206
+ * This used to write the message to stderr and return. `connect()` races only the `ready`
1207
+ * promise against the timeout, so a bridge that told us exactly what was wrong and exited
1208
+ * still cost the caller the full `connectTimeoutMs` and surfaced as a timeout — the one
1209
+ * error that carries no information. The diagnosis was printed where nothing could act on
1210
+ * it, which is the swallowing `rules/error-handling.md` § 5 names.
1211
+ */
1212
+ handleBridgeError(event) {
1213
+ process.stderr.write(`[whatsapp-web bridge] ${event.message}
1214
+ `);
1215
+ const failure = new WhatsAppBridgeError(event.message, event.code);
1216
+ for (const reject of this.connectRejectors) reject(failure);
1217
+ this.connectRejectors = [];
718
1218
  }
719
1219
  handleSendAck(event) {
720
1220
  const pending = this.pending.get(event.msgId);
@@ -734,6 +1234,10 @@ var WhatsAppWebBackend = class {
734
1234
  status: event.status,
735
1235
  recipient: event.recipient,
736
1236
  timestamp: event.timestamp || Date.now()
1237
+ }).catch((err) => {
1238
+ const m = err instanceof Error ? err.message : String(err);
1239
+ process.stderr.write(`[whatsapp-web] status handler threw: ${m}
1240
+ `);
737
1241
  });
738
1242
  }
739
1243
  dispatch(event) {
@@ -751,19 +1255,315 @@ var WhatsAppWebBackend = class {
751
1255
  this.handleStatus(event);
752
1256
  return;
753
1257
  case "error":
754
- process.stderr.write(`[whatsapp-web bridge] ${event.message}
755
- `);
1258
+ this.handleBridgeError(event);
756
1259
  return;
757
1260
  }
758
1261
  }
759
1262
  };
760
1263
  function defaultBridgeScriptPath() {
761
- return path.resolve(
762
- path.dirname(new URL(import.meta.url).pathname),
763
- "../../bridge/whatsapp-web-bridge.mjs"
764
- );
1264
+ const here = path2.dirname(fileURLToPath(import.meta.url));
1265
+ const candidates = [
1266
+ // Bundled: dist/index.js beside dist/bridge/
1267
+ path2.resolve(here, "bridge/whatsapp-web-bridge.mjs"),
1268
+ // Source: src/backend/web/index.ts up two to src/
1269
+ path2.resolve(here, "../../bridge/whatsapp-web-bridge.mjs")
1270
+ ];
1271
+ const found = candidates.find((candidate) => existsSync(candidate));
1272
+ if (found === void 0) {
1273
+ throw new WhatsAppBridgeError(
1274
+ `bridge script not found. Looked in: ${candidates.join(", ")}. Pass \`bridgeScriptPath\` explicitly if the package layout differs.`,
1275
+ "bridge_script_missing"
1276
+ );
1277
+ }
1278
+ return found;
765
1279
  }
1280
+ var WHATSAPP_MAX_TEXT = 4096;
1281
+ function splitForWhatsApp(text) {
1282
+ return chunkText(text, {
1283
+ limit: WHATSAPP_MAX_TEXT,
1284
+ boundaries: ["\n\n", "\n", " "],
1285
+ lastResort: "last-boundary",
1286
+ surrogateGuard: true,
1287
+ stripLeading: /^\s+/,
1288
+ trimParts: true
1289
+ });
1290
+ }
1291
+
1292
+ // src/adapter.ts
1293
+ function requireNonEmpty(entries) {
1294
+ for (const [name, value] of entries) {
1295
+ if (value === void 0 || value.trim().length === 0) {
1296
+ throw new ConfigurationError({
1297
+ code: "missing_option",
1298
+ message: `gateway-whatsapp: ${name} is required and must not be empty.`
1299
+ });
1300
+ }
1301
+ }
1302
+ }
1303
+ function digitsOnly(s) {
1304
+ return s.replace(/[^\d]/g, "");
1305
+ }
1306
+ var PHONE_RUN = /[\d][\d+\-().  ]*[\d]|[\d]/g;
1307
+ function phoneRuns(s) {
1308
+ return (s.match(PHONE_RUN) ?? []).map(digitsOnly).filter((d) => d.length > 0);
1309
+ }
1310
+ var WhatsAppAdapter = class _WhatsAppAdapter extends BasePlatformAdapter {
1311
+ platform = "whatsapp";
1312
+ backendImpl;
1313
+ requireMention;
1314
+ botPhoneId;
1315
+ /** `undefined` = no allowlist configured; a set = configured, and enforced fail-closed. */
1316
+ allowedSenders;
1317
+ /** Mirrors the sibling adapters: guards connect() against opening a second session. */
1318
+ connected = false;
1319
+ handler;
1320
+ statusHandler;
1321
+ // EC-H: track unsubscribe handles so onInbound REPLACES instead of stacks.
1322
+ inboundUnsubscribe;
1323
+ statusUnsubscribe;
1324
+ /**
1325
+ * Build an adapter from a discriminated configuration.
1326
+ *
1327
+ * The entry point for configuration that arrives as **data** — read from a file, an
1328
+ * environment, or a tenant record — where the backend is a string rather than a decision
1329
+ * made in code. `fromCloud` / `fromWeb` are the direct forms when the choice is already
1330
+ * known at the call site.
1331
+ *
1332
+ * This is what `WhatsAppAdapterOptions` exists for. Until it had this consumer the union
1333
+ * was exported, documented and inert, which is the defect #47 was filed about, and the
1334
+ * first attempt at closing that issue left it inert — the factories took the config halves
1335
+ * directly and never the union.
1336
+ *
1337
+ * @throws {ConfigurationError} when a required option is missing or empty.
1338
+ * @public
1339
+ */
1340
+ static from(options, common = {}) {
1341
+ switch (options.backend) {
1342
+ case "cloud":
1343
+ return _WhatsAppAdapter.fromCloud(options.cloud, common);
1344
+ case "web":
1345
+ return _WhatsAppAdapter.fromWeb(options.web, common);
1346
+ case "baileys":
1347
+ return _WhatsAppAdapter.fromBaileys(options.baileys, common);
1348
+ }
1349
+ }
1350
+ /**
1351
+ * Build a Baileys adapter.
1352
+ *
1353
+ * Unofficial, and no amount of code changes that: it automates a WhatsApp Web session,
1354
+ * which Meta's terms do not sanction and which can get a number banned. Use a number
1355
+ * created for this, never a personal one. Prefer {@link WhatsAppAdapter.fromCloud} unless
1356
+ * the number has no Cloud API access.
1357
+ *
1358
+ * Unlike {@link WhatsAppAdapter.fromWeb} it embeds no browser — it speaks the multi-device
1359
+ * protocol over a WebSocket. `baileys` is an optional peer dependency; it is loaded lazily
1360
+ * at connect, so a consumer who never calls this never needs it installed.
1361
+ *
1362
+ * `botPhoneId` has nothing to default from here, so leaving it unset while `requireMention`
1363
+ * is on (its default) drops every group message. The adapter logs when it does.
1364
+ *
1365
+ * @throws {ConfigurationError} when `sessionDir` is missing or empty.
1366
+ * @public
1367
+ */
1368
+ static fromBaileys(baileys, opts = {}) {
1369
+ requireNonEmpty([["sessionDir", baileys.sessionDir]]);
1370
+ return new _WhatsAppAdapter(
1371
+ new WhatsAppBaileysBackend({
1372
+ sessionDir: baileys.sessionDir,
1373
+ ...baileys.connectTimeoutMs !== void 0 ? { connectTimeoutMs: baileys.connectTimeoutMs } : {},
1374
+ ...baileys.sendTimeoutMs !== void 0 ? { sendTimeoutMs: baileys.sendTimeoutMs } : {},
1375
+ ...baileys.onQr !== void 0 ? { onQr: baileys.onQr } : {}
1376
+ }),
1377
+ opts
1378
+ );
1379
+ }
1380
+ /**
1381
+ * Build a Cloud-API adapter.
1382
+ *
1383
+ * The construction path this package's docblock has named since it was written, and which
1384
+ * did not exist until #47 — a consumer following the only guidance the package gave wrote
1385
+ * code that would not compile.
1386
+ *
1387
+ * Prefer it over the constructor: it keeps `WhatsAppCloudBackend` an implementation detail
1388
+ * of this package rather than something every consumer imports and assembles.
1389
+ *
1390
+ * @throws {ConfigurationError} when a required credential is missing or empty.
1391
+ * @public
1392
+ */
1393
+ static fromCloud(cloud, opts = {}) {
1394
+ requireNonEmpty([
1395
+ ["accessToken", cloud.accessToken],
1396
+ ["phoneNumberId", cloud.phoneNumberId]
1397
+ ]);
1398
+ if (cloud.apiVersion !== void 0) {
1399
+ requireNonEmpty([["apiVersion", cloud.apiVersion]]);
1400
+ }
1401
+ return new _WhatsAppAdapter(
1402
+ new WhatsAppCloudBackend({
1403
+ accessToken: cloud.accessToken,
1404
+ phoneNumberId: cloud.phoneNumberId,
1405
+ appSecret: cloud.appSecret,
1406
+ ...cloud.apiVersion !== void 0 ? { apiVersion: cloud.apiVersion } : {}
1407
+ }),
1408
+ { ...opts, botPhoneId: opts.botPhoneId ?? cloud.phoneNumberId }
1409
+ );
1410
+ }
1411
+ /**
1412
+ * Build a WhatsApp-Web adapter.
1413
+ *
1414
+ * Unofficial: it drives a real WhatsApp Web session through a browser, which Meta's terms
1415
+ * do not sanction and which can get a number banned. It also needs a browser this package
1416
+ * does not install. Prefer {@link WhatsAppAdapter.fromCloud} unless the number has no
1417
+ * Cloud API access.
1418
+ *
1419
+ * @throws {ConfigurationError} when `sessionId` is missing or empty.
1420
+ * @public
1421
+ */
1422
+ static fromWeb(web, opts = {}) {
1423
+ requireNonEmpty([["sessionId", web.sessionId]]);
1424
+ return new _WhatsAppAdapter(
1425
+ new WhatsAppWebBackend({
1426
+ sessionId: web.sessionId,
1427
+ ...web.bridgeScriptPath !== void 0 ? { bridgeScriptPath: web.bridgeScriptPath } : {}
1428
+ }),
1429
+ opts
1430
+ );
1431
+ }
1432
+ /** Construct from a pre-built backend. Prefer the factories; this is for tests and for a custom backend. */
1433
+ constructor(backendImpl, opts = {}) {
1434
+ super();
1435
+ this.backendImpl = backendImpl;
1436
+ this.requireMention = opts.requireMention ?? true;
1437
+ this.botPhoneId = digitsOnly(opts.botPhoneId ?? "");
1438
+ this.allowedSenders = opts.allowedSenders === void 0 ? void 0 : parseAllowedSenders(opts.allowedSenders);
1439
+ }
1440
+ /** Escape hatch (D180-style) for advanced features. */
1441
+ getBackend() {
1442
+ return this.backendImpl;
1443
+ }
1444
+ async connect() {
1445
+ if (this.connected) return true;
1446
+ const ok = await this.backendImpl.connect();
1447
+ this.connected = ok;
1448
+ return ok;
1449
+ }
1450
+ async disconnect() {
1451
+ this.connected = false;
1452
+ this.inboundUnsubscribe?.();
1453
+ this.inboundUnsubscribe = void 0;
1454
+ this.statusUnsubscribe?.();
1455
+ this.statusUnsubscribe = void 0;
1456
+ this.handler = void 0;
1457
+ this.statusHandler = void 0;
1458
+ await this.backendImpl.disconnect();
1459
+ }
1460
+ async sendMessage(out) {
1461
+ if (out.text.length === 0) {
1462
+ return { ok: false, error: { code: "empty_text", message: "Empty text rejected." } };
1463
+ }
1464
+ const parts = splitForWhatsApp(out.text);
1465
+ if (parts.length === 0) {
1466
+ return {
1467
+ ok: false,
1468
+ error: { code: "empty_text", message: "Text reduced to zero parts after splitting." }
1469
+ };
1470
+ }
1471
+ let lastWamid;
1472
+ const isGroup = out.channel.type === "group";
1473
+ for (const part of parts) {
1474
+ const r = await this.backendImpl.send({ to: out.channel.id, isGroup, text: part });
1475
+ if (!r.ok) {
1476
+ return {
1477
+ ok: false,
1478
+ error: { code: r.error?.code ?? "unknown", message: r.error?.message ?? "Send failed." }
1479
+ };
1480
+ }
1481
+ lastWamid = r.wamid;
1482
+ }
1483
+ return lastWamid !== void 0 ? { ok: true, messageId: lastWamid } : { ok: true };
1484
+ }
1485
+ /**
1486
+ * Is this sender refused by a configured allowlist?
1487
+ *
1488
+ * Runs before the group/mention filter because it answers a different question: that one asks
1489
+ * whether a message was meant for us, this one asks whether the sender may reach us at all.
1490
+ *
1491
+ * The refusal is logged. A silent drop is indistinguishable from a broken gateway, and the
1492
+ * first thing a mistyped allowlist causes is an operator wondering why the bot went mute.
1493
+ */
1494
+ isRefusedBySenderAllowlist(inbound) {
1495
+ if (this.allowedSenders === void 0) return false;
1496
+ if (isSenderAllowed(inbound.fromPhone, this.allowedSenders)) return false;
1497
+ process.stderr.write(
1498
+ `[whatsapp] dropped inbound from "${inbound.fromPhone}" \u2014 not in the configured allowlist
1499
+ `
1500
+ );
1501
+ return true;
1502
+ }
1503
+ /** D309 + EC-7: group filter with digit-only normalization. */
1504
+ shouldDropGroupMessage(inbound) {
1505
+ if (inbound.conversationType !== "group" || !this.requireMention) return false;
1506
+ if (this.botPhoneId.length === 0) {
1507
+ process.stderr.write(
1508
+ "[whatsapp] dropping every group message: requireMention is on and botPhoneId is unset\n"
1509
+ );
1510
+ return true;
1511
+ }
1512
+ return !phoneRuns(inbound.text).some((run) => run.includes(this.botPhoneId));
1513
+ }
1514
+ toMessageEvent(inbound) {
1515
+ return {
1516
+ id: inbound.wamid,
1517
+ platform: "whatsapp",
1518
+ sender: { id: inbound.fromPhone, displayName: inbound.contactName },
1519
+ channel: { id: inbound.channelId, type: inbound.conversationType },
1520
+ text: inbound.text,
1521
+ receivedAt: inbound.receivedAt,
1522
+ whatsapp: {
1523
+ wamid: inbound.wamid,
1524
+ phoneNumberId: inbound.phoneNumberId,
1525
+ contactName: inbound.contactName,
1526
+ backend: inbound.backend,
1527
+ raw: inbound.raw
1528
+ }
1529
+ };
1530
+ }
1531
+ onInbound(handler) {
1532
+ this.inboundUnsubscribe?.();
1533
+ this.handler = handler;
1534
+ const off = this.backendImpl.onInbound(async (inbound) => {
1535
+ if (!this.handler) return;
1536
+ if (this.isRefusedBySenderAllowlist(inbound)) return;
1537
+ if (this.shouldDropGroupMessage(inbound)) return;
1538
+ await this.handler(this.toMessageEvent(inbound));
1539
+ });
1540
+ this.inboundUnsubscribe = off;
1541
+ return () => {
1542
+ if (this.handler === handler) {
1543
+ this.handler = void 0;
1544
+ off();
1545
+ this.inboundUnsubscribe = void 0;
1546
+ }
1547
+ };
1548
+ }
1549
+ /** Status receipts (sent/delivered/read/failed). Adapter-specific (D307). */
1550
+ onStatusReceipt(handler) {
1551
+ this.statusUnsubscribe?.();
1552
+ this.statusHandler = handler;
1553
+ const off = this.backendImpl.onStatusReceipt(async (r) => {
1554
+ await this.statusHandler?.(r);
1555
+ });
1556
+ this.statusUnsubscribe = off;
1557
+ return () => {
1558
+ if (this.statusHandler === handler) {
1559
+ this.statusHandler = void 0;
1560
+ off();
1561
+ this.statusUnsubscribe = void 0;
1562
+ }
1563
+ };
1564
+ }
1565
+ };
766
1566
 
767
- export { LineBuffer, WhatsAppAdapter, WhatsAppCloudBackend, WhatsAppConnectTimeoutError, WhatsAppWebBackend, digitsOnly, formatCommand, mapWhatsAppCloudError, mapWhatsAppWebError, normalizeInboundMessages, normalizeStatusReceipts, parseEvent, parseWebhookPayload, splitForWhatsApp, verifyWebhookSignature, verifyWebhookSubscription };
1567
+ export { ConfigurationError, LineBuffer, WhatsAppAdapter, WhatsAppBaileysBackend, WhatsAppBridgeError, WhatsAppCloudBackend, WhatsAppConnectTimeoutError, WhatsAppWebBackend, createBaileysSocket, defaultBridgeScriptPath, digitsOnly, formatCommand, mapWhatsAppCloudError, mapWhatsAppWebError, normalizeInboundMessages, normalizeStatusReceipts, parseEvent, parseWebhookPayload, splitForWhatsApp, verifyWebhookSignature, verifyWebhookSubscription };
768
1568
  //# sourceMappingURL=index.js.map
769
1569
  //# sourceMappingURL=index.js.map