@theokit/gateway 0.5.0 → 0.6.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 +134 -0
- package/LICENSE +201 -0
- package/dist/index.cjs +65 -21
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +66 -6
- package/dist/index.d.ts +66 -6
- package/dist/index.js +65 -22
- package/dist/index.js.map +1 -1
- package/package.json +19 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,139 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.6.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 08abaed: **`GatewayRunner.stop()` is now terminal, and says so instead of leaving a runner nothing can stop.**
|
|
8
|
+
|
|
9
|
+
`start()` and `stop()` were each written to be idempotent, but they guarded on different flags. `stop()` cleared `connected` and set `stopped`; nothing ever cleared `stopped`. So a second `start()` sailed past its `connected` guard, reconnected every adapter and rewired inbound dispatch — while the next `stop()` returned at its own `stopped` guard without disconnecting anything. Measured on the previous release: two connects, one disconnect, and a live inbound handler that no call could take down.
|
|
10
|
+
|
|
11
|
+
Nothing reported this. The adapters stayed connected, the events kept arriving, and both methods returned normally. A process that reloads configuration or reconnects after a network failure by restarting the runner leaked a connection every cycle.
|
|
12
|
+
|
|
13
|
+
`start()` on a stopped runner now throws `GatewayLifecycleError` with `code: "runner_stopped"`, and the message says to construct a new runner. That is the whole of the behaviour change: a call that previously appeared to succeed while corrupting state now fails at the call that cannot be honoured, which is the only point where a caller can still do something about it.
|
|
14
|
+
|
|
15
|
+
Adds `GatewayLifecycleError` and `GatewayLifecycleErrorOptions` to the public API. It is deliberately separate from `GatewayConfigurationError`: that one reports a bad setting, this one reports a fine setting used at an impossible moment.
|
|
16
|
+
|
|
17
|
+
- 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.
|
|
18
|
+
|
|
19
|
+
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.
|
|
20
|
+
|
|
21
|
+
**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.
|
|
22
|
+
|
|
23
|
+
**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.
|
|
24
|
+
|
|
25
|
+
Three decisions worth naming:
|
|
26
|
+
|
|
27
|
+
_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.
|
|
28
|
+
|
|
29
|
+
_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.
|
|
30
|
+
|
|
31
|
+
_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.
|
|
32
|
+
|
|
33
|
+
_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.
|
|
34
|
+
|
|
35
|
+
_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.
|
|
36
|
+
|
|
37
|
+
_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.
|
|
38
|
+
|
|
39
|
+
_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.
|
|
40
|
+
|
|
41
|
+
**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.
|
|
42
|
+
|
|
43
|
+
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.
|
|
44
|
+
|
|
45
|
+
`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.
|
|
46
|
+
|
|
47
|
+
### Patch Changes
|
|
48
|
+
|
|
49
|
+
- 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.
|
|
50
|
+
|
|
51
|
+
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.
|
|
52
|
+
|
|
53
|
+
**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.
|
|
54
|
+
|
|
55
|
+
**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`.
|
|
56
|
+
|
|
57
|
+
**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.
|
|
58
|
+
|
|
59
|
+
**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.
|
|
60
|
+
|
|
61
|
+
- 9c35372: **Slack now answers `empty_text` for empty text, like the other nine adapters.** The contract states it without a condition — `sendMessage` with empty text returns `{ ok: false, code: "empty_text" }` — but Slack checked the connection first, so the same call answered `not_connected` there and `empty_text` everywhere else.
|
|
62
|
+
|
|
63
|
+
Nobody lost a delivery over it: both results are already `ok: false`. What broke is code that branches on the code — treating a caller's bad input one way and an unavailable transport another, with a retry or an alert behind the second. Written against the contract, that code did the right thing on nine platforms and the wrong thing on the tenth, with nothing to say why.
|
|
64
|
+
|
|
65
|
+
The connection guard keeps its reason (`this.app` is set before `app.start()` resolves, so a send in that window would otherwise leak through); only the order changed. Input first, transport second, which is what `rules/error-handling.md` § 2 asks for and what the other nine already did.
|
|
66
|
+
|
|
67
|
+
The cross-adapter gate gains the invariant, and it is checked against a deliberately reverted adapter. That check earned its keep immediately: the first version of the invariant read a window of raw source that its own explanatory comment filled, so it passed against the reverted adapter by matching the prose describing the rule. It now strips comments before asking — a gate answered by a comment is worse than no gate, because it reports coverage it does not have.
|
|
68
|
+
|
|
69
|
+
- 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.
|
|
70
|
+
|
|
71
|
+
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.
|
|
72
|
+
|
|
73
|
+
**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.
|
|
74
|
+
|
|
75
|
+
- 5bae032: Six defects that broke real conversations, found by testing the adapters against the live platforms instead of against fakes.
|
|
76
|
+
|
|
77
|
+
**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.
|
|
78
|
+
|
|
79
|
+
**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.
|
|
80
|
+
|
|
81
|
+
**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.
|
|
82
|
+
|
|
83
|
+
**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.
|
|
84
|
+
|
|
85
|
+
**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.
|
|
86
|
+
|
|
87
|
+
**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.
|
|
88
|
+
|
|
89
|
+
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.
|
|
90
|
+
|
|
91
|
+
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.
|
|
92
|
+
|
|
93
|
+
- 144b2ba: **The `post_outbound` hook now fires.** It is one of the three fire points `GatewayHook` documents and exports, and no production code had ever called it: `HookExecutor.firePostOutbound` existed, was typed, was unit-tested, and had exactly one caller in the repository — its own test.
|
|
94
|
+
|
|
95
|
+
That is the worst shape a broken contract can take. Registering a `post_outbound` hook for delivery auditing, outbound metrics or reply logging raised no error and produced no warning. The hook was simply never invoked, and the instrumentation a consumer believed they had did not exist.
|
|
96
|
+
|
|
97
|
+
Every reply now leaves through one path that sends and then reports, so the hook fires exactly once per attempt with `{ event, outbound, result }` — including the EC-D auto-reply sent when a `pre_inbound` hook blocks with a message, and including the attempt that finds no adapter registered for the event's platform. That last case matters more than it looks: a hook counting deliveries would otherwise omit precisely the replies that went nowhere.
|
|
98
|
+
|
|
99
|
+
The hook observes; it does not intercept. The adapter's `SendResult` reaches the caller of `reply` unchanged, and a hook that throws is contained by `HookExecutor`, so a broken observer cannot turn a delivered reply into a failed one.
|
|
100
|
+
|
|
101
|
+
- 111f837: **`stop()` no longer holds the process open for the whole drain window.** A bot that stopped on `SIGINT` sat there for ten more seconds before the process exited, with nothing running and nothing to wait for.
|
|
102
|
+
|
|
103
|
+
`stop()` drains in-flight handlers by racing them against a `drainTimeoutMs` timer. `Promise.race` settles on whichever branch finishes first and abandons the other — but an abandoned `setTimeout` is still a scheduled timer, and a scheduled timer keeps Node's event loop alive. The drain finished in under a millisecond; the timer it beat kept the process running for the remaining ten seconds. Measured before the fix: `stop()` returned after 0 ms, the process exited after 10 001 ms. After: 1 ms.
|
|
104
|
+
|
|
105
|
+
The delay only appeared once at least one event had been dispatched, since the drain branch is guarded on there being something in flight — which is to say, on every real bot rather than on any test that stopped a runner it had never used. Under an orchestrator that sends `SIGTERM` and then `SIGKILL`, the difference is whether shutdown is clean or forced.
|
|
106
|
+
|
|
107
|
+
The timer handle is now cleared in a `finally`, so the cleanup does not depend on which branch of the race won.
|
|
108
|
+
|
|
109
|
+
## 0.5.1
|
|
110
|
+
|
|
111
|
+
### Patch Changes
|
|
112
|
+
|
|
113
|
+
- 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.
|
|
114
|
+
|
|
115
|
+
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.
|
|
116
|
+
|
|
117
|
+
**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.
|
|
118
|
+
|
|
119
|
+
- 5bae032: Six defects that broke real conversations, found by testing the adapters against the live platforms instead of against fakes.
|
|
120
|
+
|
|
121
|
+
**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.
|
|
122
|
+
|
|
123
|
+
**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.
|
|
124
|
+
|
|
125
|
+
**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.
|
|
126
|
+
|
|
127
|
+
**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.
|
|
128
|
+
|
|
129
|
+
**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.
|
|
130
|
+
|
|
131
|
+
**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.
|
|
132
|
+
|
|
133
|
+
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.
|
|
134
|
+
|
|
135
|
+
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.
|
|
136
|
+
|
|
3
137
|
## 0.5.0
|
|
4
138
|
|
|
5
139
|
### Minor Changes
|
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 usetheo.dev
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/dist/index.cjs
CHANGED
|
@@ -51,7 +51,16 @@ var GatewayConfigurationError = class extends Error {
|
|
|
51
51
|
}
|
|
52
52
|
};
|
|
53
53
|
|
|
54
|
-
// src/
|
|
54
|
+
// src/errors/lifecycle-error.ts
|
|
55
|
+
var GatewayLifecycleError = class extends Error {
|
|
56
|
+
name = "GatewayLifecycleError";
|
|
57
|
+
/** Stable discriminator, so callers branch on `code` rather than on message text. */
|
|
58
|
+
code;
|
|
59
|
+
constructor(opts) {
|
|
60
|
+
super(opts.message);
|
|
61
|
+
this.code = opts.code;
|
|
62
|
+
}
|
|
63
|
+
};
|
|
55
64
|
var HookExecutor = class {
|
|
56
65
|
constructor(hooks) {
|
|
57
66
|
this.hooks = hooks;
|
|
@@ -68,9 +77,13 @@ var HookExecutor = class {
|
|
|
68
77
|
try {
|
|
69
78
|
decision = await h.pre_inbound(ctx);
|
|
70
79
|
} catch (err) {
|
|
80
|
+
process.stderr.write(
|
|
81
|
+
`[gateway] pre_inbound hook "${h.name}" threw: ${sdk.Security.redact(err.message)}
|
|
82
|
+
`
|
|
83
|
+
);
|
|
71
84
|
return {
|
|
72
85
|
block: true,
|
|
73
|
-
message: `hook ${h.name}
|
|
86
|
+
message: `Request blocked: hook "${h.name}" failed.`
|
|
74
87
|
};
|
|
75
88
|
}
|
|
76
89
|
if (decision !== void 0 && decision.block === true) {
|
|
@@ -134,8 +147,19 @@ var GatewayRunner = class {
|
|
|
134
147
|
command(name, handler) {
|
|
135
148
|
this.commands.set(name, handler);
|
|
136
149
|
}
|
|
137
|
-
/**
|
|
150
|
+
/**
|
|
151
|
+
* Connect all adapters and wire inbound dispatch.
|
|
152
|
+
*
|
|
153
|
+
* @throws {GatewayLifecycleError} `runner_stopped` — the runner was already
|
|
154
|
+
* stopped. A stopped runner is spent; construct a new one.
|
|
155
|
+
*/
|
|
138
156
|
async start() {
|
|
157
|
+
if (this.stopped) {
|
|
158
|
+
throw new GatewayLifecycleError({
|
|
159
|
+
code: "runner_stopped",
|
|
160
|
+
message: "GatewayRunner.start(): this runner has already been stopped and cannot be restarted. Construct a new GatewayRunner instead."
|
|
161
|
+
});
|
|
162
|
+
}
|
|
139
163
|
if (this.connected) return;
|
|
140
164
|
const connected = [];
|
|
141
165
|
try {
|
|
@@ -176,10 +200,17 @@ var GatewayRunner = class {
|
|
|
176
200
|
this.unsubs.length = 0;
|
|
177
201
|
const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;
|
|
178
202
|
if (this.inflight.size > 0) {
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
203
|
+
let timer;
|
|
204
|
+
try {
|
|
205
|
+
await Promise.race([
|
|
206
|
+
Promise.all([...this.inflight]).then(() => void 0),
|
|
207
|
+
new Promise((r) => {
|
|
208
|
+
timer = setTimeout(r, drainMs);
|
|
209
|
+
})
|
|
210
|
+
]);
|
|
211
|
+
} finally {
|
|
212
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
213
|
+
}
|
|
183
214
|
}
|
|
184
215
|
await Promise.all(
|
|
185
216
|
[...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => void 0))
|
|
@@ -240,24 +271,36 @@ var GatewayRunner = class {
|
|
|
240
271
|
}
|
|
241
272
|
/** EC-G: per-event ctx whose reply routes to the matching adapter. */
|
|
242
273
|
buildContext(event) {
|
|
243
|
-
const adapter = this.adaptersByPlatform.get(event.platform);
|
|
244
274
|
return {
|
|
245
275
|
event,
|
|
246
|
-
reply: async (text, opts) => {
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
};
|
|
252
|
-
}
|
|
253
|
-
return adapter.sendMessage({
|
|
254
|
-
channel: event.channel,
|
|
255
|
-
text,
|
|
256
|
-
...opts?.format !== void 0 ? { format: opts.format } : {}
|
|
257
|
-
});
|
|
258
|
-
}
|
|
276
|
+
reply: async (text, opts) => this.deliver(event, {
|
|
277
|
+
channel: event.channel,
|
|
278
|
+
text,
|
|
279
|
+
...opts?.format !== void 0 ? { format: opts.format } : {}
|
|
280
|
+
})
|
|
259
281
|
};
|
|
260
282
|
}
|
|
283
|
+
/**
|
|
284
|
+
* Send one outbound on behalf of `event` and report it to `post_outbound`.
|
|
285
|
+
*
|
|
286
|
+
* Every reply leaves through here so the hook fires exactly once per attempt —
|
|
287
|
+
* including the EC-D auto-reply, and including the attempt that finds no
|
|
288
|
+
* adapter for the platform. An audit hook that counted only the deliveries
|
|
289
|
+
* which reached a transport would omit precisely the ones that went nowhere.
|
|
290
|
+
*
|
|
291
|
+
* `post_outbound` observes; it does not intercept. The adapter's `SendResult`
|
|
292
|
+
* is returned to the caller unchanged, and `HookExecutor` already contains a
|
|
293
|
+
* throwing hook, so a broken observer cannot turn a delivered reply into a
|
|
294
|
+
* failed one.
|
|
295
|
+
*
|
|
296
|
+
* @internal
|
|
297
|
+
*/
|
|
298
|
+
async deliver(event, outbound) {
|
|
299
|
+
const adapter = this.adaptersByPlatform.get(event.platform);
|
|
300
|
+
const result = adapter === void 0 ? { ok: false, error: { code: "no_adapter", message: `no adapter for ${event.platform}` } } : await adapter.sendMessage(outbound);
|
|
301
|
+
await this.hookExecutor.firePostOutbound({ event, outbound, result });
|
|
302
|
+
return result;
|
|
303
|
+
}
|
|
261
304
|
};
|
|
262
305
|
|
|
263
306
|
// src/session/router.ts
|
|
@@ -369,6 +412,7 @@ function chunkByGrapheme(text, options) {
|
|
|
369
412
|
exports.BasePlatformAdapter = BasePlatformAdapter;
|
|
370
413
|
exports.DeliveryRouter = DeliveryRouter;
|
|
371
414
|
exports.GatewayConfigurationError = GatewayConfigurationError;
|
|
415
|
+
exports.GatewayLifecycleError = GatewayLifecycleError;
|
|
372
416
|
exports.GatewayRunner = GatewayRunner;
|
|
373
417
|
exports.HookExecutor = HookExecutor;
|
|
374
418
|
exports.SessionRouter = SessionRouter;
|