@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/CHANGELOG.md +172 -0
- package/dist/bridge/whatsapp-web-bridge.mjs +79 -11
- package/dist/index.cjs +977 -164
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +570 -46
- package/dist/index.d.ts +570 -46
- package/dist/index.js +974 -165
- package/dist/index.js.map +1 -1
- package/package.json +16 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,177 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 389bd0d: **`WhatsAppAdapter.fromCloud()` and `.fromWeb()` now exist.** The class docblock has instructed consumers to call them since the package was written, and neither did. Three exported types described that API — `WhatsAppAdapterOptions`, `WhatsAppCloudConfig`, `WhatsAppWebConfig` — and no source file consumed any of them. Anyone following the only construction guidance the package gave wrote code that did not compile.
|
|
8
|
+
|
|
9
|
+
The factories build the backend and delegate to the constructor, so a consumer stops importing `WhatsAppCloudBackend` to pass it in. The constructor stays for tests and for a backend of your own.
|
|
10
|
+
|
|
11
|
+
They also validate — `accessToken`, `phoneNumberId`, `sessionId`, and `apiVersion` when it is supplied. Deliberately **not** `appSecret`: it verifies inbound webhook signatures and outbound never reads it, so requiring it would lock an outbound-only consumer out of the path the factory exists to offer. This repository's own integration suite passes `""` for exactly that reason. `fromCloud` with an empty `accessToken` now throws `ConfigurationError` at construction rather than returning an adapter that fails later against the network — a factory that hands back something which cannot authenticate has moved the error away from its cause, so the stack names a send when the mistake was in construction. `ConfigurationError` extends the core's `GatewayConfigurationError` and carries this package's prefix, so one `catch (e) { if (e instanceof GatewayConfigurationError) }` works across the adapters that use it. Counted rather than assumed: four of the nine siblings do — line, matrix, mattermost and sms. The other five (discord, email, slack, teams, telegram) do not reference the base at all, so this is a convergence toward a shared base and not yet a property of the whole family.
|
|
12
|
+
|
|
13
|
+
`WhatsAppAdapter.from(options)` is the entry point for configuration that arrives as **data** — read from a file, an environment or a tenant record — where the backend is a string rather than a decision made in code. It is what `WhatsAppAdapterOptions` exists for, and until it had that consumer the union was exported, documented and inert, which is the defect #47 was filed about.
|
|
14
|
+
|
|
15
|
+
`WhatsAppAdapterOptions` was reshaped: the union now carries only what differs between backends. `requireMention`, `botPhoneId` and `allowedSenders` mean the same thing on either one and moved to `WhatsAppAdapterCommonOptions`, so there is one copy rather than one per arm for the two to drift apart. Nothing consumed the type before, so no caller can break.
|
|
16
|
+
|
|
17
|
+
Worth naming why the alternative was rejected: deleting the promise and documenting the real constructor was cheaper and equally honest, and it was the front-runner until a third backend became concrete. With three, picking one by a string discriminator is the ergonomics the union was written for.
|
|
18
|
+
|
|
19
|
+
`quality:doc-coverage` read 100% throughout, because it measures whether a docblock exists and not whether it is true.
|
|
20
|
+
|
|
21
|
+
**A misconfiguration that used to be silent now says so.** `requireMention` defaults on and `botPhoneId` has nothing to default from on the web backend, so a web adapter built without one dropped every group message and explained nothing — the adapter cannot tell whether it was mentioned. The drop is now logged, matching the sibling allowlist check fifteen lines below it, whose own comment says a silent drop is indistinguishable from a broken gateway.
|
|
22
|
+
|
|
23
|
+
**Known cost, measured.** `fromWeb` holds a static reference to `WhatsAppWebBackend`, so a bundler can no longer drop the web backend from a cloud-only consumer's build: an esbuild bundle of `import { WhatsAppAdapter }` alone grows from 6,565 to 33,780 bytes. No new runtime dependency is pulled — `whatsapp-web.js` is still only `import()`ed inside the spawned bridge, never at import time. Accepted rather than fixed: this package targets Node, where that size is not a user-facing cost, and the alternative is an async factory, which is a worse API for every consumer in order to serve bundle size for some.
|
|
24
|
+
|
|
25
|
+
- 66e08ba: **A third WhatsApp backend: `WhatsAppBaileysBackend`.** It speaks the WhatsApp Web multi-device protocol over a WebSocket. Where the `web` backend drives a headless Chromium through `whatsapp-web.js`, this holds a socket — that is the whole difference in kind.
|
|
26
|
+
|
|
27
|
+
Reach it with `WhatsAppAdapter.fromBaileys({ sessionDir })`, or through `WhatsAppAdapter.from({ backend: "baileys", baileys: { … } })` when the choice arrives as configuration rather than as a decision in code. `baileys` is an **optional peer dependency** (`>=7.0.0-rc14`), loaded lazily at connect: a consumer who never constructs this never needs it installed.
|
|
28
|
+
|
|
29
|
+
**Added rather than replacing**, for three reasons a substitution would not give. Nobody loses a paired session — a Puppeteer profile and a multi-file auth state are not interchangeable. The comparison against the incumbent becomes measurable rather than asserted, which is the whole point: no comparison has been made yet, and this changeset does not claim one. And retreat stays cheap, because nobody is forced onto it.
|
|
30
|
+
|
|
31
|
+
**Unofficial, and no amount of code changes that.** It automates a WhatsApp Web session, which Meta's terms do not sanction and which can get a number banned. Use a number created for this and nothing else, never a personal one.
|
|
32
|
+
|
|
33
|
+
Three decisions worth naming:
|
|
34
|
+
|
|
35
|
+
_Sends are serialised_ — one `sendMessage` in flight per socket, including when one times out. That last clause was not true when this was first written: the queue advanced on the raced result, and a timeout does not cancel a `sendMessage`, so a timed-out send stayed on the socket while the next one started — reaching the exact hazard the serialisation exists to prevent, through the timeout meant to bound it. A review found it; there is now a test that fails if the queue goes back to advancing on the race. Honest about provenance: both peer gateways studied do this and one records that concurrent sends on a single socket can misdeliver to the wrong chat. **We have not measured that in our own code**, so it is precaution rather than a reproduction of our own bug. Kept because the cost is one promise chain and the failure it guards against is a message reaching the wrong person.
|
|
36
|
+
|
|
37
|
+
_A timed-out send reports undetermined delivery, and is never retried._ A local timeout says the acknowledgement did not arrive, not that the message did not; retrying can duplicate — the failure this repository already shipped once, in the email backend re-answering its inbox.
|
|
38
|
+
|
|
39
|
+
_A connect that fails or is superseded tears its socket down._ A timed-out connect used to leave a live socket behind: it kept feeding inbound into the handler, and the retry opened a second live session — which on an unofficial automation is ban surface, not merely a leak. The same generation counter makes `disconnect()` during an in-flight `connect()` safe; without it the late success set `connected` over a backend with no socket, and every later send was refused until the object was rebuilt.
|
|
40
|
+
|
|
41
|
+
_The backend depends on a three-member socket contract we declare_, not on Baileys' types. That is what lets every test in this backend drive a fake and run with `baileys` absent — which matters, because a backend that could only be exercised with the real library installed is a backend exercised by nothing, and that is exactly how the `web` backend reached production unable to start.
|
|
42
|
+
|
|
43
|
+
_A retired connection attempt is ended, not merely silenced._ Retiring by generation made an abandoned attempt's listeners no-ops — including the one that resolves it — so nothing could settle it but the timeout. A `disconnect()` during pairing therefore blocked shutdown for the full 60s default while the socket it asked to close stayed live. And a socket that closed under the backend kept its reference until the next `connect()` overwrote it, so it was never ended and no later `disconnect()` could reach it. Both are fixed, as is a third window a later round found: a `disconnect()` landing while the factory itself was still awaiting — a dynamic import, the auth state off disk, and a network round-trip for the protocol version all happen before a socket exists — could not see an attempt that had no socket yet. Each has a test that fails when its fix alone is reverted.
|
|
44
|
+
|
|
45
|
+
_A failed connect says why._ `false` with no output cannot distinguish a network blip from a device the operator unlinked from their phone, and only one of those is worth retrying — a supervisor that cannot tell them apart retries forever against a session that can only be re-paired.
|
|
46
|
+
|
|
47
|
+
_Pairing has somewhere to go._ `printQRInTerminal` stays off — a library writing to stdout decides where a host's output goes — so the QR is handed to an `onQr` callback, defaulting to stderr. Without it a fresh session directory could only ever time out: there is no other way to pair.
|
|
48
|
+
|
|
49
|
+
**What no test here proves.** Nothing in this repository touches WhatsApp. Pairing needs a QR scan by a human and there is no WhatsApp in Docker, so protocol conformance, delivery, receipts and ban behaviour are unproven by this changeset and by every gate in this repository. A green suite means our logic does what we think — not that WhatsApp agrees.
|
|
50
|
+
|
|
51
|
+
The socket contract this backend depends on lost a member: `logout()` was declared and called by nothing, and on WhatsApp `logout()` **unpairs the device** — the opposite of what `disconnect()` means here. A dead member advertising a destructive capability is worse than an absent one.
|
|
52
|
+
|
|
53
|
+
`WhatsAppMessageEvent.whatsapp.backend` and `WhatsAppBackend.kind` gain a third member, so an exhaustive `switch` over either stops compiling until the case is handled. No call site in this repository switches on them.
|
|
54
|
+
|
|
55
|
+
- fe1f25c: **The `web` backend never started, and when it failed it said nothing useful.** Three defects, each hiding the next.
|
|
56
|
+
|
|
57
|
+
**It died before reaching a browser.** The bridge read `Client` and `LocalAuth` off the module namespace of `whatsapp-web.js`. That package ends its `module.exports` object with a spread, and `cjs-module-lexer` — which Node uses to synthesise named exports for a CommonJS module — cannot statically analyse an object built that way. It proved `Client` and gave up: measured on 1.34.7, `mod.LocalAuth` is `undefined` while `mod.default.LocalAuth` is a function. The API now comes off the default export, with a namespace fallback for a true-ESM module.
|
|
58
|
+
|
|
59
|
+
**It could not be found at all from the published package.** `defaultBridgeScriptPath()` walked `../../bridge/` from the module — correct in the source tree, where `src/backend/web/` up two is `src/`. The bundle is one flat file at `dist/index.js`, so the same walk landed on `packages/bridge/`, one directory above the package. The child died with `MODULE_NOT_FOUND`. Both layouts are now checked, and neither existing raises a named error instead of returning a path that cannot work.
|
|
60
|
+
|
|
61
|
+
**And every one of those failures surfaced as a timeout.** `connect()` raced only the `ready` promise; a bridge that reported exactly what was wrong had its message written to stderr and dropped. The caller paid the full `connectTimeoutMs` — two minutes by default — and received `WhatsAppConnectTimeoutError`, the one error carrying no cause. A reported failure now rejects `connect()` immediately with `WhatsAppBridgeError`, which is new and exported, and carries a machine-readable `code`: `peer_missing`, `peer_incompatible`, `peer_load_failed` or `bridge_script_missing`. The `IpcEvent` error arm carries that code too.
|
|
62
|
+
|
|
63
|
+
A package that is present but does not export what the bridge needs is now distinguished from one that is absent — telling a consumer to run `pnpm add` for a package they already have sends them the wrong way. `ERR_MODULE_NOT_FOUND` separates them.
|
|
64
|
+
|
|
65
|
+
**What this does not fix.** No browser is installed here, because `puppeteer` is absent from `pnpm.onlyBuiltDependencies`. That failure is now reported rather than crashed on, with Chrome's own install command in the message, but the backend still cannot reach WhatsApp. Tracked separately.
|
|
66
|
+
|
|
67
|
+
Minor rather than patch: `WhatsAppBridgeError` and `defaultBridgeScriptPath` join the public API, and `IpcEvent`'s error arm gains an optional `code`.
|
|
68
|
+
|
|
69
|
+
Nothing had ever executed any of this. Every test injected a fake child process, and the live suite excludes the web backend by declaration, so 132 green tests sat over a backend that could not start, could not be found, and could not say so. Seven tests now drive the real script and the real spawn — and each was checked by reverting the fix it covers and confirming it goes red.
|
|
70
|
+
|
|
71
|
+
- c1d40db: **The Cloud API error mapper now recognises the codes Meta actually sends.** It recognised none of them.
|
|
72
|
+
|
|
73
|
+
`cloudErrorCode` tested `errCode === 130 || errCode === 131`. No Cloud API response can satisfy that — the codes in those families are six digits (`130429`, `131047`, `131026`, `130403`). Someone truncated the prefixes, the rate-limit branch became dead code, and every real throttle reached the caller as `invalid_request`. A consumer with backoff behind `code === "rate_limit"` never saw it fire, and kept calling an API that was throttling it.
|
|
74
|
+
|
|
75
|
+
The unit test that claimed to cover this passed a fabricated code `130` and asserted `rate_limit` — which it got from the HTTP 429 in the same call, not from the code. It proved the mapper agreed with whoever wrote the test. Every code in the suite is now one Meta publishes, with the number stated in the test.
|
|
76
|
+
|
|
77
|
+
**Two new codes, because collapsing them threw away the answer.**
|
|
78
|
+
|
|
79
|
+
`session_window_expired` (`131047`) — more than 24 hours since the recipient last replied. The credential is valid and the payload is correct; WhatsApp policy refuses free-form text outside that window, and Meta's own remedy is to resend as an approved template. Reported as `invalid_request`, that instruction was indistinguishable from "your JSON is wrong". The message now carries the remedy too.
|
|
80
|
+
|
|
81
|
+
`undeliverable` (`131026`, `130403`) — the recipient has no WhatsApp account, has not accepted the terms, is on an outdated client, or has been blocked by the business. Terminal: no retry changes it, which is the opposite of what `invalid_request` suggests.
|
|
82
|
+
|
|
83
|
+
Rate limiting now covers `4` (app), `80007` (business account) and `130429` (Cloud API throughput), alongside the HTTP 429 that was doing all the work.
|
|
84
|
+
|
|
85
|
+
Minor rather than patch: `WhatsAppSendResult["error"]["code"]` gains two members, so an exhaustive `switch` over it stops compiling until the new cases are handled. That is the intended prompt — the two conditions were always reachable, and were being silently mislabelled.
|
|
86
|
+
|
|
87
|
+
- c157088: **A fail-closed sender allowlist.** The package had no sender filter at all. `shouldDropGroupMessage` fires only for _groups_ with `requireMention`, so any stranger who sent a direct message reached the handler — and from there whatever agent is behind it.
|
|
88
|
+
|
|
89
|
+
That is two problems wearing one coat. A number that answers strangers accumulates blocks and reports, which is what WhatsApp's enforcement runs on, so an open gateway is a slow route to a banned number. And an agent wired to tools acts on what arrives, so an unfiltered inbound is an instruction channel for anyone who knows the number.
|
|
90
|
+
|
|
91
|
+
Pass `allowedSenders` to the adapter — a comma-separated list — and anything not on it is dropped and logged. `"*"` opens it, and has to be written deliberately.
|
|
92
|
+
|
|
93
|
+
**Absent and empty are different answers, on purpose.** No `allowedSenders` at all means the filter has not been adopted and delivery is unchanged; turning it on by default would mute every existing deployment, which is a breaking change and belongs to its own decision. An empty `allowedSenders` means someone configured a list and named nobody, and that is honoured: nobody gets through. The inverse default is a mistake worth naming — it makes the safest-looking configuration, the empty one, the most open.
|
|
94
|
+
|
|
95
|
+
An unidentifiable sender is refused even under the wildcard: `*` means "any sender", and something whose sender cannot be named is not a sender.
|
|
96
|
+
|
|
97
|
+
Identifier matching handles the shapes WhatsApp and humans actually produce — `5511999999999@s.whatsapp.net`, a `:12` device suffix, `+55 (11) 99999-9999`, and group JIDs. The device suffix is stripped before digits are taken; folding it in yields `551199999999912`, which matches nothing, so an allowlist would silently stop recognising a sender the moment they paired a second device.
|
|
98
|
+
|
|
99
|
+
Refusals are logged. A silent drop is indistinguishable from a broken gateway, and a mistyped allowlist otherwise presents as a bot that went mute for no reason.
|
|
100
|
+
|
|
101
|
+
- 90d3720: **`WhatsAppCloudBackend.sendTemplate()` — the send that reaches someone who has not written first.**
|
|
102
|
+
|
|
103
|
+
The adapter could only send `type: "text"`, and Meta refuses free-form text more than 24 hours after the recipient last replied. That excluded every notification use case, and it made the integration impossible to check unattended: the live suite's outbound test asserted success while its own comment admitted it would fail on policy, so a red run meant "the recipient has not written recently" as often as it meant "something is broken".
|
|
104
|
+
|
|
105
|
+
Templates carry no such condition. `hello_world` is pre-approved on every WhatsApp Business account, so validating outbound now needs nothing arranged by hand.
|
|
106
|
+
|
|
107
|
+
It is deliberately **not** on the `WhatsAppBackend` interface. WhatsApp Web has no concept of templates, and widening the shared contract would hand the web backend a method it could only throw from. Reach it by holding `WhatsAppCloudBackend` directly.
|
|
108
|
+
|
|
109
|
+
`components` is omitted from the payload when absent rather than sent empty, because Meta rejects `components: []` on a template that declares no variables. The POST-and-interpret half of `sendText` moved into a shared `postMessage` rather than being copied.
|
|
110
|
+
|
|
111
|
+
The live outbound test now checks the template send, and the free-form text test asserts the pair it can honestly assert: either the message went out, or Meta refused it for the one documented policy reason and the mapper reported `session_window_expired`. An auth failure, a malformed payload or an unrecognised code still fail, and are now distinguishable from a recipient who simply has not written lately.
|
|
112
|
+
|
|
113
|
+
### Patch Changes
|
|
114
|
+
|
|
115
|
+
- e682180: **A message whose handler throws no longer kills the bot.** On Teams and on WhatsApp's web backend it did — not degraded delivery, an exit code. `Error: ... / Node.js v22.22.2`, and the next message never arrived.
|
|
116
|
+
|
|
117
|
+
Both dispatched with `void handler(event)`. `void` reads as "I am not waiting for this"; what it tells the runtime is "I am not handling the error", and under Node 22's default an unhandled rejection ends the process. Measured against both adapters through their own injection seams before the fix, and again after: the throw is now contained, named, and delivery continues.
|
|
118
|
+
|
|
119
|
+
**Discord and Telegram contained it but blamed the wrong thing.** The rejection escaped into the platform library's error channel, so a bug in the consumer's own handler surfaced as `[discord] client error` / `[telegram] bot error`. Anyone debugging that went looking in discord.js and grammy for a fault that was in their own code. Both now report `handler threw` and return `"handler_threw"` from the internal dispatch seam.
|
|
120
|
+
|
|
121
|
+
**WhatsApp Cloud dropped the rest of the batch, and made the platform resend it.** Meta packs several messages and their delivery receipts into one webhook, and the dispatch loop awaited each handler with nothing around it. One throw skipped every remaining message in the payload, skipped the status receipts, and rejected `handleWebhookPayload` — so the caller's route answered 500 and Meta redelivered the whole batch, replaying the messages that had already been handled. That is a duplicate-reply bug reached through a different door than the one fixed in #11. The same method also now answers `false` on a signed body that is not JSON, instead of throwing out of a method whose contract is `true`/`false`.
|
|
122
|
+
|
|
123
|
+
**Email gained a net it did not strictly need.** Its drain is written never to reject, and it does not — but both launch sites discard the promise, so that property was the only thing between a future edit and the same fatal rejection, and nothing enforced it. The catch now lives at the site that would pay for it.
|
|
124
|
+
|
|
125
|
+
**The contract is written down, and held to.** `BasePlatformAdapter.onInbound` now states it: a handler may throw, and an adapter must contain that throw, report it as the handler's failure rather than the platform's, and keep delivering. Eight of ten adapters had converged on exactly that with nothing recording it. `tests/lint/adapter-contract.test.ts` gains two invariants — every adapter names a handler throw as the handler's, and no adapter launches a user callback with a bare `void` — and both were checked against a deliberately reverted adapter to confirm they fire rather than pass vacuously.
|
|
126
|
+
|
|
127
|
+
- 272e111: **`WhatsAppCloudBackend` and `WhatsAppWebBackend` now identity-guard their unsubscribes.** Both are public exports implementing the exported `WhatsAppBackend` interface, so a consumer holding a backend directly — rather than going through `WhatsAppAdapter` — hit `onInbound(A)` → `onInbound(B)` → `A.off()` and stopped receiving anything, with no error and no crash. The Baileys backend had the guard; its two siblings never did.
|
|
128
|
+
|
|
129
|
+
The reason the gap survived is worth more than the fix: the cross-adapter contract test checked this invariant **per package**, so one compliant file covered every other file beside it. It now checks per declaration.
|
|
130
|
+
|
|
131
|
+
- 8cbf136: **Every published export now carries documentation.** Forty-seven public symbols shipped with no docblock at all, so a consumer hovering `DiscordAdapter`, `SlackAdapter`, `WhatsAppCloudBackend`, `ThreadStore` or any of the error classes got an empty tooltip. Coverage across the eleven packages went from 71.2% to 100% (163/163), measured over the published declarations rather than the source, because a docblock is not documentation until it survives the build.
|
|
132
|
+
|
|
133
|
+
The text says what each symbol is for and what constrains it, not what its name already says. `TelegramAdapter` records that a bot cannot enumerate its chats nor speak into one that has not spoken first. `DiscordAdapter` records that reading message content needs a privileged intent enabled in the developer portal, without which every `event.text` arrives empty and nothing says why. `WhatsAppWebBackend` records that it is unofficial and can get a number banned. `shouldDispatchSyncEvent` records that Matrix replays history on sync, which is why a freshly started bot would otherwise answer every message it can still see.
|
|
134
|
+
|
|
135
|
+
**`gateway-slack`'s README documented a type that does not exist.** Its usage example imported `GatewayMessageEvent` from `@theokit/gateway`. That name is an internal alias inside the Discord and Telegram adapters (`MessageEvent as GatewayMessageEvent`), never an export. A reader who copied the example got code that did not compile. It now imports `MessageEvent`, which is what `onInbound` actually hands the handler.
|
|
136
|
+
|
|
137
|
+
Two docblocks that attached to nothing were reattached: `acquirePidLock` in `gateway-whatsapp` had its documentation stranded thirty lines above, over a different function, and shipped undocumented as a result.
|
|
138
|
+
|
|
139
|
+
- b8ef098: **Every package now ships the licence it declares.** All twelve manifests in this repository declare `Apache-2.0`, and the repository had no `LICENSE` file at all — not at the root, and not in any package directory except `gateway-email`. So each published tarball asserted a licence while carrying none of its terms, and §4(a) of that licence requires a copy to travel with the distribution. Worse than a missing file: with no licence text anywhere, everything outside the manifests fell back to default copyright, which grants a recipient nothing.
|
|
140
|
+
|
|
141
|
+
The text is now at the repository root and inside every publishable package, byte-identical to the canonical Apache License 2.0 with the appendix filled in (`Copyright 2026 usetheo.dev`). The one pre-existing copy, in `gateway-email`, was replaced along with the rest: it carried the same truncated paragraph 4(d) found across the ecosystem, dropping "reasonable and customary use" from the NOTICE clause — a modified body under an unmodified SPDX identifier.
|
|
142
|
+
|
|
143
|
+
**The repository moved to the official `usetheokit` organization.** Existing clones and published URLs keep working through GitHub's permanent redirect; the root manifest now declares `Apache-2.0` explicitly rather than leaving the workspace root silent.
|
|
144
|
+
|
|
145
|
+
- 5bae032: Six defects that broke real conversations, found by testing the adapters against the live platforms instead of against fakes.
|
|
146
|
+
|
|
147
|
+
**LINE — no outbound message was ever delivered.** The adapter called the v9 SDK client with positional arguments while that client takes a single request object, so LINE received an empty request and rejected every send with a 400. Upgrade if you use this adapter at all: nothing it sent reached anyone.
|
|
148
|
+
|
|
149
|
+
**Telegram — the bot froze on long replies.** Any message over 4096 characters that began with an unclosed code span (a stray backtick) put the splitter into an infinite loop, hanging the process until it ran out of memory. Long agent answers now split correctly whatever markdown they contain.
|
|
150
|
+
|
|
151
|
+
**Mattermost — long messages silently vanished.** The adapter never split anything, so any reply over 16,383 characters was rejected by the server and the user simply saw nothing. Long replies are now split into parts Mattermost accepts.
|
|
152
|
+
|
|
153
|
+
**SMS — long messages were rejected from the hundredth part onward.** The `(i/N)` prefix outgrew the space reserved for it, pushing every later part past the provider's limit.
|
|
154
|
+
|
|
155
|
+
**Matrix and LINE — `connect()` reported success with an invalid token.** Both now verify the credential with the server before returning `true`, so a wrong token fails at startup instead of silently receiving nothing forever.
|
|
156
|
+
|
|
157
|
+
**Email and Teams — the bot could go permanently deaf.** Replacing an inbound handler and then disposing of the previous one removed the new handler as well, and the gateway stopped receiving messages with nothing logged.
|
|
158
|
+
|
|
159
|
+
Also: a `pre_inbound` hook that threw put its raw error text into the user's chat, which could expose internal details such as connection strings or tokens. Users now see only which hook failed; the detail goes to the server log, redacted.
|
|
160
|
+
|
|
161
|
+
WhatsApp additionally stops opening a second session when `connect()` is called twice, and its group mention filter no longer treats unrelated digits scattered through a message as a mention of the bot.
|
|
162
|
+
|
|
163
|
+
- 4e6ae26: **The published type declarations now compile.** Five of these packages shipped a `.d.ts` (and matching `.d.cts`) containing type references that resolve to nothing — nine names, replicated across both module formats. `skipLibCheck: true` is on by default in most consumer projects, so the packages installed, imported and looked correct; under type-aware lint, which resolves the real type graph and has no such escape, every type reached through a broken reference degrades to `error`, and ordinary correct calls into these adapters come back flagged `no-unsafe-*`.
|
|
164
|
+
|
|
165
|
+
The names, all now bound: `EmailMessageEvent` (email), `SendResult` and `SlackMessageEvent` (slack), `GatewayConfigurationError` and `GatewayConfigurationErrorOptions` (sms), `TeamsMessageEvent` (teams), `ChildProcess` and `WhatsAppSendResult` (whatsapp).
|
|
166
|
+
|
|
167
|
+
Nothing was wrong with the source — every package's own `tsc --noEmit` was green throughout, which is exactly why this survived. The defect is in how tsup's declaration rollup emits the bundle: it re-exports a name without binding it locally, drops a type-only import from an external module while inlining the declarations that use it, or renames a declaration to avoid a collision and misses one use site. The `sms` names are the newest instance — the shared `GatewayConfigurationError` base introduced in `@theokit/gateway` 0.5.0 turned a local type into an external one, which is the shape the rollup drops.
|
|
168
|
+
|
|
169
|
+
The public surface of every package is unchanged: the same names are exported, and the repair that rewrites a re-export verifies that before and after. What changed is where a name is bound inside the declaration file.
|
|
170
|
+
|
|
171
|
+
- 9e7384e: **A stale unsubscribe no longer deafens the adapter.** The function `onInbound` returned called whichever backend handle was _current_ rather than the one it owned, so `onInbound(A)` → `onInbound(B)` → `A.off()` tore down **B's** subscription and nulled the handler. The adapter then received nothing, with no error and no crash — the worst way for a message bus to fail, because there is nothing in a log to see and nothing to alert on. It is now identity-guarded, and so is `onStatusReceipt`.
|
|
172
|
+
|
|
173
|
+
Worth naming: this is precisely the defect the cross-adapter contract test exists to catch, and this adapter was exempted from it by a comment asserting its mechanism was "a different mechanism with the same guarantee". It had no guard at all. The exemption is removed — the one adapter the gate excused turned out to be the one carrying the defect, which is what an exemption written from a reading of the code rather than a test of it eventually becomes.
|
|
174
|
+
|
|
3
175
|
## 0.1.2
|
|
4
176
|
|
|
5
177
|
### Patch Changes
|
|
@@ -21,26 +21,94 @@ function emit(event) {
|
|
|
21
21
|
process.stdout.write(`${JSON.stringify(event)}\n`);
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
-
|
|
25
|
-
|
|
24
|
+
/**
|
|
25
|
+
* Report a failure on the protocol the parent reads.
|
|
26
|
+
*
|
|
27
|
+
* `code` is what makes the report actionable by a machine. Without it the backend can only
|
|
28
|
+
* substring-match the message, which is how `mapWhatsAppWebError` works and why every
|
|
29
|
+
* startup failure landed on `unknown`.
|
|
30
|
+
*/
|
|
31
|
+
function emitError(message, code) {
|
|
32
|
+
emit({ event: "error", message, ...(code !== undefined ? { code } : {}) });
|
|
26
33
|
}
|
|
27
34
|
|
|
35
|
+
const argv = process.argv.slice(2);
|
|
36
|
+
|
|
37
|
+
/** Value of a `--flag value` pair in argv, or undefined. */
|
|
38
|
+
function argOf(flag) {
|
|
39
|
+
const i = argv.indexOf(flag);
|
|
40
|
+
return i >= 0 ? argv[i + 1] : undefined;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Where to load the WhatsApp Web client from.
|
|
45
|
+
*
|
|
46
|
+
* Injected as an argument rather than read from the environment. An env var is ambient: the
|
|
47
|
+
* parent spawns without an explicit `env`, so the child inherits the host application's
|
|
48
|
+
* whole environment, and any value sitting there would silently control an arbitrary
|
|
49
|
+
* `import()` inside this process. An argument comes from the one caller that spawns us, and
|
|
50
|
+
* every other seam in this repository has the same shape — `__appFactory`, `__imapFactory`,
|
|
51
|
+
* `spawnFactory` — an injection point the parent controls rather than ambient state.
|
|
52
|
+
*/
|
|
53
|
+
const SPECIFIER = argOf("--specifier") ?? "whatsapp-web.js";
|
|
54
|
+
|
|
28
55
|
let Client;
|
|
29
56
|
let LocalAuth;
|
|
30
57
|
try {
|
|
31
|
-
const mod = await import(
|
|
32
|
-
|
|
33
|
-
|
|
58
|
+
const mod = await import(SPECIFIER);
|
|
59
|
+
// D315: read the API off the DEFAULT export, not off synthesised named bindings.
|
|
60
|
+
//
|
|
61
|
+
// `whatsapp-web.js/index.js` ends its `module.exports` object with a spread
|
|
62
|
+
// (`...Constants`). `cjs-module-lexer` cannot statically analyse an object built that
|
|
63
|
+
// way, so Node synthesises only some named exports — measured on 1.34.7, exactly
|
|
64
|
+
// `Client`, while `LocalAuth`, `NoAuth` and `RemoteAuth` exist only on the default.
|
|
65
|
+
// Destructuring the namespace therefore yielded `LocalAuth === undefined`, and the
|
|
66
|
+
// process died at `new LocalAuth(...)` with a TypeError (B-002). The default export is
|
|
67
|
+
// the whole `module.exports` value at runtime, whatever the lexer could prove.
|
|
68
|
+
//
|
|
69
|
+
// The `?? mod` fallback covers a true-ESM module, where there is no default to read.
|
|
70
|
+
const api = mod.default ?? mod;
|
|
71
|
+
Client = api.Client ?? mod.Client;
|
|
72
|
+
LocalAuth = api.LocalAuth ?? mod.LocalAuth;
|
|
34
73
|
} catch (err) {
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
74
|
+
// Absent and broken are different problems. Any throw used to yield "not installed", so a
|
|
75
|
+
// nested missing dependency or a syntax error inside a package that IS installed sent the
|
|
76
|
+
// consumer to install what they already had.
|
|
77
|
+
if (err?.code === "ERR_MODULE_NOT_FOUND") {
|
|
78
|
+
emitError(
|
|
79
|
+
`${SPECIFIER} not installed in your app. Run \`pnpm add whatsapp-web.js\` to use the web backend. (${err?.message ?? err})`,
|
|
80
|
+
"peer_missing",
|
|
81
|
+
);
|
|
82
|
+
} else {
|
|
83
|
+
emitError(
|
|
84
|
+
`${SPECIFIER} is installed but failed to load: ${err?.message ?? err}`,
|
|
85
|
+
"peer_load_failed",
|
|
86
|
+
);
|
|
87
|
+
}
|
|
38
88
|
process.exit(1);
|
|
39
89
|
}
|
|
40
90
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
91
|
+
// D316: a package that is PRESENT but does not expose what we need is a different failure
|
|
92
|
+
// from one that is absent, and it needs a different message. The `catch` above only sees an
|
|
93
|
+
// import that threw; a resolved module missing a member sails past it and surfaces thirteen
|
|
94
|
+
// lines later as an unhandled TypeError the parent cannot map to anything. Telling the
|
|
95
|
+
// consumer to run `pnpm add` for a package they already have is worse than saying nothing.
|
|
96
|
+
for (const [name, value] of [
|
|
97
|
+
["Client", Client],
|
|
98
|
+
["LocalAuth", LocalAuth],
|
|
99
|
+
]) {
|
|
100
|
+
if (typeof value !== "function") {
|
|
101
|
+
emitError(
|
|
102
|
+
`${SPECIFIER} is installed but does not export ${name} as a constructor. ` +
|
|
103
|
+
`Expected a function, got ${typeof value}. This usually means an incompatible version — ` +
|
|
104
|
+
`the web backend expects the peer range declared in @theokit/gateway-whatsapp.`,
|
|
105
|
+
"peer_incompatible",
|
|
106
|
+
);
|
|
107
|
+
process.exit(1);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const sessionId = argOf("--session") ?? "default";
|
|
44
112
|
|
|
45
113
|
const client = new Client({
|
|
46
114
|
authStrategy: new LocalAuth({ clientId: sessionId }),
|