@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.js CHANGED
@@ -1,156 +1,156 @@
1
- import { chunkText, BasePlatformAdapter } from '@theokit/gateway';
1
+ import { GatewayConfigurationError, chunkText, BasePlatformAdapter } from '@theokit/gateway';
2
2
  import * as crypto from 'crypto';
3
- import * as path from 'path';
4
- import { spawn, execSync } from 'child_process';
5
3
  import * as fs from 'fs';
4
+ import { existsSync } from 'fs';
5
+ import * as path2 from 'path';
6
+ import { fileURLToPath } from 'url';
7
+ import { spawn, execSync } from 'child_process';
6
8
 
7
9
  // src/adapter.ts
8
- var WHATSAPP_MAX_TEXT = 4096;
9
- function splitForWhatsApp(text) {
10
- return chunkText(text, {
11
- limit: WHATSAPP_MAX_TEXT,
12
- boundaries: ["\n\n", "\n", " "],
13
- lastResort: "last-boundary",
14
- surrogateGuard: true,
15
- stripLeading: /^\s+/,
16
- trimParts: true
17
- });
10
+
11
+ // src/allowlist.ts
12
+ var WILDCARD = "*";
13
+ function normalizeWhatsAppId(value) {
14
+ const withoutDevice = value.replace(/:[^@]*(?=@)/, "");
15
+ const withoutDomain = withoutDevice.replace(/@.*$/, "");
16
+ return withoutDomain.replace(/\D/g, "");
17
+ }
18
+ function parseAllowedSenders(raw) {
19
+ const entries = (raw ?? "").split(",").map((entry) => entry.trim()).map((entry) => entry === WILDCARD ? WILDCARD : normalizeWhatsAppId(entry)).filter((entry) => entry.length > 0);
20
+ return new Set(entries);
21
+ }
22
+ function isSenderAllowed(senderId, allowed) {
23
+ const normalized = normalizeWhatsAppId(senderId);
24
+ if (normalized.length === 0) return false;
25
+ if (allowed.size === 0) return false;
26
+ if (allowed.has(WILDCARD)) return true;
27
+ return allowed.has(normalized);
18
28
  }
19
29
 
20
- // src/adapter.ts
21
- function digitsOnly(s) {
22
- return s.replace(/[^\d]/g, "");
30
+ // src/backend/baileys/normalize.ts
31
+ var STATUS_BROADCAST_JID = "status@broadcast";
32
+ var WRAPPER_KEYS = [
33
+ "ephemeralMessage",
34
+ "viewOnceMessage",
35
+ "viewOnceMessageV2",
36
+ "documentWithCaptionMessage"
37
+ ];
38
+ var MAX_WRAPPER_DEPTH = 3;
39
+ function asObject(value) {
40
+ return typeof value === "object" && value !== null ? value : void 0;
23
41
  }
24
- var PHONE_RUN = /[\d][\d+\-().  ]*[\d]|[\d]/g;
25
- function phoneRuns(s) {
26
- return (s.match(PHONE_RUN) ?? []).map(digitsOnly).filter((d) => d.length > 0);
42
+ function asText(value) {
43
+ return typeof value === "string" && value.length > 0 ? value : void 0;
27
44
  }
28
- var WhatsAppAdapter = class extends BasePlatformAdapter {
29
- platform = "whatsapp";
30
- backendImpl;
31
- requireMention;
32
- botPhoneId;
33
- /** Mirrors the sibling adapters: guards connect() against opening a second session. */
34
- connected = false;
35
- handler;
36
- statusHandler;
37
- // EC-H: track unsubscribe handles so onInbound REPLACES instead of stacks.
38
- inboundUnsubscribe;
39
- statusUnsubscribe;
40
- /** Construct from a pre-built backend (used by the static factories + tests). */
41
- constructor(backendImpl, opts = {}) {
42
- super();
43
- this.backendImpl = backendImpl;
44
- this.requireMention = opts.requireMention ?? true;
45
- this.botPhoneId = digitsOnly(opts.botPhoneId ?? "");
46
- }
47
- /** Escape hatch (D180-style) for advanced features. */
48
- getBackend() {
49
- return this.backendImpl;
50
- }
51
- async connect() {
52
- if (this.connected) return true;
53
- const ok = await this.backendImpl.connect();
54
- this.connected = ok;
55
- return ok;
56
- }
57
- async disconnect() {
58
- this.connected = false;
59
- this.inboundUnsubscribe?.();
60
- this.inboundUnsubscribe = void 0;
61
- this.statusUnsubscribe?.();
62
- this.statusUnsubscribe = void 0;
63
- this.handler = void 0;
64
- this.statusHandler = void 0;
65
- await this.backendImpl.disconnect();
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;
66
57
  }
67
- async sendMessage(out) {
68
- if (out.text.length === 0) {
69
- return { ok: false, error: { code: "empty_text", message: "Empty text rejected." } };
70
- }
71
- const parts = splitForWhatsApp(out.text);
72
- if (parts.length === 0) {
73
- return {
74
- ok: false,
75
- error: { code: "empty_text", message: "Text reduced to zero parts after splitting." }
76
- };
77
- }
78
- let lastWamid;
79
- const isGroup = out.channel.type === "group";
80
- for (const part of parts) {
81
- const r = await this.backendImpl.send({ to: out.channel.id, isGroup, text: part });
82
- if (!r.ok) {
83
- return {
84
- ok: false,
85
- error: { code: r.error?.code ?? "unknown", message: r.error?.message ?? "Send failed." }
86
- };
87
- }
88
- lastWamid = r.wamid;
89
- }
90
- return lastWamid !== void 0 ? { ok: true, messageId: lastWamid } : { ok: true };
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;
91
65
  }
92
- /** D309 + EC-7: group filter with digit-only normalization. */
93
- shouldDropGroupMessage(inbound) {
94
- if (inbound.conversationType !== "group" || !this.requireMention) return false;
95
- if (this.botPhoneId.length === 0) return true;
96
- return !phoneRuns(inbound.text).some((run) => run.includes(this.botPhoneId));
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;
97
70
  }
98
- toMessageEvent(inbound) {
99
- return {
100
- id: inbound.wamid,
101
- platform: "whatsapp",
102
- sender: { id: inbound.fromPhone, displayName: inbound.contactName },
103
- channel: { id: inbound.channelId, type: inbound.conversationType },
104
- text: inbound.text,
105
- receivedAt: inbound.receivedAt,
106
- whatsapp: {
107
- wamid: inbound.wamid,
108
- phoneNumberId: inbound.phoneNumberId,
109
- contactName: inbound.contactName,
110
- backend: inbound.backend,
111
- raw: inbound.raw
112
- }
113
- };
114
- }
115
- onInbound(handler) {
116
- this.inboundUnsubscribe?.();
117
- this.handler = handler;
118
- this.inboundUnsubscribe = this.backendImpl.onInbound(async (inbound) => {
119
- if (!this.handler) return;
120
- if (this.shouldDropGroupMessage(inbound)) return;
121
- await this.handler(this.toMessageEvent(inbound));
122
- });
123
- return () => {
124
- this.inboundUnsubscribe?.();
125
- this.inboundUnsubscribe = void 0;
126
- this.handler = void 0;
127
- };
71
+ return void 0;
72
+ }
73
+ function resolveParties(key, remoteJid) {
74
+ const isGroup = remoteJid.endsWith("@g.us");
75
+ const senderJid = isGroup ? asText(key.participant) : remoteJid;
76
+ if (senderJid === void 0) return void 0;
77
+ const fromPhone = normalizeWhatsAppId(senderJid);
78
+ const channelId = normalizeWhatsAppId(remoteJid);
79
+ if (fromPhone.length === 0 || channelId.length === 0) return void 0;
80
+ return { fromPhone, channelId, isGroup };
81
+ }
82
+ function isDispatchable(key, remoteJid) {
83
+ if (key.fromMe === true) return false;
84
+ return remoteJid !== STATUS_BROADCAST_JID;
85
+ }
86
+ function normalizeBaileysMessage(raw) {
87
+ const envelope = asObject(raw);
88
+ const key = envelope === void 0 ? void 0 : asObject(envelope.key);
89
+ if (key === void 0) return void 0;
90
+ const remoteJid = asText(key.remoteJid);
91
+ const wamid = asText(key.id);
92
+ if (remoteJid === void 0 || wamid === void 0) return void 0;
93
+ if (!isDispatchable(key, remoteJid)) return void 0;
94
+ const text = extractText(envelope?.message);
95
+ if (text === void 0) return void 0;
96
+ const parties = resolveParties(key, remoteJid);
97
+ if (parties === void 0) return void 0;
98
+ const seconds = toSeconds(envelope?.messageTimestamp);
99
+ if (seconds === void 0) return void 0;
100
+ const contactName = asText(envelope?.pushName);
101
+ return {
102
+ wamid,
103
+ fromPhone: parties.fromPhone,
104
+ conversationType: parties.isGroup ? "group" : "dm",
105
+ channelId: parties.channelId,
106
+ text,
107
+ receivedAt: seconds * 1e3,
108
+ backend: "baileys",
109
+ raw,
110
+ ...contactName !== void 0 ? { contactName } : {}
111
+ };
112
+ }
113
+ var ConfigurationError = class extends GatewayConfigurationError {
114
+ name = "ConfigurationError";
115
+ constructor(opts) {
116
+ super("gateway-whatsapp", opts);
128
117
  }
129
- /** Status receipts (sent/delivered/read/failed). Adapter-specific (D307). */
130
- onStatusReceipt(handler) {
131
- this.statusUnsubscribe?.();
132
- this.statusHandler = handler;
133
- this.statusUnsubscribe = this.backendImpl.onStatusReceipt(async (r) => {
134
- await this.statusHandler?.(r);
135
- });
136
- return () => {
137
- this.statusUnsubscribe?.();
138
- this.statusUnsubscribe = void 0;
139
- this.statusHandler = void 0;
140
- };
118
+ };
119
+ var WhatsAppBridgeError = class extends Error {
120
+ name = "WhatsAppBridgeError";
121
+ /** Cause as named by the bridge, when it could name one. */
122
+ code;
123
+ constructor(message, code) {
124
+ super(`WhatsApp web bridge could not start: ${message}`);
125
+ this.code = code;
141
126
  }
142
127
  };
143
-
144
- // src/errors.ts
145
128
  var WhatsAppConnectTimeoutError = class extends Error {
146
129
  constructor(timeoutMs) {
147
130
  super(`WhatsApp web bridge connect timed out after ${timeoutMs}ms (QR code not scanned?)`);
148
131
  this.name = "WhatsAppConnectTimeoutError";
149
132
  }
150
133
  };
134
+ var RATE_LIMIT_CODES = /* @__PURE__ */ new Set([
135
+ 4,
136
+ // the app reached its API call rate limit
137
+ 80007,
138
+ // the WhatsApp Business Account reached its rate limit
139
+ 130429
140
+ // Cloud API message throughput reached
141
+ ]);
142
+ var UNDELIVERABLE_CODES = /* @__PURE__ */ new Set([
143
+ 130403,
144
+ // the business has blocked this user
145
+ 131026
146
+ // no WhatsApp account, terms not accepted, or an outdated client
147
+ ]);
148
+ var SESSION_WINDOW_EXPIRED_CODE = 131047;
151
149
  function cloudErrorCode(status, errCode) {
152
150
  if (errCode === 190 || status === 401) return "auth_failed";
153
- 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";
154
154
  if (status === 400 || errCode === 100) return "invalid_request";
155
155
  if (status >= 500) return "server_error";
156
156
  return "unknown";
@@ -162,6 +162,12 @@ function mapWhatsAppCloudError(status, body) {
162
162
  const code = cloudErrorCode(status, errCode);
163
163
  if (code === "auth_failed") return { code, message: `Bearer token rejected: ${errMsg}` };
164
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
+ }
165
171
  return { code, message: errMsg };
166
172
  }
167
173
  function mapWhatsAppWebError(ipcError) {
@@ -181,6 +187,398 @@ function mapWhatsAppWebError(ipcError) {
181
187
  return { code: "unknown", message: msg };
182
188
  }
183
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
+
184
582
  // src/backend/cloud/client.ts
185
583
  var WhatsAppCloudClient = class {
186
584
  constructor(opts) {
@@ -206,6 +604,44 @@ var WhatsAppCloudClient = class {
206
604
  type: "text",
207
605
  text: { body, preview_url: false }
208
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) {
209
645
  let response;
210
646
  try {
211
647
  response = await this.fetchImpl(`${this.baseUrl}/messages`, {
@@ -380,16 +816,34 @@ var WhatsAppCloudBackend = class {
380
816
  async send(message) {
381
817
  return this.client.sendText(message.to, message.text, message.isGroup);
382
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
+ }
383
837
  onInbound(handler) {
384
838
  this.inboundHandler = handler;
385
839
  return () => {
386
- this.inboundHandler = void 0;
840
+ if (this.inboundHandler === handler) this.inboundHandler = void 0;
387
841
  };
388
842
  }
389
843
  onStatusReceipt(handler) {
390
844
  this.statusHandler = handler;
391
845
  return () => {
392
- this.statusHandler = void 0;
846
+ if (this.statusHandler === handler) this.statusHandler = void 0;
393
847
  };
394
848
  }
395
849
  /**
@@ -403,25 +857,52 @@ var WhatsAppCloudBackend = class {
403
857
  if (!verifyWebhookSignature(rawBody, signatureHeader, this.appSecret)) {
404
858
  return false;
405
859
  }
406
- const json = JSON.parse(
407
- typeof rawBody === "string" ? rawBody : rawBody.toString("utf8")
408
- );
860
+ const json = this.parseBody(rawBody);
861
+ if (json === void 0) return false;
409
862
  const envelope = parseWebhookPayload(json);
410
863
  if (envelope === null) return true;
411
- const inbounds = normalizeInboundMessages(envelope);
412
- for (const event of inbounds) {
413
- if (this.inboundHandler !== void 0) {
414
- await this.inboundHandler(event);
415
- }
864
+ for (const event of normalizeInboundMessages(envelope)) {
865
+ if (this.inboundHandler === void 0) continue;
866
+ await this.dispatchContained(() => this.inboundHandler?.(event), "handler");
416
867
  }
417
- const statuses = normalizeStatusReceipts(envelope);
418
- for (const receipt of statuses) {
419
- if (this.statusHandler !== void 0) {
420
- await this.statusHandler(receipt);
421
- }
868
+ for (const receipt of normalizeStatusReceipts(envelope)) {
869
+ if (this.statusHandler === void 0) continue;
870
+ await this.dispatchContained(() => this.statusHandler?.(receipt), "status handler");
422
871
  }
423
872
  return true;
424
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
+ }
425
906
  };
426
907
 
427
908
  // src/backend/web/ipc.ts
@@ -460,10 +941,10 @@ var LineBuffer = class {
460
941
  };
461
942
  var BRIDGE_PROCESS_TAG = "whatsapp-web-bridge";
462
943
  function pidFilePath(theokitHome, sessionId) {
463
- return path.join(theokitHome, `whatsapp-bridge-${sessionId}.pid`);
944
+ return path2.join(theokitHome, `whatsapp-bridge-${sessionId}.pid`);
464
945
  }
465
946
  function defaultTheokitHome() {
466
- 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");
467
948
  }
468
949
  function pidBelongsToOurBridge(pid) {
469
950
  try {
@@ -566,8 +1047,8 @@ function waitForExit(child, timeoutMs) {
566
1047
  }
567
1048
 
568
1049
  // src/backend/web/index.ts
569
- var DEFAULT_CONNECT_TIMEOUT_MS = 12e4;
570
- var DEFAULT_SEND_TIMEOUT_MS = 3e4;
1050
+ var DEFAULT_CONNECT_TIMEOUT_MS2 = 12e4;
1051
+ var DEFAULT_SEND_TIMEOUT_MS2 = 3e4;
571
1052
  var WhatsAppWebBackend = class {
572
1053
  constructor(opts) {
573
1054
  this.opts = opts;
@@ -579,6 +1060,8 @@ var WhatsAppWebBackend = class {
579
1060
  inboundHandler;
580
1061
  statusHandler;
581
1062
  pending = /* @__PURE__ */ new Map();
1063
+ /** Rejects an in-flight `connect()` when the bridge reports it cannot start. */
1064
+ connectRejectors = [];
582
1065
  msgIdCounter = 0;
583
1066
  botPhone;
584
1067
  connected = false;
@@ -611,22 +1094,27 @@ var WhatsAppWebBackend = class {
611
1094
  if (this.connected) return true;
612
1095
  this.handle = this.spawnBridgeHandle();
613
1096
  this.wireStdout();
614
- const timeoutMs = this.opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
615
- 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
+ });
616
1102
  let timer;
617
1103
  const timeout = new Promise((_resolve, reject) => {
618
1104
  timer = setTimeout(() => reject(new WhatsAppConnectTimeoutError(timeoutMs)), timeoutMs);
619
1105
  });
620
1106
  try {
621
1107
  const phone = await Promise.race([ready, timeout]);
622
- if (timer !== void 0) clearTimeout(timer);
623
1108
  this.botPhone = phone;
624
1109
  this.connected = true;
625
1110
  return true;
626
1111
  } catch (err) {
627
- if (timer !== void 0) clearTimeout(timer);
628
1112
  await this.cleanupHandle();
629
1113
  throw err;
1114
+ } finally {
1115
+ if (timer !== void 0) clearTimeout(timer);
1116
+ this.readyResolvers = [];
1117
+ this.connectRejectors = [];
630
1118
  }
631
1119
  }
632
1120
  async disconnect() {
@@ -646,13 +1134,14 @@ var WhatsAppWebBackend = class {
646
1134
  }
647
1135
  this.pending.clear();
648
1136
  this.readyResolvers = [];
1137
+ this.connectRejectors = [];
649
1138
  }
650
1139
  async send(message) {
651
1140
  if (!this.connected || this.handle === void 0 || this.handle.child.stdin === null) {
652
1141
  return { ok: false, error: { code: "server_error", message: "Bridge not connected." } };
653
1142
  }
654
1143
  const msgId = `out-${++this.msgIdCounter}`;
655
- const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;
1144
+ const timeoutMs = this.opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS2;
656
1145
  return new Promise((resolve2) => {
657
1146
  const timer = setTimeout(() => {
658
1147
  this.pending.delete(msgId);
@@ -679,13 +1168,13 @@ var WhatsAppWebBackend = class {
679
1168
  onInbound(handler) {
680
1169
  this.inboundHandler = handler;
681
1170
  return () => {
682
- this.inboundHandler = void 0;
1171
+ if (this.inboundHandler === handler) this.inboundHandler = void 0;
683
1172
  };
684
1173
  }
685
1174
  onStatusReceipt(handler) {
686
1175
  this.statusHandler = handler;
687
1176
  return () => {
688
- this.statusHandler = void 0;
1177
+ if (this.statusHandler === handler) this.statusHandler = void 0;
689
1178
  };
690
1179
  }
691
1180
  handleReady(event) {
@@ -705,7 +1194,27 @@ var WhatsAppWebBackend = class {
705
1194
  backend: "web",
706
1195
  raw: event
707
1196
  };
708
- 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 = [];
709
1218
  }
710
1219
  handleSendAck(event) {
711
1220
  const pending = this.pending.get(event.msgId);
@@ -725,6 +1234,10 @@ var WhatsAppWebBackend = class {
725
1234
  status: event.status,
726
1235
  recipient: event.recipient,
727
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
+ `);
728
1241
  });
729
1242
  }
730
1243
  dispatch(event) {
@@ -742,19 +1255,315 @@ var WhatsAppWebBackend = class {
742
1255
  this.handleStatus(event);
743
1256
  return;
744
1257
  case "error":
745
- process.stderr.write(`[whatsapp-web bridge] ${event.message}
746
- `);
1258
+ this.handleBridgeError(event);
747
1259
  return;
748
1260
  }
749
1261
  }
750
1262
  };
751
1263
  function defaultBridgeScriptPath() {
752
- return path.resolve(
753
- path.dirname(new URL(import.meta.url).pathname),
754
- "../../bridge/whatsapp-web-bridge.mjs"
755
- );
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;
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
+ });
756
1290
  }
757
1291
 
758
- export { LineBuffer, WhatsAppAdapter, WhatsAppCloudBackend, WhatsAppConnectTimeoutError, WhatsAppWebBackend, digitsOnly, formatCommand, mapWhatsAppCloudError, mapWhatsAppWebError, normalizeInboundMessages, normalizeStatusReceipts, parseEvent, parseWebhookPayload, splitForWhatsApp, verifyWebhookSignature, verifyWebhookSubscription };
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
+ };
1566
+
1567
+ export { ConfigurationError, LineBuffer, WhatsAppAdapter, WhatsAppBaileysBackend, WhatsAppBridgeError, WhatsAppCloudBackend, WhatsAppConnectTimeoutError, WhatsAppWebBackend, createBaileysSocket, defaultBridgeScriptPath, digitsOnly, formatCommand, mapWhatsAppCloudError, mapWhatsAppWebError, normalizeInboundMessages, normalizeStatusReceipts, parseEvent, parseWebhookPayload, splitForWhatsApp, verifyWebhookSignature, verifyWebhookSubscription };
759
1568
  //# sourceMappingURL=index.js.map
760
1569
  //# sourceMappingURL=index.js.map