@theokit/gateway 0.11.0 → 0.12.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 CHANGED
@@ -1,5 +1,138 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.12.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 05e7fdd: Edit a message an adapter sent, so a reply can stream as a preview that the final text replaces.
8
+
9
+ `BasePlatformAdapter` gains `supportsEdit` (`false` by default) and
10
+ `editMessage(messageId, out)`, whose default refuses with `edit_unsupported`, makes no platform
11
+ call and never throws. A third-party subclass that already declares a member with either name and
12
+ a different type no longer compiles against this release, and under `noImplicitOverride` one
13
+ that declares it without `override` does not either.
14
+
15
+ Telegram (`editMessageText`), Discord (one REST `PATCH` of the message, without fetching the
16
+ channel), Slack (`chat.update`), Mattermost (`patchPost`), Matrix (an `m.replace` event) and Teams
17
+ (`updateActivity`, or `activities(conversationId).update` on `@microsoft/teams.api` below 2.0.14)
18
+ set `supportsEdit` to `true` and replace the text of a message they sent, honouring `format` as
19
+ `sendMessage` does (Slack's `chat.update` takes no `mrkdwn` argument, so its edit sends the text
20
+ as it is for every format), and return `{ ok: true, messageId }` with the same id. E-mail, SMS, LINE and
21
+ WhatsApp keep the default.
22
+
23
+ An edit is refused with no request as `edit_too_long` when the text would need more than one
24
+ platform message (Matrix has no length check), as `invalid_message_id` for an empty id (and on
25
+ Telegram one that is not a safe positive integer), and as `empty_text` and `not_connected` where
26
+ `sendMessage` answers those. Telegram answers its "message is not modified" refusal as a success.
27
+ On Discord an unknown channel is answered by the platform, as `discord_10003`. On Matrix a
28
+ `#alias` the adapter never resolved costs one lookup before the edit. Teams and Matrix do not
29
+ retry a refused markup as plain text on an edit, as they do on a send.
30
+
31
+ The six adapters keep `>=0.9.0` as their peer range on `@theokit/gateway` in this release. At run
32
+ time they work against any core in that range, since no adapter calls the base `editMessage`. Their
33
+ sources declare both members with `override`, so building them against a core older than this one
34
+ reports TS4113. The floor rises to this core in the next release, once it is on npm
35
+ (`docs/adr/0008-edit-capable-adapters-raise-their-core-floor-after-the-core-ships.md`). A
36
+ consumer's own typecheck reads the published declarations, which carry no `override`, and passes
37
+ on an older core.
38
+
39
+ - e646038: Make `google_chat` a first-party platform.
40
+
41
+ `@theokit/gateway` gains the `google_chat` key in `PlatformEventRegistry`, the
42
+ `GoogleChatMessageEvent` type, and a `channelRendering("google_chat")` row. `PlatformName` grows by
43
+ one member. Code that lists every platform in a `Record<PlatformName, …>` or in a switch with a
44
+ `never` default must add a `google_chat` entry, and a package that registered its own `google_chat`
45
+ key through module augmentation now collides with the first-party one (TS2717) and should drop it.
46
+
47
+ - e646038: Make `imessage` a first-party platform.
48
+
49
+ `@theokit/gateway` gains the `imessage` key in `PlatformEventRegistry`, the `IMessageMessageEvent`
50
+ type, and a `channelRendering("imessage")` row (`plain`, markers removed). `PlatformName` grows by
51
+ one member. Code that lists every platform in a `Record<PlatformName, …>` or in a switch with a
52
+ `never` default must add an `imessage` entry, and a package that registered its own `imessage` key
53
+ through module augmentation now collides with the first-party one (TS2717) and should drop it.
54
+
55
+ - e646038: Make `irc` a first-party platform.
56
+
57
+ `@theokit/gateway` gains the `irc` key in `PlatformEventRegistry`, the `IrcMessageEvent` type,
58
+ and a `channelRendering("irc")` row (`plain`, markers removed). `PlatformName` grows by one
59
+ member. Code that lists every platform in a `Record<PlatformName, …>` or in a switch with a
60
+ `never` default must add an `irc` entry, and a package that registered its own `irc` key through
61
+ module augmentation now collides with the first-party one (TS2717) and should drop it.
62
+
63
+ - e646038: Make `nextcloud_talk` a first-party platform.
64
+
65
+ `@theokit/gateway` gains the `nextcloud_talk` key in `PlatformEventRegistry`, the
66
+ `NextcloudTalkMessageEvent` type, and a `channelRendering("nextcloud_talk")` row (`markdown`,
67
+ passed through). `PlatformName` grows by one member. Code that lists every platform in a
68
+ `Record<PlatformName, …>` or in a switch with a `never` default must add a `nextcloud_talk`
69
+ entry, and a package that registered its own `nextcloud_talk` key through module augmentation now
70
+ collides with the first-party one (TS2717) and should drop it.
71
+
72
+ - e646038: Make `signal` a first-party platform.
73
+
74
+ `@theokit/gateway` gains the `signal` key in `PlatformEventRegistry`, the `SignalMessageEvent`
75
+ type, and a `channelRendering("signal")` row (`markdown`, text unchanged). `PlatformName` grows by
76
+ one member. Code that lists every platform in a `Record<PlatformName, …>` or in a switch with a
77
+ `never` default must add a `signal` entry, and a package that registered its own `signal` key
78
+ through module augmentation now collides with the first-party one (TS2717) and should drop it.
79
+
80
+ - b0b29d3: `rawBodyCapture(tag, { maxBytes })` refuses a body larger than `maxBytes` bytes before holding it.
81
+ A declared `content-length` over the limit is refused before any byte is kept; a streamed body is
82
+ refused once it passes the limit. Either way the rest of the stream is dropped, and when it ends
83
+ the middleware answers 413 with the JSON body `{ "error": "request body too large" }` and one
84
+ stderr line naming the router. `next` is not called, so no error reaches Express's final handler,
85
+ which would answer with an HTML page carrying the stack outside production. The middleware
86
+ answers once: data, the end of the stream or a stream error after a refusal do nothing. A
87
+ `maxBytes` that is not a finite number of zero or more throws a `RangeError` when the middleware is
88
+ built. Without the option the middleware keeps no limit, as before. `RawBodyCaptureOptions` is
89
+ exported.
90
+
91
+ ### Patch Changes
92
+
93
+ - d3f359a: `createChannels` builds one adapter per platform. In 0.11.0 it built every entry, so two entries
94
+ for one platform gave a `GatewayRunner` two adapters of that platform: the runner sent the first
95
+ one's replies through the second and never disconnected the first. A later entry for a platform
96
+ it already built is now rejected with a `GatewayConfigurationError` coded `duplicate_channel`, and
97
+ its `create` is not called. If your app lists two entries for one platform, the second one now
98
+ lands in `rejected` instead of being built. The first entry built for a platform wins, and an
99
+ entry rejected for its configuration does not claim its platform.
100
+
101
+ An entry whose `create` returns an adapter reporting another platform than its descriptor declares
102
+ is rejected with the code `platform_mismatch`, and the adapter it built is dropped unconnected.
103
+ The runner keys adapters by the adapter's own platform, so such an adapter would otherwise reach
104
+ it as a second adapter for a platform the duplicate check never saw.
105
+
106
+ - 7bea3d4: Two overlapping `start()` calls on one `GatewayRunner` now share one connect. A call made while
107
+ the first is still connecting no longer connects every adapter again; both calls resolve the same
108
+ `StartResult`, or reject with the same error. A start that rejects is not remembered, so a later
109
+ `start()` connects again.
110
+
111
+ A `stop()` during an in-flight `start()` no longer leaves an adapter connected on a stopped runner.
112
+ The start disconnects what connected, wires no inbound dispatch, and resolves
113
+ `{ connected: [], failed }` instead of naming the platforms it connected. Under `"rollback"`, a
114
+ connect that fails still rejects it.
115
+
116
+ Under the default `connectFailure: "rollback"`, the rollback waits for every connect to settle, so
117
+ an adapter that connects after another refused is disconnected as well. The rejection therefore
118
+ comes only once the slowest connect settles. With one adapter refusing and another whose connect
119
+ hangs, `start()` used to reject at once and now stays pending, as a successful rollback start and
120
+ an `"isolate"` start already did.
121
+
122
+ When `stop()`, a rollback, or a start that `stop()` overtook disconnects an adapter and that
123
+ `disconnect()` fails, the runner now writes one line to stderr naming the platform, with any
124
+ credential in the error redacted. The failure used to be discarded, so an adapter that might still
125
+ hold its platform session left no trace. How `start()` and `stop()` resolve or reject is unchanged.
126
+
127
+ - 9a8b81b: `listenerLifecycle(...).start()` rejects with the bind error when the port is taken, instead of
128
+ resolving over no listener. Under Express 5 the error reached the `listen` callback, which ignored
129
+ it, so a second server on a port another one held reported itself started and answered nothing;
130
+ under Express 4 the error was emitted on the server with no listener attached. The
131
+ `createWebhookServer` of `@theokit/gateway-line` and `@theokit/gateway-sms` returns this lifecycle,
132
+ so their `start()` now rejects with `EADDRINUSE` in that case, and a later `start()` tries again.
133
+ `ListenableApp.listen` declares the error argument Express 5 passes, and `ListenerLike` the
134
+ optional `once("error")` Express 4's server has.
135
+
3
136
  ## 0.11.0
4
137
 
5
138
  ### Minor Changes
package/README.md CHANGED
@@ -93,6 +93,61 @@ presenter per turn; it keeps state between `present()` calls.
93
93
  - `@theokit/presenter` is your dependency, not this package's: `@theokit/gateway` does not depend
94
94
  on it.
95
95
 
96
+ ## Editing a sent message
97
+
98
+ Six adapters can replace the text of a message they sent, keeping its id: Telegram, Discord,
99
+ Slack, Mattermost, Matrix and Teams. E-mail, SMS, LINE and WhatsApp cannot, because their
100
+ platforms have no edit call. A caller that wants a reply to appear as a preview and then become
101
+ the final text reads `supportsEdit` before it starts, and falls back to `sendMessage` whenever an
102
+ edit is refused. `BasePlatformAdapter`, `OutboundMessage` and `SendResult` come from
103
+ `@theokit/gateway`.
104
+
105
+ ```typescript
106
+ async function sendWithPreview(
107
+ adapter: BasePlatformAdapter,
108
+ out: OutboundMessage,
109
+ preview: string,
110
+ ): Promise<SendResult> {
111
+ // No edit call on this platform: send the final text once.
112
+ if (!adapter.supportsEdit) return adapter.sendMessage(out);
113
+ const sent = await adapter.sendMessage({ ...out, text: preview });
114
+ if (!sent.ok || sent.messageId === undefined) return adapter.sendMessage(out);
115
+ // The preview must fit one message; edit_too_long and every other refusal fall back to a send.
116
+ const edited = await adapter.editMessage(sent.messageId, out);
117
+ return edited.ok ? edited : adapter.sendMessage(out);
118
+ }
119
+ ```
120
+
121
+ `supportsEdit` is set at construction and does not change with `connect()`. `editMessage` never
122
+ throws on a platform error; it answers with a `SendResult`, and these refusals make no edit
123
+ request:
124
+
125
+ | Code | When |
126
+ |---|---|
127
+ | `edit_unsupported` | the adapter cannot edit (the four above), or a Matrix client injected without `sendMessage` |
128
+ | `edit_too_long` | the text would need more than one platform message, counted after a `plain` text is escaped as a send escapes it; an edit replaces one message and is never split. Matrix has no length check |
129
+ | `invalid_message_id` | the id is empty, or on Telegram not a positive integer |
130
+ | `empty_text` | the text is empty, or on Teams only whitespace |
131
+ | `not_connected` | the adapter is not connected, where its `sendMessage` checks that too (all but Telegram and Discord) |
132
+ | `invalid_channel` | Telegram only: the channel id is not numeric, as on a send |
133
+ | `encrypted_room_unsupported` | Matrix only: the room is encrypted, as on a send |
134
+
135
+ Any other refusal comes from the platform, mapped as `sendMessage` maps it. Keep the preview
136
+ within one message, and edit only a message this adapter sent: on Matrix an edit is an
137
+ `m.replace` event, and clients apply it only to an event from the same sender. An edit whose
138
+ markup the platform refuses is not retried as plain text. When an edit is refused, the sample
139
+ sends the final text as a new message, so the preview stays above it.
140
+
141
+ `supportsEdit` says that the adapter has an edit call, not that every edit is accepted. Treat
142
+ `edit_unsupported` from an adapter that reports `true` as "stop previewing", like any other
143
+ refusal. Where an adapter checks the connection, `not_connected` is answered before
144
+ `invalid_message_id`.
145
+
146
+ The adapters do not order edits. Two edits of the same message that are in flight at once can
147
+ reach the platform in either order, and the one that lands last stays on screen; on Matrix each
148
+ edit is a separate event and clients show the newest. Await each edit before sending the next,
149
+ or keep one in flight and send only the latest text when it settles.
150
+
96
151
  ## Architecture (5 pieces)
97
152
 
98
153
  | Module | Responsibility |
@@ -178,9 +233,14 @@ for (const { platform, reason } of failed) console.error(`${platform} did not co
178
233
  - `start()` resolves a `StartResult` (`{ connected, failed }`) under both values. Code that awaits
179
234
  it and ignores the value is unaffected; a type or subclass that declares
180
235
  `start(): Promise<void>` needs to change.
181
- - Give a runner one channel per platform. It routes replies and `stop()` by platform, so with two
182
- channels of one platform the later one sends the earlier one's replies, and the earlier one is
183
- connected but never disconnected.
236
+ - A runner holds one channel per platform: it routes replies and `stop()` by platform.
237
+ `createChannels` enforces this. The first entry built for a platform wins, and a later entry for
238
+ it is rejected with a `GatewayConfigurationError` coded `duplicate_channel` and never built. An
239
+ entry whose `create` returns an adapter reporting another platform than its descriptor is
240
+ rejected with the code `platform_mismatch`, and that adapter is dropped unconnected. A
241
+ runner you build from adapters you constructed yourself is not checked, so give it one adapter
242
+ per platform: with two of one platform the later one sends the earlier one's replies, and the
243
+ earlier one is connected but never disconnected.
184
244
  - Under `"isolate"`, and under `"rollback"` until the first failure, `start()` waits for every
185
245
  connect, so a connect that never settles blocks it.
186
246
  - A webhook channel's request reaches your HTTP route; route it by platform to the descriptor's
package/dist/index.cjs CHANGED
@@ -28,6 +28,35 @@ var BasePlatformAdapter = class {
28
28
  }
29
29
  return "ok";
30
30
  }
31
+ /**
32
+ * Whether {@link editMessage} can replace the text of a message this adapter sent.
33
+ *
34
+ * Read it before starting a preview: on `false`, send the final text instead. An adapter sets
35
+ * it at construction and MUST NOT change it with `connect()`. Annotated as `boolean` so that an
36
+ * edit-capable adapter can override it with `true`.
37
+ */
38
+ supportsEdit = false;
39
+ /**
40
+ * Replace the text of a message this adapter sent, keeping its id.
41
+ *
42
+ * Returns `{ ok: true, messageId }` on success and a `SendResult` error otherwise; it never
43
+ * throws on platform errors. An edit-capable adapter applies, with no request, the same local
44
+ * checks its `sendMessage` applies (such as `empty_text`, and `not_connected` where the send
45
+ * checks the connection), plus `invalid_message_id`, and `edit_too_long` where the adapter
46
+ * splits text: an edit that would need more than one platform message is refused, never split.
47
+ *
48
+ * Default: refuses with `edit_unsupported`, makes no platform call, and checks nothing else
49
+ * first, so capability is answered before input.
50
+ */
51
+ async editMessage(_messageId, _out) {
52
+ return {
53
+ ok: false,
54
+ error: {
55
+ code: "edit_unsupported",
56
+ message: `${this.platform} adapter cannot edit a sent message`
57
+ }
58
+ };
59
+ }
31
60
  /** Lifecycle: emit a typing indicator. Default: noop. */
32
61
  async startTyping(_channelId) {
33
62
  }
@@ -59,29 +88,63 @@ function isAbsent(value) {
59
88
  function missingRequiredKeys(entry, values) {
60
89
  return entry.descriptor.config.filter((field) => field.required && isAbsent(values[field.key])).map((field) => field.key);
61
90
  }
91
+ function refused(platform, code, reason) {
92
+ return {
93
+ refusal: {
94
+ platform,
95
+ error: new GatewayConfigurationError("gateway", {
96
+ code,
97
+ message: `channel ${platform}: ${reason}`
98
+ })
99
+ }
100
+ };
101
+ }
102
+ function refuseBeforeCreate(entry, values, builtPlatforms) {
103
+ const platform = entry.descriptor.platform;
104
+ if (builtPlatforms.has(platform)) {
105
+ return refused(platform, "duplicate_channel", "a channel for this platform was already built");
106
+ }
107
+ const missing = missingRequiredKeys(entry, values);
108
+ if (missing.length > 0) {
109
+ return refused(
110
+ platform,
111
+ "missing_required_config",
112
+ `missing required config ${missing.join(", ")}`
113
+ );
114
+ }
115
+ return void 0;
116
+ }
117
+ function createAdapter(entry, values) {
118
+ const platform = entry.descriptor.platform;
119
+ let adapter;
120
+ try {
121
+ adapter = entry.descriptor.create(values);
122
+ } catch (err) {
123
+ if (!(err instanceof GatewayConfigurationError)) throw err;
124
+ return { refusal: { platform, error: err } };
125
+ }
126
+ if (adapter.platform !== platform) {
127
+ return refused(
128
+ platform,
129
+ "platform_mismatch",
130
+ `create returned an adapter reporting platform ${adapter.platform}`
131
+ );
132
+ }
133
+ return { adapter };
134
+ }
62
135
  function createChannels(entries) {
63
136
  const adapters = [];
64
137
  const rejected = [];
138
+ const builtPlatforms = /* @__PURE__ */ new Set();
65
139
  for (const entry of entries) {
66
140
  const values = entry.config ?? {};
67
- const platform = entry.descriptor.platform;
68
- const missing = missingRequiredKeys(entry, values);
69
- if (missing.length > 0) {
70
- rejected.push({
71
- platform,
72
- error: new GatewayConfigurationError("gateway", {
73
- code: "missing_required_config",
74
- message: `channel ${platform}: missing required config ${missing.join(", ")}`
75
- })
76
- });
141
+ const outcome = refuseBeforeCreate(entry, values, builtPlatforms) ?? createAdapter(entry, values);
142
+ if (outcome.refusal !== void 0) {
143
+ rejected.push(outcome.refusal);
77
144
  continue;
78
145
  }
79
- try {
80
- adapters.push(entry.descriptor.create(values));
81
- } catch (err) {
82
- if (!(err instanceof GatewayConfigurationError)) throw err;
83
- rejected.push({ platform, error: err });
84
- }
146
+ adapters.push(outcome.adapter);
147
+ builtPlatforms.add(entry.descriptor.platform);
85
148
  }
86
149
  return { adapters, rejected };
87
150
  }
@@ -173,6 +236,18 @@ var CREDENTIAL_SHAPES = {
173
236
  field: "gateway-whatsapp `appSecret`",
174
237
  why: "32 lowercase hex, the same shape as the Twilio auth token above and as every md5 and dashless UUID. Masking it would eat the correlation ids in a log."
175
238
  },
239
+ {
240
+ field: "gateway-nextcloud-talk `secret`",
241
+ why: "a Talk bot secret is a string of 40 to 128 characters the administrator chose for `occ talk:bot:install`, with no prefix or format to recognise. It never travels: both sides send only an HMAC made with it, and the adapter never logs it."
242
+ },
243
+ {
244
+ field: "gateway-irc `password` and `saslPassword`",
245
+ why: "a server password and a NickServ password are passphrases the operator chose, with no format to recognise. The SDK's `key=value` rule masks them as fields wherever they appear as `password=...`; the SASL payload on the wire is their base64, which the adapter never logs."
246
+ },
247
+ {
248
+ field: "gateway-google-chat `privateKey`",
249
+ why: "a PEM block spans lines, and in a log it usually arrives inside a JSON string with its line breaks escaped as \\n, which no single-line shape can claim whole. The SDK's `key=value` rule masks it as a field wherever it appears as `private_key=...` or `privateKey=...`."
250
+ },
176
251
  {
177
252
  field: "gateway-line `channelAccessToken`, gateway-sms `authToken` (Plivo)",
178
253
  why: "long base64 runs with no prefix, indistinguishable from any encoded blob a platform library puts in an error message."
@@ -293,6 +368,21 @@ function connectFailureReason(outcome) {
293
368
  const message = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
294
369
  return redactSecrets(message);
295
370
  }
371
+ async function releaseAdapters(adapters, during) {
372
+ await Promise.all(
373
+ adapters.map(async (a) => {
374
+ try {
375
+ await a.disconnect();
376
+ } catch (err) {
377
+ const message = err instanceof Error ? err.message : String(err);
378
+ process.stderr.write(
379
+ `[gateway] adapter "${a.platform}" disconnect failed while ${during}: ${redactSecrets(message)}
380
+ `
381
+ );
382
+ }
383
+ })
384
+ );
385
+ }
296
386
  var GatewayRunner = class {
297
387
  constructor(opts) {
298
388
  this.opts = opts;
@@ -307,6 +397,8 @@ var GatewayRunner = class {
307
397
  /** Slash command registry: name → handler (word-boundary match, EC-A). */
308
398
  commands = /* @__PURE__ */ new Map();
309
399
  startResult;
400
+ /** The start that has not settled yet, shared by every overlapping `start()` call. */
401
+ startInFlight;
310
402
  stopped = false;
311
403
  /**
312
404
  * Register a slash command. Match rule (EC-A): text === "/" + name
@@ -323,10 +415,24 @@ var GatewayRunner = class {
323
415
  * Resolves with what connected. A second call after the first resolved returns the same result
324
416
  * without connecting again.
325
417
  *
418
+ * Overlapping calls share one start; a start overtaken by stop resolves with no adapter connected.
419
+ * A call made before `stop()` while another is still connecting connects nothing and settles
420
+ * with it; a call made after `stop()` throws `runner_stopped`. When `stop()` runs before the
421
+ * connect settles, the adapters that connected are disconnected, no inbound dispatch is wired,
422
+ * and the start resolves `{ connected: [], failed }`, keeping the `"isolate"` failures. Under
423
+ * `"rollback"`, a connect that fails still rejects the start.
424
+ *
425
+ * Under `connectFailure: "rollback"`, every connect settles before the rollback, so a failing
426
+ * start rejects only once its slowest connect settles, as a successful one resolves only then.
427
+ *
428
+ * An adapter whose `disconnect()` fails while a start rolls back, or while a start that `stop()`
429
+ * overtook gives its adapters back, is named on stderr with the error redacted; how the start
430
+ * settles does not change.
431
+ *
326
432
  * @throws {GatewayLifecycleError} `runner_stopped` — the runner was already
327
433
  * stopped. A stopped runner is spent; construct a new one.
328
- * @throws {Error} under the default `connectFailure: "rollback"`, the first connect failure, after the
329
- * adapters that did connect were disconnected.
434
+ * @throws {Error} under the default `connectFailure: "rollback"`, the first connect failure, after
435
+ * every connect settled and the adapters that did connect were disconnected.
330
436
  */
331
437
  async start() {
332
438
  if (this.stopped) {
@@ -336,7 +442,22 @@ var GatewayRunner = class {
336
442
  });
337
443
  }
338
444
  if (this.startResult !== void 0) return this.startResult;
445
+ if (this.startInFlight === void 0) {
446
+ const pending = this.runStart();
447
+ this.startInFlight = pending;
448
+ pending.catch(() => {
449
+ if (this.startInFlight === pending) this.startInFlight = void 0;
450
+ });
451
+ }
452
+ return this.startInFlight;
453
+ }
454
+ async runStart() {
339
455
  const result = (this.opts.connectFailure ?? "rollback") === "isolate" ? await this.connectIsolated() : await this.connectAllOrRollback();
456
+ if (this.stopped) {
457
+ await releaseAdapters(result.connected, "releasing a start that stop() overtook");
458
+ this.startResult = { connected: [], failed: result.failed };
459
+ return this.startResult;
460
+ }
340
461
  this.wireInbound(result.connected);
341
462
  this.startResult = {
342
463
  connected: result.connected.map((a) => a.platform),
@@ -344,22 +465,36 @@ var GatewayRunner = class {
344
465
  };
345
466
  return this.startResult;
346
467
  }
347
- /** All or nothing: one failure disconnects the adapters already open, then rethrows. */
468
+ /**
469
+ * All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow
470
+ * the first failure. Every connect settles before the rollback: rolling back while one is still
471
+ * pending left that adapter live once it connected.
472
+ */
348
473
  async connectAllOrRollback() {
349
- const connected = [];
350
- try {
351
- await Promise.all(
352
- this.opts.adapters.map(async (a) => {
353
- const ok = await a.connect();
354
- if (ok) connected.push(a);
355
- else throw new Error(`adapter "${a.platform}" connect returned false`);
356
- })
357
- );
358
- } catch (err) {
359
- await Promise.all(connected.map((a) => a.disconnect().catch(() => void 0)));
360
- throw err;
474
+ const adapters = this.opts.adapters;
475
+ const failures = [];
476
+ const settled = await Promise.allSettled(
477
+ adapters.map(async (a) => {
478
+ let ok;
479
+ try {
480
+ ok = await a.connect();
481
+ } catch (err) {
482
+ failures.push(err);
483
+ throw err;
484
+ }
485
+ if (!ok) {
486
+ const refusal = new Error(`adapter "${a.platform}" connect returned false`);
487
+ failures.push(refusal);
488
+ throw refusal;
489
+ }
490
+ })
491
+ );
492
+ if (failures.length > 0) {
493
+ const connected = adapters.filter((_, i) => settled[i]?.status === "fulfilled");
494
+ await releaseAdapters(connected, "rolling back a failed start");
495
+ throw failures[0];
361
496
  }
362
- return { connected: [...this.opts.adapters], failed: [] };
497
+ return { connected: [...adapters], failed: [] };
363
498
  }
364
499
  /**
365
500
  * Connect every adapter and keep the ones that connected. The `async` wrapper turns a
@@ -390,7 +525,12 @@ var GatewayRunner = class {
390
525
  }
391
526
  /**
392
527
  * Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,
393
- * then disconnects adapters. Idempotent (EC-E).
528
+ * then disconnects adapters. Idempotent (EC-E). A disconnect that fails does not make `stop()`
529
+ * reject and does not stop the other disconnects; it is written to stderr, redacted, naming the
530
+ * platform.
531
+ *
532
+ * An adapter still connecting under an in-flight start is released when that start settles;
533
+ * `stop()` does not wait for it.
394
534
  */
395
535
  async stop() {
396
536
  if (this.stopped) return;
@@ -416,9 +556,7 @@ var GatewayRunner = class {
416
556
  if (timer !== void 0) clearTimeout(timer);
417
557
  }
418
558
  }
419
- await Promise.all(
420
- [...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => void 0))
421
- );
559
+ await releaseAdapters([...this.adaptersByPlatform.values()], "stopping the runner");
422
560
  }
423
561
  /**
424
562
  * @internal Test seam, following `EmailAdapter._threadStoreSize`. The drain set must SHRINK: a
@@ -590,11 +728,16 @@ var RENDERINGS = {
590
728
  discord: { format: "markdown", translate: identity },
591
729
  mattermost: { format: "markdown", translate: identity },
592
730
  teams: { format: "markdown", translate: identity },
731
+ signal: { format: "markdown", translate: identity },
593
732
  line: { format: "plain", translate: translateWith(DIALECTS.line) },
594
733
  sms: { format: "plain", translate: translateWith(DIALECTS.sms) },
595
734
  telegram: { format: "plain", translate: translateWith(STRIP) },
596
735
  matrix: { format: "plain", translate: translateWith(STRIP) },
597
- email: { format: "plain", translate: translateWith(STRIP) }
736
+ email: { format: "plain", translate: translateWith(STRIP) },
737
+ imessage: { format: "plain", translate: translateWith(STRIP) },
738
+ google_chat: { format: "plain", translate: translateWith(STRIP) },
739
+ irc: { format: "plain", translate: translateWith(STRIP) },
740
+ nextcloud_talk: { format: "markdown", translate: identity }
598
741
  };
599
742
  function channelRendering(platform) {
600
743
  const rendering = Object.hasOwn(RENDERINGS, platform) ? RENDERINGS[platform] : void 0;
@@ -691,8 +834,14 @@ async function loadPeer(load, onMissing) {
691
834
  onMissing();
692
835
  }
693
836
  }
694
- function rawBodyCapture(tag) {
695
- return (rawReq, _res, next) => {
837
+ function rawBodyCapture(tag, options = {}) {
838
+ const { maxBytes } = options;
839
+ if (maxBytes !== void 0 && !(Number.isFinite(maxBytes) && maxBytes >= 0)) {
840
+ throw new RangeError(
841
+ `[${tag}] rawBodyCapture: maxBytes must be a finite number of zero or more, got ${maxBytes}`
842
+ );
843
+ }
844
+ return (rawReq, rawRes, next) => {
696
845
  const req = rawReq;
697
846
  if (req.readableEnded === true || req.complete === true) {
698
847
  process.stderr.write(
@@ -704,17 +853,48 @@ function rawBodyCapture(tag) {
704
853
  return;
705
854
  }
706
855
  let buf = "";
856
+ let bytes = 0;
857
+ let refused2 = maxBytes !== void 0 && declaredLength(req) > maxBytes;
858
+ let settled = false;
707
859
  req.setEncoding("utf8");
708
860
  req.on("data", (chunk) => {
861
+ if (refused2 || settled) return;
862
+ bytes += Buffer.byteLength(chunk);
863
+ if (maxBytes !== void 0 && bytes > maxBytes) {
864
+ refused2 = true;
865
+ buf = "";
866
+ return;
867
+ }
709
868
  buf += chunk;
710
869
  });
711
870
  req.on("end", () => {
871
+ if (settled) return;
872
+ settled = true;
873
+ if (refused2) {
874
+ answerTooLarge(rawRes, tag, maxBytes ?? 0);
875
+ return;
876
+ }
712
877
  req.rawBody = buf;
713
878
  next();
714
879
  });
715
- req.on("error", (err) => next(err));
880
+ req.on("error", (err) => {
881
+ if (settled) return;
882
+ settled = true;
883
+ if (refused2) return;
884
+ next(err);
885
+ });
716
886
  };
717
887
  }
888
+ function declaredLength(req) {
889
+ const value = req.headers?.["content-length"];
890
+ const declared = Number(Array.isArray(value) ? value[0] : value);
891
+ return Number.isFinite(declared) ? declared : 0;
892
+ }
893
+ function answerTooLarge(res, tag, maxBytes) {
894
+ process.stderr.write(`[${tag}] refused a request (413): body larger than ${maxBytes} bytes
895
+ `);
896
+ res.status(413).json({ error: "request body too large" });
897
+ }
718
898
  function listenerLifecycle(opts) {
719
899
  let started = false;
720
900
  let stopped = false;
@@ -726,8 +906,17 @@ function listenerLifecycle(opts) {
726
906
  return;
727
907
  }
728
908
  stopped = false;
729
- await new Promise((resolve) => {
730
- listener = opts.app.listen(opts.port, () => resolve());
909
+ await new Promise((resolve, reject) => {
910
+ const settle = (err) => {
911
+ if (err === void 0) resolve();
912
+ else reject(err);
913
+ };
914
+ const current = opts.app.listen(opts.port, settle);
915
+ listener = current;
916
+ current.once?.("error", settle);
917
+ }).catch((err) => {
918
+ listener = void 0;
919
+ throw err;
731
920
  });
732
921
  started = true;
733
922
  },