@theokit/gateway-whatsapp 0.1.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +232 -0
- package/dist/bridge/whatsapp-web-bridge.mjs +79 -11
- package/dist/index.cjs +1127 -165
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +678 -49
- package/dist/index.d.ts +678 -49
- package/dist/index.js +1124 -166
- package/dist/index.js.map +1 -1
- package/package.json +16 -3
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { ChildProcess } from 'node:child_process';
|
|
2
|
+
import { GatewayConfigurationError, GatewayConfigurationErrorOptions, BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent } from '@theokit/gateway';
|
|
2
3
|
export { WhatsAppMessageEvent } from '@theokit/gateway';
|
|
3
4
|
|
|
4
5
|
/**
|
|
@@ -27,7 +28,7 @@ interface WhatsAppInboundEvent {
|
|
|
27
28
|
/** Receipt timestamp (ms since epoch). */
|
|
28
29
|
readonly receivedAt: number;
|
|
29
30
|
/** Backend that emitted this event. */
|
|
30
|
-
readonly backend: "cloud" | "web";
|
|
31
|
+
readonly backend: "cloud" | "web" | "baileys";
|
|
31
32
|
/** Raw envelope for the escape hatch. */
|
|
32
33
|
readonly raw: unknown;
|
|
33
34
|
}
|
|
@@ -51,25 +52,101 @@ interface WhatsAppStatusReceipt {
|
|
|
51
52
|
/** Receipt timestamp. */
|
|
52
53
|
readonly timestamp: number;
|
|
53
54
|
}
|
|
55
|
+
/**
|
|
56
|
+
* What went wrong, in the vocabulary a caller can branch on.
|
|
57
|
+
*
|
|
58
|
+
* Extracted from `WhatsAppSendResult` rather than copied beside it: a credential check and a
|
|
59
|
+
* send fail for the same reasons, and two declarations of one vocabulary drift the moment
|
|
60
|
+
* somebody adds a code to one of them.
|
|
61
|
+
*/
|
|
62
|
+
interface WhatsAppError {
|
|
63
|
+
readonly code: "auth_failed" | "rate_limit" | "invalid_request"
|
|
64
|
+
/**
|
|
65
|
+
* More than 24 hours since the recipient last replied. The payload was
|
|
66
|
+
* fine and the credential is fine; WhatsApp policy refuses free-form text
|
|
67
|
+
* outside that window. The remedy is specific and different from every
|
|
68
|
+
* other error here — resend as an approved template — which is why it is
|
|
69
|
+
* its own code rather than one more `invalid_request`.
|
|
70
|
+
*/
|
|
71
|
+
| "session_window_expired"
|
|
72
|
+
/**
|
|
73
|
+
* The recipient was never registered against this phone number. The payload
|
|
74
|
+
* is fine and the credential is fine; the number simply may not message this
|
|
75
|
+
* person yet. Its own code because the remedy is a console step rather than
|
|
76
|
+
* anything in the request — and because every Cloud API app starts on a test
|
|
77
|
+
* number, it is the error most integrations meet first.
|
|
78
|
+
*/
|
|
79
|
+
| "recipient_not_allowlisted"
|
|
80
|
+
/**
|
|
81
|
+
* `send()` was called without a successful `connect()`, or after `disconnect()`.
|
|
82
|
+
*
|
|
83
|
+
* Its own code because all three backends reach this state and used to describe it three
|
|
84
|
+
* different ways — `server_error` from web and Baileys, nothing at all from Cloud, which
|
|
85
|
+
* sent regardless. A caller cannot branch on prose, and a conformance test cannot assert on
|
|
86
|
+
* it either: one code is what makes "the implementations agree" a checkable claim rather
|
|
87
|
+
* than a hope.
|
|
88
|
+
*/
|
|
89
|
+
| "not_connected"
|
|
90
|
+
/**
|
|
91
|
+
* The recipient cannot receive this message, and no retry changes that:
|
|
92
|
+
* no WhatsApp account, terms not accepted, an outdated client, or the
|
|
93
|
+
* business having blocked them. Terminal by nature; the cause is in the
|
|
94
|
+
* message.
|
|
95
|
+
*/
|
|
96
|
+
| "undeliverable" | "server_error" | "timeout" | "unknown";
|
|
97
|
+
readonly message: string;
|
|
98
|
+
}
|
|
54
99
|
/** Per-message send result returned by `WhatsAppBackend.send`. */
|
|
55
|
-
interface WhatsAppSendResult
|
|
100
|
+
interface WhatsAppSendResult {
|
|
56
101
|
readonly ok: boolean;
|
|
57
102
|
/** Set when ok=true. The wamid Meta / web assigned to the outbound message. */
|
|
58
103
|
readonly wamid?: string;
|
|
59
|
-
readonly error?:
|
|
60
|
-
readonly code: "auth_failed" | "rate_limit" | "invalid_request" | "server_error" | "timeout" | "unknown";
|
|
61
|
-
readonly message: string;
|
|
62
|
-
};
|
|
104
|
+
readonly error?: WhatsAppError;
|
|
63
105
|
}
|
|
64
106
|
/**
|
|
65
107
|
* Backend contract — every backend (cloud, web, future) implements this shape.
|
|
66
108
|
* `WhatsAppAdapter` delegates lifecycle + send + subscribe through this seam.
|
|
67
109
|
*/
|
|
68
110
|
interface WhatsAppBackend {
|
|
69
|
-
readonly kind: "cloud" | "web";
|
|
111
|
+
readonly kind: "cloud" | "web" | "baileys";
|
|
112
|
+
/**
|
|
113
|
+
* Make the backend usable, and report whether it is.
|
|
114
|
+
*
|
|
115
|
+
* Idempotent: a second call while connected returns `true` without repeating the work.
|
|
116
|
+
*
|
|
117
|
+
* **Operational failure returns `false`; misconfiguration throws.** A rejected credential, an
|
|
118
|
+
* unreachable server, a session that never opens — those are conditions a supervisor can retry
|
|
119
|
+
* or report, so they come back as `false` with the reason written where a human can read it. A
|
|
120
|
+
* missing peer dependency or an absent browser is not: no retry fixes it, and answering `false`
|
|
121
|
+
* would bury a setup error under a runtime one.
|
|
122
|
+
*
|
|
123
|
+
* The line was drawn after the conformance suite asserted the absolute version and two of three
|
|
124
|
+
* implementations "failed" it — correctly. They throw `ConfigurationError` and
|
|
125
|
+
* `WhatsAppBridgeError` for exactly the case that should not be swallowed.
|
|
126
|
+
*/
|
|
70
127
|
connect(): Promise<boolean>;
|
|
128
|
+
/** Release whatever `connect()` took. Idempotent, and safe on a backend that never connected. */
|
|
71
129
|
disconnect(): Promise<void>;
|
|
72
|
-
|
|
130
|
+
/**
|
|
131
|
+
* Send one message.
|
|
132
|
+
*
|
|
133
|
+
* **Requires a successful `connect()` first, and refuses without one** — with
|
|
134
|
+
* `ok: false, error.code === "not_connected"`, never a throw, and without touching the
|
|
135
|
+
* transport. One code across every implementation, because a caller branches on the code and
|
|
136
|
+
* a conformance test can only assert on one.
|
|
137
|
+
*
|
|
138
|
+
* That sentence is here because its absence cost something. The interface used to declare bare
|
|
139
|
+
* signatures, each implementation answered the unasked question its own way, and they diverged:
|
|
140
|
+
* web and Baileys refused, Cloud posted regardless. A consumer swapping backends — the single
|
|
141
|
+
* thing this seam exists to allow — found unconnected sends leaving the process, which for
|
|
142
|
+
* Cloud meant a real request carrying a credential nothing had verified, or one `connect()`
|
|
143
|
+
* had already rejected.
|
|
144
|
+
*
|
|
145
|
+
* Enforced by `tests/backend-conformance.test.ts` against every implementation at once. A
|
|
146
|
+
* per-backend test proves one of them does something; only a shared one proves they agree, and
|
|
147
|
+
* the agreement is the product.
|
|
148
|
+
*/
|
|
149
|
+
send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult>;
|
|
73
150
|
/** Subscribe to normalized inbound events. Returns unsubscribe. */
|
|
74
151
|
onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void;
|
|
75
152
|
/** Subscribe to status receipts. Returns unsubscribe. */
|
|
@@ -98,6 +175,35 @@ interface WhatsAppCloudConfig {
|
|
|
98
175
|
/** Graph API version. Defaults to `v18.0`. */
|
|
99
176
|
readonly apiVersion?: string;
|
|
100
177
|
}
|
|
178
|
+
/**
|
|
179
|
+
* Baileys backend config (ADR D319-D322).
|
|
180
|
+
*
|
|
181
|
+
* Unofficial, like the `web` backend: it automates a WhatsApp Web session, which Meta's terms
|
|
182
|
+
* do not sanction and which can get a number banned. Unlike `web` it needs no browser.
|
|
183
|
+
*
|
|
184
|
+
* @public
|
|
185
|
+
*/
|
|
186
|
+
interface WhatsAppBaileysConfig {
|
|
187
|
+
/**
|
|
188
|
+
* Directory holding the multi-file auth state — the pairing, persisted.
|
|
189
|
+
*
|
|
190
|
+
* Treat it like a credential: it IS the session, and anyone holding it is the account.
|
|
191
|
+
*/
|
|
192
|
+
readonly sessionDir: string;
|
|
193
|
+
/** Give up on `connect()` after this long. Default 60s. */
|
|
194
|
+
readonly connectTimeoutMs?: number;
|
|
195
|
+
/** Give up on one send after this long. Default 30s. */
|
|
196
|
+
readonly sendTimeoutMs?: number;
|
|
197
|
+
/**
|
|
198
|
+
* Where the pairing QR goes, as often as WhatsApp reissues it. Defaults to stderr.
|
|
199
|
+
*
|
|
200
|
+
* The backend has always accepted this; it was reachable only by constructing the backend by
|
|
201
|
+
* hand, which is the path this class exists to replace. A host that is not a terminal — a
|
|
202
|
+
* service, a container, a web app — cannot read stderr back to the person holding the phone,
|
|
203
|
+
* and without a route out the QR a fresh `sessionDir` can only ever time out.
|
|
204
|
+
*/
|
|
205
|
+
readonly onQr?: (qr: string) => void;
|
|
206
|
+
}
|
|
101
207
|
/** Web (whatsapp-web.js subprocess bridge) backend config (ADR D305). */
|
|
102
208
|
interface WhatsAppWebConfig {
|
|
103
209
|
/** Stable session id used to lock the bridge per-workspace. */
|
|
@@ -105,50 +211,149 @@ interface WhatsAppWebConfig {
|
|
|
105
211
|
/** Optional override of the bridge script path (defaults to packaged bridge). */
|
|
106
212
|
readonly bridgeScriptPath?: string;
|
|
107
213
|
}
|
|
108
|
-
/**
|
|
214
|
+
/**
|
|
215
|
+
* Which backend to build, and its configuration.
|
|
216
|
+
*
|
|
217
|
+
* The union carries only what DIFFERS between backends. Options that mean the same thing on
|
|
218
|
+
* either one — `requireMention`, `botPhoneId`, `allowedSenders` — live in
|
|
219
|
+
* {@link WhatsAppAdapterCommonOptions} instead, so there is one copy rather than one per arm
|
|
220
|
+
* for the two copies to drift apart (ADR D318).
|
|
221
|
+
*
|
|
222
|
+
* @public
|
|
223
|
+
*/
|
|
109
224
|
type WhatsAppAdapterOptions = {
|
|
110
225
|
readonly backend: "cloud";
|
|
111
226
|
readonly cloud: WhatsAppCloudConfig;
|
|
112
|
-
/** D309: require @mention in groups. Default `true`. */
|
|
113
|
-
readonly requireMention?: boolean;
|
|
114
|
-
/** Phone id to detect mentions of (digits only). Defaults to `cloud.phoneNumberId`. */
|
|
115
|
-
readonly botPhoneId?: string;
|
|
116
227
|
} | {
|
|
117
228
|
readonly backend: "web";
|
|
118
229
|
readonly web: WhatsAppWebConfig;
|
|
230
|
+
} | {
|
|
231
|
+
readonly backend: "baileys";
|
|
232
|
+
readonly baileys: WhatsAppBaileysConfig;
|
|
233
|
+
};
|
|
234
|
+
/**
|
|
235
|
+
* Options that apply whichever backend is in use.
|
|
236
|
+
*
|
|
237
|
+
* @public
|
|
238
|
+
*/
|
|
239
|
+
interface WhatsAppAdapterCommonOptions {
|
|
240
|
+
/** D309: require an @mention in groups. Default `true`. */
|
|
119
241
|
readonly requireMention?: boolean;
|
|
120
|
-
/**
|
|
242
|
+
/**
|
|
243
|
+
* Phone id to detect mentions of (digits only).
|
|
244
|
+
*
|
|
245
|
+
* `fromCloud` defaults it to the phone number id. **The web backend has nothing to default
|
|
246
|
+
* from**, so leaving it unset there while `requireMention` is on (its default) drops every
|
|
247
|
+
* group message — the adapter cannot tell whether it was mentioned. That drop is now
|
|
248
|
+
* logged rather than silent.
|
|
249
|
+
*/
|
|
121
250
|
readonly botPhoneId?: string;
|
|
122
|
-
|
|
251
|
+
/**
|
|
252
|
+
* Comma-separated senders allowed to reach the handler. Absent leaves delivery unchanged;
|
|
253
|
+
* an empty string admits nobody. See `allowlist.ts` for why those differ.
|
|
254
|
+
*/
|
|
255
|
+
readonly allowedSenders?: string;
|
|
256
|
+
}
|
|
123
257
|
/** EC-7: digit-only normalizer for mention comparison (handles `+`, `-`, `()`, spaces). */
|
|
124
258
|
declare function digitsOnly(s: string): string;
|
|
125
259
|
/**
|
|
126
260
|
* Adapter facade. Implements `BasePlatformAdapter` (D172).
|
|
127
261
|
*
|
|
128
|
-
* Use `WhatsAppAdapter.fromCloud(config)` or `WhatsAppAdapter.fromWeb(config)
|
|
129
|
-
*
|
|
262
|
+
* Use `WhatsAppAdapter.fromCloud(config)` or `WhatsAppAdapter.fromWeb(config)`. The
|
|
263
|
+
* constructor stays available for tests and for a backend of your own.
|
|
130
264
|
*/
|
|
131
265
|
declare class WhatsAppAdapter extends BasePlatformAdapter {
|
|
132
266
|
readonly platform: "whatsapp";
|
|
133
267
|
private readonly backendImpl;
|
|
134
268
|
private readonly requireMention;
|
|
135
269
|
private readonly botPhoneId;
|
|
270
|
+
/** `undefined` = no allowlist configured; a set = configured, and enforced fail-closed. */
|
|
271
|
+
private readonly allowedSenders;
|
|
136
272
|
/** Mirrors the sibling adapters: guards connect() against opening a second session. */
|
|
137
273
|
private connected;
|
|
138
274
|
private handler?;
|
|
139
275
|
private statusHandler?;
|
|
140
276
|
private inboundUnsubscribe?;
|
|
141
277
|
private statusUnsubscribe?;
|
|
142
|
-
/**
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
278
|
+
/**
|
|
279
|
+
* Build an adapter from a discriminated configuration.
|
|
280
|
+
*
|
|
281
|
+
* The entry point for configuration that arrives as **data** — read from a file, an
|
|
282
|
+
* environment, or a tenant record — where the backend is a string rather than a decision
|
|
283
|
+
* made in code. `fromCloud` / `fromWeb` are the direct forms when the choice is already
|
|
284
|
+
* known at the call site.
|
|
285
|
+
*
|
|
286
|
+
* This is what `WhatsAppAdapterOptions` exists for. Until it had this consumer the union
|
|
287
|
+
* was exported, documented and inert, which is the defect #47 was filed about, and the
|
|
288
|
+
* first attempt at closing that issue left it inert — the factories took the config halves
|
|
289
|
+
* directly and never the union.
|
|
290
|
+
*
|
|
291
|
+
* @throws {ConfigurationError} when a required option is missing or empty.
|
|
292
|
+
* @public
|
|
293
|
+
*/
|
|
294
|
+
static from(options: WhatsAppAdapterOptions, common?: WhatsAppAdapterCommonOptions): WhatsAppAdapter;
|
|
295
|
+
/**
|
|
296
|
+
* Build a Baileys adapter.
|
|
297
|
+
*
|
|
298
|
+
* Unofficial, and no amount of code changes that: it automates a WhatsApp Web session,
|
|
299
|
+
* which Meta's terms do not sanction and which can get a number banned. Use a number
|
|
300
|
+
* created for this, never a personal one. Prefer {@link WhatsAppAdapter.fromCloud} unless
|
|
301
|
+
* the number has no Cloud API access.
|
|
302
|
+
*
|
|
303
|
+
* Unlike {@link WhatsAppAdapter.fromWeb} it embeds no browser — it speaks the multi-device
|
|
304
|
+
* protocol over a WebSocket. `baileys` is an optional peer dependency; it is loaded lazily
|
|
305
|
+
* at connect, so a consumer who never calls this never needs it installed.
|
|
306
|
+
*
|
|
307
|
+
* `botPhoneId` has nothing to default from here, so leaving it unset while `requireMention`
|
|
308
|
+
* is on (its default) drops every group message. The adapter logs when it does.
|
|
309
|
+
*
|
|
310
|
+
* @throws {ConfigurationError} when `sessionDir` is missing or empty.
|
|
311
|
+
* @public
|
|
312
|
+
*/
|
|
313
|
+
static fromBaileys(baileys: WhatsAppBaileysConfig, opts?: WhatsAppAdapterCommonOptions): WhatsAppAdapter;
|
|
314
|
+
/**
|
|
315
|
+
* Build a Cloud-API adapter.
|
|
316
|
+
*
|
|
317
|
+
* The construction path this package's docblock has named since it was written, and which
|
|
318
|
+
* did not exist until #47 — a consumer following the only guidance the package gave wrote
|
|
319
|
+
* code that would not compile.
|
|
320
|
+
*
|
|
321
|
+
* Prefer it over the constructor: it keeps `WhatsAppCloudBackend` an implementation detail
|
|
322
|
+
* of this package rather than something every consumer imports and assembles.
|
|
323
|
+
*
|
|
324
|
+
* @throws {ConfigurationError} when a required credential is missing or empty.
|
|
325
|
+
* @public
|
|
326
|
+
*/
|
|
327
|
+
static fromCloud(cloud: WhatsAppCloudConfig, opts?: WhatsAppAdapterCommonOptions): WhatsAppAdapter;
|
|
328
|
+
/**
|
|
329
|
+
* Build a WhatsApp-Web adapter.
|
|
330
|
+
*
|
|
331
|
+
* Unofficial: it drives a real WhatsApp Web session through a browser, which Meta's terms
|
|
332
|
+
* do not sanction and which can get a number banned. It also needs a browser this package
|
|
333
|
+
* does not install. Prefer {@link WhatsAppAdapter.fromCloud} unless the number has no
|
|
334
|
+
* Cloud API access.
|
|
335
|
+
*
|
|
336
|
+
* @throws {ConfigurationError} when `sessionId` is missing or empty.
|
|
337
|
+
* @public
|
|
338
|
+
*/
|
|
339
|
+
static fromWeb(web: WhatsAppWebConfig, opts?: WhatsAppAdapterCommonOptions): WhatsAppAdapter;
|
|
340
|
+
/** Construct from a pre-built backend. Prefer the factories; this is for tests and for a custom backend. */
|
|
341
|
+
constructor(backendImpl: WhatsAppBackend, opts?: WhatsAppAdapterCommonOptions);
|
|
147
342
|
/** Escape hatch (D180-style) for advanced features. */
|
|
148
343
|
getBackend(): WhatsAppBackend;
|
|
149
344
|
connect(): Promise<boolean>;
|
|
150
345
|
disconnect(): Promise<void>;
|
|
151
346
|
sendMessage(out: OutboundMessage): Promise<SendResult>;
|
|
347
|
+
/**
|
|
348
|
+
* Is this sender refused by a configured allowlist?
|
|
349
|
+
*
|
|
350
|
+
* Runs before the group/mention filter because it answers a different question: that one asks
|
|
351
|
+
* whether a message was meant for us, this one asks whether the sender may reach us at all.
|
|
352
|
+
*
|
|
353
|
+
* The refusal is logged. A silent drop is indistinguishable from a broken gateway, and the
|
|
354
|
+
* first thing a mistyped allowlist causes is an operator wondering why the bot went mute.
|
|
355
|
+
*/
|
|
356
|
+
private isRefusedBySenderAllowlist;
|
|
152
357
|
/** D309 + EC-7: group filter with digit-only normalization. */
|
|
153
358
|
private shouldDropGroupMessage;
|
|
154
359
|
private toMessageEvent;
|
|
@@ -158,44 +363,233 @@ declare class WhatsAppAdapter extends BasePlatformAdapter {
|
|
|
158
363
|
}
|
|
159
364
|
|
|
160
365
|
/**
|
|
161
|
-
*
|
|
366
|
+
* The socket contract this backend depends on, and the real factory behind it (ADR D319).
|
|
367
|
+
*
|
|
368
|
+
* Three members, not Baileys' whole `WASocket`. Two things follow, and both are the reason
|
|
369
|
+
* the contract is ours rather than the library's.
|
|
162
370
|
*
|
|
163
|
-
*
|
|
164
|
-
*
|
|
165
|
-
*
|
|
166
|
-
*
|
|
371
|
+
* It was five, and two rounds of review took two members off it, both declared and called by
|
|
372
|
+
* nothing. `logout()` went first and mattered most: on WhatsApp it UNPAIRS the device, the
|
|
373
|
+
* opposite of what `disconnect()` means here, so the next person needing a teardown would find
|
|
374
|
+
* it, call it, and lose the session the whole `sessionDir` exists to keep. `ev.off()` went for
|
|
375
|
+
* the plain reason — nothing removed a listener, because a socket is discarded whole rather
|
|
376
|
+
* than unsubscribed from. Neither was a capability we had; both read as one.
|
|
377
|
+
*
|
|
378
|
+
* **The backend is testable with `baileys` absent.** It is an optional peer dependency, so
|
|
379
|
+
* CI does not install it — and a backend that could only be exercised with the real library
|
|
380
|
+
* installed would be exercised by nothing, which is how the `web` backend reached production
|
|
381
|
+
* unable to start (B-002).
|
|
382
|
+
*
|
|
383
|
+
* **The library stays an implementation detail of this file.** A breaking change upstream
|
|
384
|
+
* lands in one place instead of wherever its types had spread. Depending on all of `WASocket`
|
|
385
|
+
* to call three of its members is the interface-segregation problem stated plainly
|
|
386
|
+
* (`rules/architecture.md`).
|
|
387
|
+
*
|
|
388
|
+
* @internal
|
|
389
|
+
*/
|
|
390
|
+
/** A Baileys connection-state update, narrowed to what the lifecycle reads. */
|
|
391
|
+
interface BaileysConnectionUpdate {
|
|
392
|
+
readonly connection?: "close" | "connecting" | "open";
|
|
393
|
+
readonly qr?: string;
|
|
394
|
+
readonly lastDisconnect?: {
|
|
395
|
+
readonly error?: unknown;
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
/** The events this backend subscribes to. Anything else Baileys emits is ignored. */
|
|
399
|
+
interface BaileysEventMap {
|
|
400
|
+
"connection.update": BaileysConnectionUpdate;
|
|
401
|
+
"messages.upsert": {
|
|
402
|
+
readonly messages: readonly unknown[];
|
|
403
|
+
readonly type?: string;
|
|
404
|
+
};
|
|
405
|
+
"creds.update": unknown;
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* What this backend needs a socket to be.
|
|
409
|
+
*
|
|
410
|
+
* Deliberately structural: any object with these members satisfies it, which is what lets a
|
|
411
|
+
* test hand over a fake without importing anything from Baileys.
|
|
412
|
+
*/
|
|
413
|
+
interface BaileysSocketLike {
|
|
414
|
+
readonly ev: {
|
|
415
|
+
on<K extends keyof BaileysEventMap>(event: K, listener: (payload: BaileysEventMap[K]) => void): void;
|
|
416
|
+
};
|
|
417
|
+
sendMessage(jid: string, content: {
|
|
418
|
+
text: string;
|
|
419
|
+
}): Promise<{
|
|
420
|
+
key?: {
|
|
421
|
+
id?: string;
|
|
422
|
+
};
|
|
423
|
+
} | undefined>;
|
|
424
|
+
end?(error?: Error): void;
|
|
425
|
+
}
|
|
426
|
+
/** How a socket comes into being. Replaced wholesale in tests. */
|
|
427
|
+
type BaileysSocketFactory = (opts: BaileysSocketOptions) => Promise<BaileysSocketLike>;
|
|
428
|
+
/** What the real factory needs to build a socket. */
|
|
429
|
+
interface BaileysSocketOptions {
|
|
430
|
+
/** Directory holding the multi-file auth state — the pairing, persisted. */
|
|
431
|
+
readonly sessionDir: string;
|
|
432
|
+
/** Overrides the module the factory loads. Tests point it at a stub; production never sets it. */
|
|
433
|
+
readonly specifier?: string;
|
|
434
|
+
/**
|
|
435
|
+
* Called with the pairing QR, as often as WhatsApp reissues it.
|
|
436
|
+
*
|
|
437
|
+
* Without somewhere for this to go, a fresh `sessionDir` can only ever time out: there is
|
|
438
|
+
* no other way to pair, and `printQRInTerminal` is off because a library writing to stdout
|
|
439
|
+
* is a library deciding where a host application's output goes. Defaults to writing the
|
|
440
|
+
* code to **stderr**, which is what the `web` bridge does and what keeps stdout free for a
|
|
441
|
+
* host that is using it for something.
|
|
442
|
+
*/
|
|
443
|
+
readonly onQr?: (qr: string) => void;
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Build a real Baileys socket.
|
|
447
|
+
*
|
|
448
|
+
* The import shape follows what B-002 cost this repository to learn: read the API off the
|
|
449
|
+
* default export first, check each member is callable, and report a structured error naming
|
|
450
|
+
* the one that is missing. A `try/catch` around the import guards the package being absent,
|
|
451
|
+
* not a member being undefined — and that gap is what killed the `web` bridge for months
|
|
452
|
+
* behind a friendly "not installed" message that was false.
|
|
453
|
+
*
|
|
454
|
+
* The socket settings are ADR D322, each for a stated consequence rather than a precedent:
|
|
455
|
+
* `markOnlineOnConnect: false` so the account does not read as permanently online and
|
|
456
|
+
* suppress push notifications on the owner's real phone; `syncFullHistory: false` so a
|
|
457
|
+
* connect does not pull the entire history; an honest `browser` triple; and the protocol
|
|
458
|
+
* version fetched at connect, because a stale one is refused by the server.
|
|
459
|
+
*/
|
|
460
|
+
declare function createBaileysSocket(opts: BaileysSocketOptions): Promise<BaileysSocketLike>;
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* `WhatsAppBaileysBackend` — the third implementation of `WhatsAppBackend` (B-001).
|
|
464
|
+
*
|
|
465
|
+
* Baileys speaks the WhatsApp Web multi-device protocol over a WebSocket, with no browser.
|
|
466
|
+
* That is the whole difference from the `web` backend, which drives a headless Chromium.
|
|
467
|
+
*
|
|
468
|
+
* **Unofficial, and no amount of code changes that.** It automates a WhatsApp Web session,
|
|
469
|
+
* which Meta's terms do not sanction and which can get a number banned. Use a number created
|
|
470
|
+
* for this, never a personal one. Prefer {@link WhatsAppCloudBackend} unless the number has
|
|
471
|
+
* no Cloud API access.
|
|
472
|
+
*
|
|
473
|
+
* **Added rather than replacing**, for three reasons that a substitution would not give:
|
|
474
|
+
* nobody loses a paired session (a Puppeteer profile and a multi-file auth state are not
|
|
475
|
+
* interchangeable), the comparison against the incumbent becomes measurable rather than
|
|
476
|
+
* asserted, and retreat stays cheap because nobody is forced onto it.
|
|
167
477
|
*
|
|
168
478
|
* @public
|
|
169
479
|
*/
|
|
170
480
|
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
481
|
+
/** Construction options. @public */
|
|
482
|
+
interface WhatsAppBaileysBackendOptions {
|
|
483
|
+
/**
|
|
484
|
+
* Directory holding the multi-file auth state — the pairing, persisted.
|
|
485
|
+
*
|
|
486
|
+
* Treat it like a credential: it is the session, and anyone holding it is the account.
|
|
487
|
+
*/
|
|
488
|
+
readonly sessionDir: string;
|
|
489
|
+
/** Give up on `connect()` after this long. Default 60s. */
|
|
490
|
+
readonly connectTimeoutMs?: number;
|
|
491
|
+
/** Give up on one send after this long. Default 30s. */
|
|
492
|
+
readonly sendTimeoutMs?: number;
|
|
493
|
+
/** Test seam: build the socket some other way. Production leaves it unset. */
|
|
494
|
+
readonly socketFactory?: BaileysSocketFactory;
|
|
495
|
+
/**
|
|
496
|
+
* Where the pairing QR goes, as often as WhatsApp reissues it.
|
|
497
|
+
*
|
|
498
|
+
* Defaults to stderr. It is exposed here because a host that is not a terminal — a service, a
|
|
499
|
+
* container, a web app — has no way to read stderr back to the person holding the phone, and
|
|
500
|
+
* without a route out the QR the session can never be paired.
|
|
501
|
+
*/
|
|
502
|
+
readonly onQr?: (qr: string) => void;
|
|
178
503
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
504
|
+
/**
|
|
505
|
+
* A WhatsApp backend that speaks the multi-device protocol directly.
|
|
506
|
+
*
|
|
507
|
+
* No browser: where {@link WhatsAppWebBackend} drives a headless Chromium through
|
|
508
|
+
* `whatsapp-web.js`, this holds a WebSocket. That is the whole difference in kind.
|
|
509
|
+
*
|
|
510
|
+
* **Unofficial, and no amount of code changes that.** It automates a WhatsApp Web session,
|
|
511
|
+
* which Meta's terms do not sanction and which can get a number banned. Use a number created
|
|
512
|
+
* for this and nothing else — never a personal one. Prefer the Cloud API backend unless the
|
|
513
|
+
* number has no Cloud API access.
|
|
514
|
+
*
|
|
515
|
+
* `baileys` is an optional peer dependency, loaded lazily at connect, so a consumer who never
|
|
516
|
+
* constructs this never needs it installed.
|
|
517
|
+
*
|
|
518
|
+
* @public
|
|
519
|
+
*/
|
|
520
|
+
declare class WhatsAppBaileysBackend implements WhatsAppBackend {
|
|
521
|
+
private readonly opts;
|
|
522
|
+
readonly kind: "baileys";
|
|
523
|
+
private socket?;
|
|
524
|
+
private connected;
|
|
525
|
+
/** Guards a concurrent second `connect()` from opening a second live session. */
|
|
526
|
+
private connecting?;
|
|
527
|
+
/**
|
|
528
|
+
* Which connection attempt is current.
|
|
529
|
+
*
|
|
530
|
+
* Bumped by every `connect()` and every `disconnect()`. A socket from a superseded attempt
|
|
531
|
+
* checks it before touching any state, which is what stops an abandoned socket delivering
|
|
532
|
+
* inbound or flipping `connected` under a live one.
|
|
533
|
+
*/
|
|
534
|
+
private generation;
|
|
535
|
+
/**
|
|
536
|
+
* How to end a connection attempt that is still awaiting `open`.
|
|
537
|
+
*
|
|
538
|
+
* Retirement by generation makes an attempt's listeners silent, which is not the same as
|
|
539
|
+
* making the attempt finish. One entry per in-flight attempt; `disconnect()` calls them so
|
|
540
|
+
* the attempt settles now instead of at its timeout.
|
|
541
|
+
*/
|
|
542
|
+
private readonly pendingAttempts;
|
|
543
|
+
/**
|
|
544
|
+
* Why the socket last closed, as Baileys reported it.
|
|
545
|
+
*
|
|
546
|
+
* Kept because `connect()` returning `false` cannot distinguish a network blip from a
|
|
547
|
+
* session the operator unlinked from their phone — and only one of those is worth retrying.
|
|
548
|
+
* `rules/error-handling.md` § 3: fail clear, and log with enough context to act.
|
|
549
|
+
*/
|
|
550
|
+
private lastCloseError?;
|
|
183
551
|
private inboundHandler?;
|
|
184
552
|
private statusHandler?;
|
|
185
|
-
|
|
553
|
+
/**
|
|
554
|
+
* Serialises outbound sends (ADR D320).
|
|
555
|
+
*
|
|
556
|
+
* Both peer gateways studied do this, and one records that concurrent sends on a single
|
|
557
|
+
* socket can misdeliver to the wrong chat. We have NOT measured that in our own code — we
|
|
558
|
+
* have never run a Baileys socket — so this is precaution rather than a reproduction of our
|
|
559
|
+
* own bug, and saying so is the point. It is kept because the cost is one promise chain and
|
|
560
|
+
* the failure it guards against is a message delivered to the wrong person.
|
|
561
|
+
*/
|
|
562
|
+
private sendQueue;
|
|
563
|
+
constructor(opts: WhatsAppBaileysBackendOptions);
|
|
564
|
+
/**
|
|
565
|
+
* Open the socket and wait for it to report `open`.
|
|
566
|
+
*
|
|
567
|
+
* Idempotent, and safe against a concurrent second call: the in-flight promise is shared
|
|
568
|
+
* rather than a second socket being built. WhatsApp's own adapter shipped without that
|
|
569
|
+
* guard once and opened two live sessions.
|
|
570
|
+
*/
|
|
186
571
|
connect(): Promise<boolean>;
|
|
572
|
+
/** Close the socket. Idempotent, and safe when never connected. */
|
|
187
573
|
disconnect(): Promise<void>;
|
|
188
|
-
|
|
574
|
+
/**
|
|
575
|
+
* Send one text message.
|
|
576
|
+
*
|
|
577
|
+
* Queued behind any send already in flight (D320), and raced against a timeout whose
|
|
578
|
+
* expiry reports **undetermined** delivery rather than failure (D321). A local timeout says
|
|
579
|
+
* the acknowledgement did not arrive, not that the message did not — so this never
|
|
580
|
+
* retries, because a retry after a slow ack duplicates the message.
|
|
581
|
+
*/
|
|
582
|
+
send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult>;
|
|
583
|
+
/** Subscribe to inbound events. EC-H: a second call REPLACES the first. */
|
|
189
584
|
onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void;
|
|
190
|
-
onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void;
|
|
191
585
|
/**
|
|
192
|
-
*
|
|
193
|
-
* route after `verifyWebhookSubscription` on GET.
|
|
586
|
+
* Subscribe to delivery receipts. EC-H: a second call REPLACES the first.
|
|
194
587
|
*
|
|
195
|
-
*
|
|
196
|
-
*
|
|
588
|
+
* Declared for the interface; Baileys reports receipts on `messages.update`, which v1 does
|
|
589
|
+
* not consume. Registering a handler is accepted and it is never called — stated here
|
|
590
|
+
* rather than left for a consumer to discover from silence.
|
|
197
591
|
*/
|
|
198
|
-
|
|
592
|
+
onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void;
|
|
199
593
|
}
|
|
200
594
|
|
|
201
595
|
/** Inbound webhook payload — the full envelope Meta POSTs. */
|
|
@@ -245,6 +639,137 @@ interface MetaStatusUpdate {
|
|
|
245
639
|
readonly timestamp: string;
|
|
246
640
|
readonly recipient_id: string;
|
|
247
641
|
}
|
|
642
|
+
/** One component of a template — header, body or button — with its parameters. */
|
|
643
|
+
interface MetaTemplateComponent {
|
|
644
|
+
readonly type: string;
|
|
645
|
+
readonly parameters?: ReadonlyArray<Record<string, unknown>>;
|
|
646
|
+
readonly sub_type?: string;
|
|
647
|
+
readonly index?: string;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/**
|
|
651
|
+
* `WhatsAppCloudBackend` — Meta WhatsApp Business Cloud API backend (ADR D304).
|
|
652
|
+
*
|
|
653
|
+
* `connect()` verifies the credential against Meta and caches the result; `disconnect()` clears
|
|
654
|
+
* it. This header used to say both were no-ops, which is what the code did and what the first
|
|
655
|
+
* live run of the WhatsApp suite refuted (#58): a wrong or revoked token reported success at
|
|
656
|
+
* startup and surfaced as messages that silently never arrived.
|
|
657
|
+
*
|
|
658
|
+
* There is still no session to open — HTTP push via webhook is the only inbound channel, and
|
|
659
|
+
* outbound is a stateless POST. What `connect()` buys is the startup answer to "can this
|
|
660
|
+
* credential act as this number?", which is the question every sibling adapter answers and this
|
|
661
|
+
* one did not. Outbound delegates to `WhatsAppCloudClient`. Inbound dispatch is driven by the
|
|
662
|
+
* user calling `handleWebhookPayload(rawBody, sig)` from inside their HTTP route.
|
|
663
|
+
*
|
|
664
|
+
* @public
|
|
665
|
+
*/
|
|
666
|
+
|
|
667
|
+
interface WhatsAppCloudBackendOptions {
|
|
668
|
+
readonly accessToken: string;
|
|
669
|
+
readonly phoneNumberId: string;
|
|
670
|
+
readonly appSecret: string;
|
|
671
|
+
readonly apiVersion?: string;
|
|
672
|
+
/** Test seam. */
|
|
673
|
+
readonly fetch?: typeof fetch;
|
|
674
|
+
}
|
|
675
|
+
/**
|
|
676
|
+
* WhatsApp backend over Meta's official Cloud API.
|
|
677
|
+
*
|
|
678
|
+
* The supported path: Meta dials in with webhook deliveries, so inbound needs a publicly reachable
|
|
679
|
+
* HTTPS endpoint registered in the Meta console. Outbound is a plain HTTPS call and works anywhere.
|
|
680
|
+
* Business-initiated messages outside the 24-hour customer service window must use an approved
|
|
681
|
+
* template — a plain text send to a cold contact is rejected by the platform, not by this code.
|
|
682
|
+
*/
|
|
683
|
+
declare class WhatsAppCloudBackend implements WhatsAppBackend {
|
|
684
|
+
readonly kind: "cloud";
|
|
685
|
+
private readonly client;
|
|
686
|
+
/** Verified once by `connect()`; cleared by `disconnect()`. */
|
|
687
|
+
private connected;
|
|
688
|
+
/**
|
|
689
|
+
* The verification currently in flight, shared by every caller that arrives during it.
|
|
690
|
+
*
|
|
691
|
+
* A flag alone only guards callers that arrive AFTER one finished — two simultaneous
|
|
692
|
+
* `connect()` calls would each ask Meta, which is one wasted round-trip at startup and a
|
|
693
|
+
* rate-limit source under a supervisor that health-checks on a schedule. Cleared when it
|
|
694
|
+
* settles, so a failed attempt does not become a permanent refusal: a transient blip must stay
|
|
695
|
+
* distinguishable from a revoked token.
|
|
696
|
+
*/
|
|
697
|
+
private connecting?;
|
|
698
|
+
/**
|
|
699
|
+
* Which connection attempt is current.
|
|
700
|
+
*
|
|
701
|
+
* Bumped by every `connect()` and every `disconnect()`. Without it a verify that was still in
|
|
702
|
+
* flight when `disconnect()` ran would set `connected` back to true as it resolved, and every
|
|
703
|
+
* later `connect()` would short-circuit on a flag no live check stands behind — the field's own
|
|
704
|
+
* comment claims `disconnect()` clears it, and it did not. Same guard the Baileys backend
|
|
705
|
+
* carries, for the same reason.
|
|
706
|
+
*/
|
|
707
|
+
private generation;
|
|
708
|
+
private readonly appSecret;
|
|
709
|
+
private inboundHandler?;
|
|
710
|
+
private statusHandler?;
|
|
711
|
+
constructor(opts: WhatsAppCloudBackendOptions);
|
|
712
|
+
/**
|
|
713
|
+
* Confirm with Meta that this credential can act as this phone number.
|
|
714
|
+
*
|
|
715
|
+
* This used to be `return true`. A consumer with a wrong, expired or revoked token got success
|
|
716
|
+
* at startup and found out from messages that silently never arrived — no error, no log,
|
|
717
|
+
* nothing to alert on, which is the worst failure mode a gateway has. The first live run of the
|
|
718
|
+
* WhatsApp suite caught it (#58); no unit test could, because a fake backend always accepts.
|
|
719
|
+
*
|
|
720
|
+
* Idempotent, like every sibling: verified once, then cached. Re-asking on every call would
|
|
721
|
+
* turn a supervisor's health check into a rate-limit source against Meta.
|
|
722
|
+
*
|
|
723
|
+
* Returns false rather than throwing — the contract each sibling adapter is tested against,
|
|
724
|
+
* because a throw at startup takes the whole runner down with it. The reason goes to stderr
|
|
725
|
+
* first: told only "false", a supervisor cannot tell a revoked token, which needs a human,
|
|
726
|
+
* from a rate limit, which needs a wait.
|
|
727
|
+
*/
|
|
728
|
+
connect(): Promise<boolean>;
|
|
729
|
+
disconnect(): Promise<void>;
|
|
730
|
+
send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult>;
|
|
731
|
+
/**
|
|
732
|
+
* Send an approved template to `to`.
|
|
733
|
+
*
|
|
734
|
+
* Cloud-only, and deliberately absent from the `WhatsAppBackend` interface: WhatsApp Web has no
|
|
735
|
+
* concept of templates, so putting this on the shared contract would hand the web backend a
|
|
736
|
+
* method it could only throw from. A consumer reaches it by holding the backend directly.
|
|
737
|
+
*
|
|
738
|
+
* This is the only way to message someone outside the 24-hour service window — every
|
|
739
|
+
* notification, and every unattended check that this integration still works. Free-form text to
|
|
740
|
+
* a cold recipient comes back as `session_window_expired`.
|
|
741
|
+
*
|
|
742
|
+
* @param templateName Name of a template already approved on the WhatsApp Business account.
|
|
743
|
+
* @param languageCode Locale of the approved template, e.g. `en_US`, `pt_BR`.
|
|
744
|
+
* @param components Values for the template's variables; omit for a template that takes none.
|
|
745
|
+
*/
|
|
746
|
+
sendTemplate(to: string, templateName: string, languageCode: string, components?: ReadonlyArray<MetaTemplateComponent>): Promise<WhatsAppSendResult>;
|
|
747
|
+
onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void;
|
|
748
|
+
onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void;
|
|
749
|
+
/**
|
|
750
|
+
* Webhook entrypoint. The user calls this from inside their POST /webhook
|
|
751
|
+
* route after `verifyWebhookSubscription` on GET.
|
|
752
|
+
*
|
|
753
|
+
* @returns `true` if signature valid + dispatched (or empty payload).
|
|
754
|
+
* `false` if signature invalid (route should return 401).
|
|
755
|
+
*/
|
|
756
|
+
handleWebhookPayload(rawBody: Buffer | string, signatureHeader: string | undefined): Promise<boolean>;
|
|
757
|
+
/**
|
|
758
|
+
* Parse a signed webhook body, or report `undefined` when it is not JSON.
|
|
759
|
+
*
|
|
760
|
+
* The method's contract is true/false; the route calling it has no reason to expect a throw.
|
|
761
|
+
*/
|
|
762
|
+
private parseBody;
|
|
763
|
+
/**
|
|
764
|
+
* Run one user callback and contain its failure.
|
|
765
|
+
*
|
|
766
|
+
* Meta batches several messages, and their delivery receipts, into a single webhook. Awaiting a
|
|
767
|
+
* handler with nothing around it made one throw skip every remaining message in the payload —
|
|
768
|
+
* and reject `handleWebhookPayload`, so the caller's route answered 500 and Meta redelivered the
|
|
769
|
+
* whole batch, replaying the messages that HAD succeeded (#41).
|
|
770
|
+
*/
|
|
771
|
+
private dispatchContained;
|
|
772
|
+
}
|
|
248
773
|
|
|
249
774
|
/**
|
|
250
775
|
* Webhook helpers for Meta WhatsApp Business Cloud API (ADR D306, D312).
|
|
@@ -279,6 +804,12 @@ declare function verifyWebhookSubscription(query: Record<string, string | undefi
|
|
|
279
804
|
declare function verifyWebhookSignature(rawBody: Buffer | string, signatureHeader: string | undefined, appSecret: string): boolean;
|
|
280
805
|
/** Parse the raw JSON payload into a typed envelope. Returns `null` if shape is unrecognized. */
|
|
281
806
|
declare function parseWebhookPayload(json: unknown): MetaWebhookEnvelope | null;
|
|
807
|
+
/**
|
|
808
|
+
* Extract the inbound messages from one Meta webhook envelope.
|
|
809
|
+
*
|
|
810
|
+
* A single delivery batches entries, changes and messages, and may carry none at all — a
|
|
811
|
+
* status-only delivery is normal. Returns an array, empty when there is nothing to hand on.
|
|
812
|
+
*/
|
|
282
813
|
declare function normalizeInboundMessages(envelope: MetaWebhookEnvelope): WhatsAppInboundEvent[];
|
|
283
814
|
/** Normalize status updates → `WhatsAppStatusReceipt[]`. */
|
|
284
815
|
declare function normalizeStatusReceipts(envelope: MetaWebhookEnvelope): WhatsAppStatusReceipt[];
|
|
@@ -311,6 +842,14 @@ interface WhatsAppWebBackendOptions {
|
|
|
311
842
|
/** Test seam: theokit home for PID locks. */
|
|
312
843
|
readonly theokitHome?: string;
|
|
313
844
|
}
|
|
845
|
+
/**
|
|
846
|
+
* WhatsApp backend driving `whatsapp-web.js` in a child process.
|
|
847
|
+
*
|
|
848
|
+
* Unofficial: it automates a WhatsApp Web session, which Meta's terms do not sanction and which can
|
|
849
|
+
* get a number banned. It exists for a personal number that has no Cloud API access. The browser
|
|
850
|
+
* runs out-of-process behind a PID lock so a crashed or orphaned bridge cannot be left holding the
|
|
851
|
+
* session.
|
|
852
|
+
*/
|
|
314
853
|
declare class WhatsAppWebBackend implements WhatsAppBackend {
|
|
315
854
|
private readonly opts;
|
|
316
855
|
readonly kind: "web";
|
|
@@ -319,6 +858,8 @@ declare class WhatsAppWebBackend implements WhatsAppBackend {
|
|
|
319
858
|
private inboundHandler?;
|
|
320
859
|
private statusHandler?;
|
|
321
860
|
private readonly pending;
|
|
861
|
+
/** Rejects an in-flight `connect()` when the bridge reports it cannot start. */
|
|
862
|
+
private connectRejectors;
|
|
322
863
|
private msgIdCounter;
|
|
323
864
|
private botPhone?;
|
|
324
865
|
private connected;
|
|
@@ -329,15 +870,40 @@ declare class WhatsAppWebBackend implements WhatsAppBackend {
|
|
|
329
870
|
private cleanupHandle;
|
|
330
871
|
connect(): Promise<boolean>;
|
|
331
872
|
disconnect(): Promise<void>;
|
|
332
|
-
send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult
|
|
873
|
+
send(message: WhatsAppOutboundMessage): Promise<WhatsAppSendResult>;
|
|
333
874
|
onInbound(handler: (event: WhatsAppInboundEvent) => Promise<void>): () => void;
|
|
334
875
|
onStatusReceipt(handler: (receipt: WhatsAppStatusReceipt) => Promise<void>): () => void;
|
|
335
876
|
private handleReady;
|
|
336
877
|
private handleMessage;
|
|
878
|
+
/**
|
|
879
|
+
* A bridge that reported a failure has failed — say so now, not in two minutes.
|
|
880
|
+
*
|
|
881
|
+
* This used to write the message to stderr and return. `connect()` races only the `ready`
|
|
882
|
+
* promise against the timeout, so a bridge that told us exactly what was wrong and exited
|
|
883
|
+
* still cost the caller the full `connectTimeoutMs` and surfaced as a timeout — the one
|
|
884
|
+
* error that carries no information. The diagnosis was printed where nothing could act on
|
|
885
|
+
* it, which is the swallowing `rules/error-handling.md` § 5 names.
|
|
886
|
+
*/
|
|
887
|
+
private handleBridgeError;
|
|
337
888
|
private handleSendAck;
|
|
338
889
|
private handleStatus;
|
|
339
890
|
private dispatch;
|
|
340
891
|
}
|
|
892
|
+
/**
|
|
893
|
+
* Where the bridge script lives, for the layout this module is running from.
|
|
894
|
+
*
|
|
895
|
+
* The single hard-coded `../../bridge/...` this replaced was written against the SOURCE
|
|
896
|
+
* tree — `src/backend/web/` up two is `src/`, which is right. The bundle is one flat file
|
|
897
|
+
* at `dist/index.js`, so the same relative path resolved to `packages/bridge/...`, one
|
|
898
|
+
* directory above the package. Nothing caught it: every test injects `spawnFactory`, so the
|
|
899
|
+
* real spawn had never run, and when it did the child died with `MODULE_NOT_FOUND` and
|
|
900
|
+
* `connect()` reported a 120-second timeout — the one error carrying no information about
|
|
901
|
+
* what actually happened.
|
|
902
|
+
*
|
|
903
|
+
* Both layouts are checked, and neither existing is an error rather than a guess: a path
|
|
904
|
+
* that does not exist can only fail later, further from the cause.
|
|
905
|
+
*/
|
|
906
|
+
declare function defaultBridgeScriptPath(): string;
|
|
341
907
|
|
|
342
908
|
/**
|
|
343
909
|
* IPC protocol between adapter and `whatsapp-web.js` subprocess bridge.
|
|
@@ -383,6 +949,12 @@ type IpcEvent = {
|
|
|
383
949
|
} | {
|
|
384
950
|
readonly event: "error";
|
|
385
951
|
readonly message: string;
|
|
952
|
+
/**
|
|
953
|
+
* Machine-readable cause, when the bridge could name one. Absent on older bridges and
|
|
954
|
+
* on failures it cannot classify, which is why every consumer must tolerate it being
|
|
955
|
+
* undefined rather than switching exhaustively.
|
|
956
|
+
*/
|
|
957
|
+
readonly code?: string;
|
|
386
958
|
};
|
|
387
959
|
/** Parse one JSON-line. Returns null on malformed. */
|
|
388
960
|
declare function parseEvent(line: string): IpcEvent | null;
|
|
@@ -407,12 +979,69 @@ declare class LineBuffer {
|
|
|
407
979
|
*
|
|
408
980
|
* @internal
|
|
409
981
|
*/
|
|
982
|
+
|
|
410
983
|
type ErrorPayload = Required<WhatsAppSendResult>["error"];
|
|
984
|
+
/**
|
|
985
|
+
* Public input shape for the {@link ConfigurationError} constructor.
|
|
986
|
+
*
|
|
987
|
+
* Aliased from the core rather than redeclared. The base type exists precisely so every
|
|
988
|
+
* adapter stops writing its own copy of the same three fields, and a redeclaration means a
|
|
989
|
+
* field added to the core silently never reaches this package. Four siblings alias it the
|
|
990
|
+
* same way.
|
|
991
|
+
*/
|
|
992
|
+
type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;
|
|
993
|
+
/**
|
|
994
|
+
* A required option is missing or empty.
|
|
995
|
+
*
|
|
996
|
+
* Raised where a consumer hands us configuration — the factories — rather than later, when
|
|
997
|
+
* the value is finally used against the network. A factory that returns an adapter which
|
|
998
|
+
* cannot authenticate has moved the error away from its cause: the stack then names a send,
|
|
999
|
+
* and the mistake was in construction.
|
|
1000
|
+
*
|
|
1001
|
+
* Matches the shape every sibling adapter uses (`gateway-line`, `gateway-email`, …), which
|
|
1002
|
+
* is what makes one `catch (e) { if (e instanceof GatewayConfigurationError) }` work across
|
|
1003
|
+
* all of them.
|
|
1004
|
+
*
|
|
1005
|
+
* @public
|
|
1006
|
+
*/
|
|
1007
|
+
declare class ConfigurationError extends GatewayConfigurationError {
|
|
1008
|
+
readonly name = "ConfigurationError";
|
|
1009
|
+
constructor(opts: ConfigurationErrorOptions);
|
|
1010
|
+
}
|
|
1011
|
+
/**
|
|
1012
|
+
* The bridge reported, on its own protocol, that it cannot start.
|
|
1013
|
+
*
|
|
1014
|
+
* Distinct from {@link WhatsAppConnectTimeoutError}, which says only that nothing arrived in
|
|
1015
|
+
* time. This one carries what the bridge said — and, when it could classify itself, a
|
|
1016
|
+
* machine-readable `code` such as `peer_missing`, `peer_incompatible` or `peer_load_failed`.
|
|
1017
|
+
* The difference matters to a caller: a timeout may be worth retrying, and a peer dependency
|
|
1018
|
+
* that does not export what we need never will be.
|
|
1019
|
+
*
|
|
1020
|
+
* @public
|
|
1021
|
+
*/
|
|
1022
|
+
declare class WhatsAppBridgeError extends Error {
|
|
1023
|
+
readonly name = "WhatsAppBridgeError";
|
|
1024
|
+
/** Cause as named by the bridge, when it could name one. */
|
|
1025
|
+
readonly code: string | undefined;
|
|
1026
|
+
constructor(message: string, code?: string);
|
|
1027
|
+
}
|
|
411
1028
|
/** Custom error: `connect()` timed out waiting for "ready" (EC-6). */
|
|
412
1029
|
declare class WhatsAppConnectTimeoutError extends Error {
|
|
413
1030
|
constructor(timeoutMs: number);
|
|
414
1031
|
}
|
|
1032
|
+
/**
|
|
1033
|
+
* Map a Cloud API HTTP failure into the canonical `{ code, message }` payload.
|
|
1034
|
+
*
|
|
1035
|
+
* Takes the status alongside the body because Meta returns the same envelope shape for very
|
|
1036
|
+
* different faults, and the status is what separates a rejected payload from an expired token.
|
|
1037
|
+
*/
|
|
415
1038
|
declare function mapWhatsAppCloudError(status: number, body: unknown): ErrorPayload;
|
|
1039
|
+
/**
|
|
1040
|
+
* Map an error string from the `whatsapp-web.js` bridge into the canonical payload.
|
|
1041
|
+
*
|
|
1042
|
+
* The bridge speaks over IPC and can only send text, so this is the boundary where a line of stderr
|
|
1043
|
+
* becomes a structured error. `undefined` maps to an `unknown` code rather than throwing.
|
|
1044
|
+
*/
|
|
416
1045
|
declare function mapWhatsAppWebError(ipcError: string | undefined): ErrorPayload;
|
|
417
1046
|
|
|
418
1047
|
/**
|
|
@@ -429,4 +1058,4 @@ declare function mapWhatsAppWebError(ipcError: string | undefined): ErrorPayload
|
|
|
429
1058
|
*/
|
|
430
1059
|
declare function splitForWhatsApp(text: string): string[];
|
|
431
1060
|
|
|
432
|
-
export { type IpcCommand, type IpcEvent, LineBuffer, WhatsAppAdapter, type WhatsAppAdapterOptions, type WhatsAppBackend, WhatsAppCloudBackend, type WhatsAppCloudBackendOptions, type WhatsAppCloudConfig, WhatsAppConnectTimeoutError, type WhatsAppInboundEvent, type WhatsAppOutboundMessage, type WhatsAppSendResult
|
|
1061
|
+
export { type BaileysSocketFactory, type BaileysSocketLike, type BaileysSocketOptions, ConfigurationError, type ConfigurationErrorOptions, type IpcCommand, type IpcEvent, LineBuffer, type MetaTemplateComponent, WhatsAppAdapter, type WhatsAppAdapterCommonOptions, type WhatsAppAdapterOptions, type WhatsAppBackend, WhatsAppBaileysBackend, type WhatsAppBaileysBackendOptions, type WhatsAppBaileysConfig, WhatsAppBridgeError, WhatsAppCloudBackend, type WhatsAppCloudBackendOptions, type WhatsAppCloudConfig, WhatsAppConnectTimeoutError, type WhatsAppInboundEvent, type WhatsAppOutboundMessage, type WhatsAppSendResult, type WhatsAppStatusReceipt, WhatsAppWebBackend, type WhatsAppWebBackendOptions, type WhatsAppWebConfig, createBaileysSocket, defaultBridgeScriptPath, digitsOnly, formatCommand, mapWhatsAppCloudError, mapWhatsAppWebError, normalizeInboundMessages, normalizeStatusReceipts, parseEvent, parseWebhookPayload, splitForWhatsApp, verifyWebhookSignature, verifyWebhookSubscription };
|