@theokit/gateway 0.11.0 → 0.14.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 +290 -0
- package/README.md +167 -18
- package/dist/index.cjs +666 -70
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +498 -19
- package/dist/index.d.ts +498 -19
- package/dist/index.js +664 -71
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -28,6 +28,43 @@ 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
|
+
* Whether {@link sendMessage} can send the images of `out.attachments` (B-674).
|
|
41
|
+
*
|
|
42
|
+
* Read it before attaching: on `false`, the adapter refuses a non-empty list with
|
|
43
|
+
* `attachments_unsupported`. Set at construction, never changed by `connect()`. Annotated as
|
|
44
|
+
* `boolean` so that an adapter that sends images can override it with `true`.
|
|
45
|
+
*/
|
|
46
|
+
supportsAttachments = false;
|
|
47
|
+
/**
|
|
48
|
+
* Replace the text of a message this adapter sent, keeping its id.
|
|
49
|
+
*
|
|
50
|
+
* Returns `{ ok: true, messageId }` on success and a `SendResult` error otherwise; it never
|
|
51
|
+
* throws on platform errors. An edit-capable adapter applies, with no request, the same local
|
|
52
|
+
* checks its `sendMessage` applies (such as `empty_text`, and `not_connected` where the send
|
|
53
|
+
* checks the connection), plus `invalid_message_id`, and `edit_too_long` where the adapter
|
|
54
|
+
* splits text: an edit that would need more than one platform message is refused, never split.
|
|
55
|
+
*
|
|
56
|
+
* Default: refuses with `edit_unsupported`, makes no platform call, and checks nothing else
|
|
57
|
+
* first, so capability is answered before input.
|
|
58
|
+
*/
|
|
59
|
+
async editMessage(_messageId, _out) {
|
|
60
|
+
return {
|
|
61
|
+
ok: false,
|
|
62
|
+
error: {
|
|
63
|
+
code: "edit_unsupported",
|
|
64
|
+
message: `${this.platform} adapter cannot edit a sent message`
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
}
|
|
31
68
|
/** Lifecycle: emit a typing indicator. Default: noop. */
|
|
32
69
|
async startTyping(_channelId) {
|
|
33
70
|
}
|
|
@@ -59,31 +96,85 @@ function isAbsent(value) {
|
|
|
59
96
|
function missingRequiredKeys(entry, values) {
|
|
60
97
|
return entry.descriptor.config.filter((field) => field.required && isAbsent(values[field.key])).map((field) => field.key);
|
|
61
98
|
}
|
|
99
|
+
function refused(platform, code, reason) {
|
|
100
|
+
return {
|
|
101
|
+
refusal: {
|
|
102
|
+
platform,
|
|
103
|
+
error: new GatewayConfigurationError("gateway", {
|
|
104
|
+
code,
|
|
105
|
+
message: `channel ${platform}: ${reason}`
|
|
106
|
+
})
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
function refuseBeforeCreate(entry, values, builtPlatforms) {
|
|
111
|
+
const platform = entry.descriptor.platform;
|
|
112
|
+
if (builtPlatforms.has(platform)) {
|
|
113
|
+
return refused(platform, "duplicate_channel", "a channel for this platform was already built");
|
|
114
|
+
}
|
|
115
|
+
const missing = missingRequiredKeys(entry, values);
|
|
116
|
+
if (missing.length > 0) {
|
|
117
|
+
return refused(
|
|
118
|
+
platform,
|
|
119
|
+
"missing_required_config",
|
|
120
|
+
`missing required config ${missing.join(", ")}`
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
return void 0;
|
|
124
|
+
}
|
|
125
|
+
function createAdapter(entry, values) {
|
|
126
|
+
const platform = entry.descriptor.platform;
|
|
127
|
+
let adapter;
|
|
128
|
+
try {
|
|
129
|
+
adapter = entry.descriptor.create(values);
|
|
130
|
+
} catch (err) {
|
|
131
|
+
if (!(err instanceof GatewayConfigurationError)) throw err;
|
|
132
|
+
return { refusal: { platform, error: err } };
|
|
133
|
+
}
|
|
134
|
+
if (adapter.platform !== platform) {
|
|
135
|
+
return refused(
|
|
136
|
+
platform,
|
|
137
|
+
"platform_mismatch",
|
|
138
|
+
`create returned an adapter reporting platform ${adapter.platform}`
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
return { adapter };
|
|
142
|
+
}
|
|
62
143
|
function createChannels(entries) {
|
|
63
144
|
const adapters = [];
|
|
145
|
+
const channels = [];
|
|
64
146
|
const rejected = [];
|
|
147
|
+
const builtPlatforms = /* @__PURE__ */ new Set();
|
|
65
148
|
for (const entry of entries) {
|
|
66
149
|
const values = entry.config ?? {};
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
|
|
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
|
-
});
|
|
150
|
+
const outcome = refuseBeforeCreate(entry, values, builtPlatforms) ?? createAdapter(entry, values);
|
|
151
|
+
if (outcome.refusal !== void 0) {
|
|
152
|
+
rejected.push(outcome.refusal);
|
|
77
153
|
continue;
|
|
78
154
|
}
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
155
|
+
adapters.push(outcome.adapter);
|
|
156
|
+
channels.push({ descriptor: entry.descriptor, adapter: outcome.adapter });
|
|
157
|
+
builtPlatforms.add(entry.descriptor.platform);
|
|
158
|
+
}
|
|
159
|
+
return { adapters, channels, rejected };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// src/delivery/attachments.ts
|
|
163
|
+
function attachmentsOf(attachments) {
|
|
164
|
+
return attachments != null && attachments.length !== 0 ? { attachments } : {};
|
|
165
|
+
}
|
|
166
|
+
function refuseUnsupportedAttachments(adapter, outbound) {
|
|
167
|
+
const { attachments } = outbound;
|
|
168
|
+
if (adapter.supportsAttachments || attachments == null || attachments.length === 0) {
|
|
169
|
+
return void 0;
|
|
85
170
|
}
|
|
86
|
-
return {
|
|
171
|
+
return {
|
|
172
|
+
ok: false,
|
|
173
|
+
error: {
|
|
174
|
+
code: "attachments_unsupported",
|
|
175
|
+
message: `${adapter.platform} adapter cannot send attachments`
|
|
176
|
+
}
|
|
177
|
+
};
|
|
87
178
|
}
|
|
88
179
|
|
|
89
180
|
// src/delivery/router.ts
|
|
@@ -100,12 +191,14 @@ var DeliveryRouter = class {
|
|
|
100
191
|
error: { code: "no_adapter", message: `no adapter for platform "${req.platform}"` }
|
|
101
192
|
};
|
|
102
193
|
}
|
|
103
|
-
|
|
194
|
+
const outbound = {
|
|
104
195
|
channel: req.channel,
|
|
105
196
|
text: req.text,
|
|
106
197
|
...req.format !== void 0 ? { format: req.format } : {},
|
|
107
|
-
...req.replyTo !== void 0 ? { replyTo: req.replyTo } : {}
|
|
108
|
-
|
|
198
|
+
...req.replyTo !== void 0 ? { replyTo: req.replyTo } : {},
|
|
199
|
+
...attachmentsOf(req.attachments)
|
|
200
|
+
};
|
|
201
|
+
return refuseUnsupportedAttachments(adapter, outbound) ?? adapter.sendMessage(outbound);
|
|
109
202
|
}
|
|
110
203
|
};
|
|
111
204
|
|
|
@@ -150,9 +243,46 @@ var CREDENTIAL_SHAPES = {
|
|
|
150
243
|
field: "gateway-teams `clientSecret`",
|
|
151
244
|
pattern: /(?<![A-Za-z0-9~])[A-Za-z0-9]{3}\d[A-Za-z0-9]?~[A-Za-z0-9._~-]{30,}(?![A-Za-z0-9._~-])/g,
|
|
152
245
|
alsoMatches: "an Entra-style secret is the only common value with a tilde in that position"
|
|
246
|
+
},
|
|
247
|
+
{
|
|
248
|
+
field: "gateway-nostr `secretKey` (nsec1 form)",
|
|
249
|
+
pattern: /(?<![a-z0-9])nsec1[02-9ac-hj-np-z]{58}(?![a-z0-9])/g,
|
|
250
|
+
alsoMatches: "nothing plausible \u2014 `nsec1` is NIP-19's prefix for a secret key"
|
|
153
251
|
}
|
|
154
252
|
],
|
|
155
253
|
uncovered: [
|
|
254
|
+
{
|
|
255
|
+
field: "gateway-buzz `token`",
|
|
256
|
+
why: "a Buzz bot token with no fixed shape this package could confirm. It travels only in Authorization headers, which the adapter never logs."
|
|
257
|
+
},
|
|
258
|
+
{
|
|
259
|
+
field: "gateway-clickclack `token`",
|
|
260
|
+
why: "a ClickClack bot token (`ccb_` prefix) or session token with no fixed shape for the latter. It travels only in Authorization headers, which the adapter never logs."
|
|
261
|
+
},
|
|
262
|
+
{
|
|
263
|
+
field: "gateway-zalo-personal `credentials`",
|
|
264
|
+
why: "a Zalo web session: a cookie jar, an IMEI-like device id and a user agent. The cookie has no prefix or fixed shape to recognise. It travels only to the Zalo library, which the adapter never logs."
|
|
265
|
+
},
|
|
266
|
+
{
|
|
267
|
+
field: "gateway-twitch `accessToken`",
|
|
268
|
+
why: "30 lowercase alphanumerics with no prefix, the shape of many ids and hashes in a log. It travels only in Authorization headers, which the adapter never logs."
|
|
269
|
+
},
|
|
270
|
+
{
|
|
271
|
+
field: "gateway-tlon-urbit `code`",
|
|
272
|
+
why: "a +code is four dash-joined phonemic syllable words, the same shape as an Urbit ship name such as ~sampel-palnet-sampel-palnet, which the logs exist to show. It travels only in the /~/login body, which the adapter never logs."
|
|
273
|
+
},
|
|
274
|
+
{
|
|
275
|
+
field: "gateway-synology-chat `botToken` and `incomingUrl`",
|
|
276
|
+
why: "a bot token is a random string the NAS generates with no prefix, and the Incoming URL carries its own token as a query parameter of an ordinary entry.cgi URL. Neither has a shape to claim without eating ordinary ids and URLs; the adapter never logs the URL, and refuses a callback token before reading it."
|
|
277
|
+
},
|
|
278
|
+
{
|
|
279
|
+
field: "gateway-feishu-lark `appSecret`",
|
|
280
|
+
why: "32 alphanumerics with no prefix, the shape of many tokens and hashes; it travels only in the body of the tenant-token request, which the adapter never logs."
|
|
281
|
+
},
|
|
282
|
+
{
|
|
283
|
+
field: "gateway-nostr `secretKey` (64-hex form)",
|
|
284
|
+
why: "64 hex characters is also every Nostr public key and event id, which the logs exist to show, and a sha256 digest. The nsec1 spelling of the same key is masked above."
|
|
285
|
+
},
|
|
156
286
|
{
|
|
157
287
|
field: "gateway-sms `authToken` (Twilio), gateway-line `channelSecret`",
|
|
158
288
|
why: "32 lowercase hex characters, which is also an md5 digest, a dashless UUID and half a git tree hash. Masking it would eat the correlation id a developer reads the log to find."
|
|
@@ -173,6 +303,18 @@ var CREDENTIAL_SHAPES = {
|
|
|
173
303
|
field: "gateway-whatsapp `appSecret`",
|
|
174
304
|
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
305
|
},
|
|
306
|
+
{
|
|
307
|
+
field: "gateway-nextcloud-talk `secret`",
|
|
308
|
+
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."
|
|
309
|
+
},
|
|
310
|
+
{
|
|
311
|
+
field: "gateway-irc `password` and `saslPassword`",
|
|
312
|
+
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."
|
|
313
|
+
},
|
|
314
|
+
{
|
|
315
|
+
field: "gateway-google-chat `privateKey`",
|
|
316
|
+
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=...`."
|
|
317
|
+
},
|
|
176
318
|
{
|
|
177
319
|
field: "gateway-line `channelAccessToken`, gateway-sms `authToken` (Plivo)",
|
|
178
320
|
why: "long base64 runs with no prefix, indistinguishable from any encoded blob a platform library puts in an error message."
|
|
@@ -293,20 +435,35 @@ function connectFailureReason(outcome) {
|
|
|
293
435
|
const message = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
|
|
294
436
|
return redactSecrets(message);
|
|
295
437
|
}
|
|
438
|
+
async function releaseAdapters(adapters, during) {
|
|
439
|
+
await Promise.all(
|
|
440
|
+
adapters.map(async (a) => {
|
|
441
|
+
try {
|
|
442
|
+
await a.disconnect();
|
|
443
|
+
} catch (err) {
|
|
444
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
445
|
+
process.stderr.write(
|
|
446
|
+
`[gateway] adapter "${a.platform}" disconnect failed while ${during}: ${redactSecrets(message)}
|
|
447
|
+
`
|
|
448
|
+
);
|
|
449
|
+
}
|
|
450
|
+
})
|
|
451
|
+
);
|
|
452
|
+
}
|
|
296
453
|
var GatewayRunner = class {
|
|
297
454
|
constructor(opts) {
|
|
298
455
|
this.opts = opts;
|
|
299
|
-
for (const a of opts.adapters) this.adaptersByPlatform.set(a.platform, a);
|
|
300
456
|
this.hookExecutor = new HookExecutor(opts.hooks ?? []);
|
|
301
457
|
}
|
|
302
458
|
opts;
|
|
303
|
-
adaptersByPlatform = /* @__PURE__ */ new Map();
|
|
304
459
|
hookExecutor;
|
|
305
460
|
inflight = /* @__PURE__ */ new Set();
|
|
306
461
|
unsubs = [];
|
|
307
462
|
/** Slash command registry: name → handler (word-boundary match, EC-A). */
|
|
308
463
|
commands = /* @__PURE__ */ new Map();
|
|
309
464
|
startResult;
|
|
465
|
+
/** The start that has not settled yet, shared by every overlapping `start()` call. */
|
|
466
|
+
startInFlight;
|
|
310
467
|
stopped = false;
|
|
311
468
|
/**
|
|
312
469
|
* Register a slash command. Match rule (EC-A): text === "/" + name
|
|
@@ -323,10 +480,24 @@ var GatewayRunner = class {
|
|
|
323
480
|
* Resolves with what connected. A second call after the first resolved returns the same result
|
|
324
481
|
* without connecting again.
|
|
325
482
|
*
|
|
483
|
+
* Overlapping calls share one start; a start overtaken by stop resolves with no adapter connected.
|
|
484
|
+
* A call made before `stop()` while another is still connecting connects nothing and settles
|
|
485
|
+
* with it; a call made after `stop()` throws `runner_stopped`. When `stop()` runs before the
|
|
486
|
+
* connect settles, the adapters that connected are disconnected, no inbound dispatch is wired,
|
|
487
|
+
* and the start resolves `{ connected: [], failed }`, keeping the `"isolate"` failures. Under
|
|
488
|
+
* `"rollback"`, a connect that fails still rejects the start.
|
|
489
|
+
*
|
|
490
|
+
* Under `connectFailure: "rollback"`, every connect settles before the rollback, so a failing
|
|
491
|
+
* start rejects only once its slowest connect settles, as a successful one resolves only then.
|
|
492
|
+
*
|
|
493
|
+
* An adapter whose `disconnect()` fails while a start rolls back, or while a start that `stop()`
|
|
494
|
+
* overtook gives its adapters back, is named on stderr with the error redacted; how the start
|
|
495
|
+
* settles does not change.
|
|
496
|
+
*
|
|
326
497
|
* @throws {GatewayLifecycleError} `runner_stopped` — the runner was already
|
|
327
498
|
* stopped. A stopped runner is spent; construct a new one.
|
|
328
|
-
* @throws {Error} under the default `connectFailure: "rollback"`, the first connect failure, after
|
|
329
|
-
* adapters that did connect were disconnected.
|
|
499
|
+
* @throws {Error} under the default `connectFailure: "rollback"`, the first connect failure, after
|
|
500
|
+
* every connect settled and the adapters that did connect were disconnected.
|
|
330
501
|
*/
|
|
331
502
|
async start() {
|
|
332
503
|
if (this.stopped) {
|
|
@@ -336,7 +507,22 @@ var GatewayRunner = class {
|
|
|
336
507
|
});
|
|
337
508
|
}
|
|
338
509
|
if (this.startResult !== void 0) return this.startResult;
|
|
510
|
+
if (this.startInFlight === void 0) {
|
|
511
|
+
const pending = this.runStart();
|
|
512
|
+
this.startInFlight = pending;
|
|
513
|
+
pending.catch(() => {
|
|
514
|
+
if (this.startInFlight === pending) this.startInFlight = void 0;
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
return this.startInFlight;
|
|
518
|
+
}
|
|
519
|
+
async runStart() {
|
|
339
520
|
const result = (this.opts.connectFailure ?? "rollback") === "isolate" ? await this.connectIsolated() : await this.connectAllOrRollback();
|
|
521
|
+
if (this.stopped) {
|
|
522
|
+
await releaseAdapters(result.connected, "releasing a start that stop() overtook");
|
|
523
|
+
this.startResult = { connected: [], failed: result.failed };
|
|
524
|
+
return this.startResult;
|
|
525
|
+
}
|
|
340
526
|
this.wireInbound(result.connected);
|
|
341
527
|
this.startResult = {
|
|
342
528
|
connected: result.connected.map((a) => a.platform),
|
|
@@ -344,22 +530,36 @@ var GatewayRunner = class {
|
|
|
344
530
|
};
|
|
345
531
|
return this.startResult;
|
|
346
532
|
}
|
|
347
|
-
/**
|
|
533
|
+
/**
|
|
534
|
+
* All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow
|
|
535
|
+
* the first failure. Every connect settles before the rollback: rolling back while one is still
|
|
536
|
+
* pending left that adapter live once it connected.
|
|
537
|
+
*/
|
|
348
538
|
async connectAllOrRollback() {
|
|
349
|
-
const
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
})
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
539
|
+
const adapters = this.opts.adapters;
|
|
540
|
+
const failures = [];
|
|
541
|
+
const settled = await Promise.allSettled(
|
|
542
|
+
adapters.map(async (a) => {
|
|
543
|
+
let ok;
|
|
544
|
+
try {
|
|
545
|
+
ok = await a.connect();
|
|
546
|
+
} catch (err) {
|
|
547
|
+
failures.push(err);
|
|
548
|
+
throw err;
|
|
549
|
+
}
|
|
550
|
+
if (!ok) {
|
|
551
|
+
const refusal = new Error(`adapter "${a.platform}" connect returned false`);
|
|
552
|
+
failures.push(refusal);
|
|
553
|
+
throw refusal;
|
|
554
|
+
}
|
|
555
|
+
})
|
|
556
|
+
);
|
|
557
|
+
if (failures.length > 0) {
|
|
558
|
+
const connected = adapters.filter((_, i) => settled[i]?.status === "fulfilled");
|
|
559
|
+
await releaseAdapters(connected, "rolling back a failed start");
|
|
560
|
+
throw failures[0];
|
|
361
561
|
}
|
|
362
|
-
return { connected: [...
|
|
562
|
+
return { connected: [...adapters], failed: [] };
|
|
363
563
|
}
|
|
364
564
|
/**
|
|
365
565
|
* Connect every adapter and keep the ones that connected. The `async` wrapper turns a
|
|
@@ -381,7 +581,7 @@ var GatewayRunner = class {
|
|
|
381
581
|
wireInbound(adapters) {
|
|
382
582
|
for (const a of adapters) {
|
|
383
583
|
const unsub = a.onInbound(async (event) => {
|
|
384
|
-
const p = this.dispatch(event);
|
|
584
|
+
const p = this.dispatch(event, a);
|
|
385
585
|
this.inflight.add(p);
|
|
386
586
|
p.finally(() => this.inflight.delete(p));
|
|
387
587
|
});
|
|
@@ -390,7 +590,12 @@ var GatewayRunner = class {
|
|
|
390
590
|
}
|
|
391
591
|
/**
|
|
392
592
|
* Stop the runner. Drains in-flight handlers up to `drainTimeoutMs`,
|
|
393
|
-
* then disconnects adapters. Idempotent (EC-E).
|
|
593
|
+
* then disconnects adapters. Idempotent (EC-E). A disconnect that fails does not make `stop()`
|
|
594
|
+
* reject and does not stop the other disconnects; it is written to stderr, redacted, naming the
|
|
595
|
+
* platform.
|
|
596
|
+
*
|
|
597
|
+
* An adapter still connecting under an in-flight start is released when that start settles;
|
|
598
|
+
* `stop()` does not wait for it.
|
|
394
599
|
*/
|
|
395
600
|
async stop() {
|
|
396
601
|
if (this.stopped) return;
|
|
@@ -416,9 +621,7 @@ var GatewayRunner = class {
|
|
|
416
621
|
if (timer !== void 0) clearTimeout(timer);
|
|
417
622
|
}
|
|
418
623
|
}
|
|
419
|
-
await
|
|
420
|
-
[...this.adaptersByPlatform.values()].map((a) => a.disconnect().catch(() => void 0))
|
|
421
|
-
);
|
|
624
|
+
await releaseAdapters([...new Set(this.opts.adapters)], "stopping the runner");
|
|
422
625
|
}
|
|
423
626
|
/**
|
|
424
627
|
* @internal Test seam, following `EmailAdapter._threadStoreSize`. The drain set must SHRINK: a
|
|
@@ -430,12 +633,17 @@ var GatewayRunner = class {
|
|
|
430
633
|
return this.inflight.size;
|
|
431
634
|
}
|
|
432
635
|
/** @internal */
|
|
433
|
-
async dispatch(event) {
|
|
434
|
-
const ctx = this.buildContext(event);
|
|
636
|
+
async dispatch(event, adapter) {
|
|
637
|
+
const ctx = this.buildContext(event, adapter);
|
|
435
638
|
const decision = await this.hookExecutor.firePreInbound({ event });
|
|
436
639
|
if (decision.block === true) {
|
|
437
640
|
if (decision.message !== void 0 && decision.message.length > 0) {
|
|
438
|
-
await ctx.reply(decision.message).catch(() =>
|
|
641
|
+
await ctx.reply(decision.message).catch(async (err) => {
|
|
642
|
+
const error = err;
|
|
643
|
+
await this.hookExecutor.fireOnError({ event, error });
|
|
644
|
+
process.stderr.write(`[gateway] auto-reply error: ${redactSecrets(error.message)}
|
|
645
|
+
`);
|
|
646
|
+
});
|
|
439
647
|
}
|
|
440
648
|
return;
|
|
441
649
|
}
|
|
@@ -480,13 +688,14 @@ var GatewayRunner = class {
|
|
|
480
688
|
return void 0;
|
|
481
689
|
}
|
|
482
690
|
/** EC-G: per-event ctx whose reply routes to the matching adapter. */
|
|
483
|
-
buildContext(event) {
|
|
691
|
+
buildContext(event, adapter) {
|
|
484
692
|
return {
|
|
485
693
|
event,
|
|
486
|
-
reply: async (text, opts) => this.deliver(event, {
|
|
694
|
+
reply: async (text, opts) => this.deliver(event, adapter, {
|
|
487
695
|
channel: event.channel,
|
|
488
696
|
text,
|
|
489
|
-
...opts?.format !== void 0 ? { format: opts.format } : {}
|
|
697
|
+
...opts?.format !== void 0 ? { format: opts.format } : {},
|
|
698
|
+
...attachmentsOf(opts?.attachments)
|
|
490
699
|
})
|
|
491
700
|
};
|
|
492
701
|
}
|
|
@@ -498,6 +707,10 @@ var GatewayRunner = class {
|
|
|
498
707
|
* adapter for the platform. An audit hook that counted only the deliveries
|
|
499
708
|
* which reached a transport would omit precisely the ones that went nowhere.
|
|
500
709
|
*
|
|
710
|
+
* An outbound with attachments for an adapter that does not declare `supportsAttachments` is
|
|
711
|
+
* refused here as `attachments_unsupported`, with no `sendMessage` call, so an adapter that
|
|
712
|
+
* ignores the field cannot drop the image and report success (B-674).
|
|
713
|
+
*
|
|
501
714
|
* `post_outbound` observes; it does not intercept. The adapter's `SendResult`
|
|
502
715
|
* is returned to the caller unchanged, and `HookExecutor` already contains a
|
|
503
716
|
* throwing hook, so a broken observer cannot turn a delivered reply into a
|
|
@@ -505,9 +718,9 @@ var GatewayRunner = class {
|
|
|
505
718
|
*
|
|
506
719
|
* @internal
|
|
507
720
|
*/
|
|
508
|
-
async deliver(event, outbound) {
|
|
509
|
-
const
|
|
510
|
-
const result =
|
|
721
|
+
async deliver(event, adapter, outbound) {
|
|
722
|
+
const target = adapter?.platform === event.platform ? adapter : void 0;
|
|
723
|
+
const result = target === void 0 ? { ok: false, error: { code: "no_adapter", message: `no adapter for ${event.platform}` } } : refuseUnsupportedAttachments(target, outbound) ?? await target.sendMessage(outbound);
|
|
511
724
|
await this.hookExecutor.firePostOutbound({ event, outbound, result });
|
|
512
725
|
return result;
|
|
513
726
|
}
|
|
@@ -543,6 +756,64 @@ var SessionRouter = class {
|
|
|
543
756
|
}
|
|
544
757
|
};
|
|
545
758
|
|
|
759
|
+
// src/text/fence.ts
|
|
760
|
+
var MAY_FENCE = /^ {0,3}(?:`{3}|~{3})/m;
|
|
761
|
+
var OPENING = /^ {0,3}(`{3,}|~{3,})(.*)$/;
|
|
762
|
+
var CLOSING = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
|
|
763
|
+
function lineEndAt(text, from) {
|
|
764
|
+
let end = from;
|
|
765
|
+
while (end < text.length && text[end] !== "\n" && text[end] !== "\r") end += 1;
|
|
766
|
+
let next = end;
|
|
767
|
+
if (text[next] === "\r" && text[next + 1] === "\n") next += 2;
|
|
768
|
+
else if (next < text.length) next += 1;
|
|
769
|
+
return { end, next };
|
|
770
|
+
}
|
|
771
|
+
function findClose(text, from, run) {
|
|
772
|
+
for (let scan = from; scan < text.length; ) {
|
|
773
|
+
const line = lineEndAt(text, scan);
|
|
774
|
+
const found = CLOSING.exec(text.slice(scan, line.end))?.[1];
|
|
775
|
+
if (found !== void 0 && found[0] === run[0] && found.length >= run.length) return line;
|
|
776
|
+
scan = line.next;
|
|
777
|
+
}
|
|
778
|
+
return void 0;
|
|
779
|
+
}
|
|
780
|
+
function scanFences(text) {
|
|
781
|
+
if (!MAY_FENCE.test(text)) return [];
|
|
782
|
+
const regions = [];
|
|
783
|
+
let pos = 0;
|
|
784
|
+
while (pos < text.length) {
|
|
785
|
+
const start = pos;
|
|
786
|
+
const line = lineEndAt(text, start);
|
|
787
|
+
const open = OPENING.exec(text.slice(start, line.end));
|
|
788
|
+
const run = open?.[1];
|
|
789
|
+
if (run === void 0 || run.startsWith("`") && (open?.[2] ?? "").includes("`")) {
|
|
790
|
+
pos = line.next;
|
|
791
|
+
continue;
|
|
792
|
+
}
|
|
793
|
+
const close = findClose(text, line.next, run);
|
|
794
|
+
pos = close?.next ?? text.length;
|
|
795
|
+
const end = close?.end ?? text.length;
|
|
796
|
+
const closed = close !== void 0;
|
|
797
|
+
regions.push({
|
|
798
|
+
start,
|
|
799
|
+
openerEnd: line.end,
|
|
800
|
+
contentStart: line.next,
|
|
801
|
+
end,
|
|
802
|
+
opener: text.slice(start, line.end),
|
|
803
|
+
closer: run,
|
|
804
|
+
closed
|
|
805
|
+
});
|
|
806
|
+
}
|
|
807
|
+
return regions;
|
|
808
|
+
}
|
|
809
|
+
function fenceAt(regions, offset) {
|
|
810
|
+
return regions.find((r) => r.start < offset && offset < r.end);
|
|
811
|
+
}
|
|
812
|
+
function openerEol(text, region) {
|
|
813
|
+
if (text.startsWith("\r\n", region.openerEnd)) return "\r\n";
|
|
814
|
+
return text[region.openerEnd] === "\r" ? "\r" : "\n";
|
|
815
|
+
}
|
|
816
|
+
|
|
546
817
|
// src/text/dialect.ts
|
|
547
818
|
var DIALECTS = {
|
|
548
819
|
// WhatsApp emphasis is inline and single-character: *bold*, _italic_, ~strike~, ```mono```.
|
|
@@ -565,18 +836,90 @@ function toDialect(text, platform) {
|
|
|
565
836
|
if (dialect === void 0) return text;
|
|
566
837
|
return rewriteMarkers(text, dialect);
|
|
567
838
|
}
|
|
839
|
+
function markerFor(matched, groups, dialect) {
|
|
840
|
+
if (groups === void 0) return matched;
|
|
841
|
+
for (const [group, marker] of GROUP_MARKERS) {
|
|
842
|
+
const content = groups[group];
|
|
843
|
+
if (content === void 0) continue;
|
|
844
|
+
const wrap = dialect[marker];
|
|
845
|
+
return wrap === void 0 ? content : `${wrap}${content}${wrap}`;
|
|
846
|
+
}
|
|
847
|
+
return matched;
|
|
848
|
+
}
|
|
849
|
+
function rewriteMatch(matched, args, dialect) {
|
|
850
|
+
return markerFor(matched, args.at(-1), dialect);
|
|
851
|
+
}
|
|
852
|
+
function replaceMarkers(text, dialect) {
|
|
853
|
+
return text.replace(PATTERN, (matched, ...args) => rewriteMatch(matched, args, dialect));
|
|
854
|
+
}
|
|
855
|
+
var ROW_START = /[^\S\r\n]*\|/y;
|
|
856
|
+
var LINE_ENDING = /(\r\n|\r|\n)/;
|
|
857
|
+
var MARKER_CHARACTER = /[*_~\x60]/;
|
|
858
|
+
var PIPE = 124;
|
|
859
|
+
var BACKSLASH = 92;
|
|
860
|
+
var LF = 10;
|
|
861
|
+
var CR = 13;
|
|
862
|
+
function rowLocator(text) {
|
|
863
|
+
const rowStart = new RegExp(ROW_START);
|
|
864
|
+
let lineStart = 0;
|
|
865
|
+
let scanned = 0;
|
|
866
|
+
return (offset) => {
|
|
867
|
+
for (; scanned < offset; scanned += 1) {
|
|
868
|
+
const code = text.charCodeAt(scanned);
|
|
869
|
+
if (code === LF || code === CR) lineStart = scanned + 1;
|
|
870
|
+
}
|
|
871
|
+
rowStart.lastIndex = lineStart;
|
|
872
|
+
return rowStart.test(text);
|
|
873
|
+
};
|
|
874
|
+
}
|
|
875
|
+
function rewriteTableRow(row, dialect) {
|
|
876
|
+
let out = "";
|
|
877
|
+
let from = 0;
|
|
878
|
+
let backslashes = 0;
|
|
879
|
+
for (let i = 0; i < row.length; i += 1) {
|
|
880
|
+
const code = row.charCodeAt(i);
|
|
881
|
+
if (code === BACKSLASH) {
|
|
882
|
+
backslashes += 1;
|
|
883
|
+
continue;
|
|
884
|
+
}
|
|
885
|
+
if (code === PIPE && backslashes % 2 === 0) {
|
|
886
|
+
out += `${replaceMarkers(row.slice(from, i), dialect)}|`;
|
|
887
|
+
from = i + 1;
|
|
888
|
+
}
|
|
889
|
+
backslashes = 0;
|
|
890
|
+
}
|
|
891
|
+
return out + replaceMarkers(row.slice(from), dialect);
|
|
892
|
+
}
|
|
893
|
+
function rewriteLine(line, dialect, rowStart) {
|
|
894
|
+
rowStart.lastIndex = 0;
|
|
895
|
+
if (!rowStart.test(line)) return replaceMarkers(line, dialect);
|
|
896
|
+
return MARKER_CHARACTER.test(line) ? rewriteTableRow(line, dialect) : line;
|
|
897
|
+
}
|
|
898
|
+
function rewriteByLine(text, dialect) {
|
|
899
|
+
const rowStart = new RegExp(ROW_START);
|
|
900
|
+
return text.split(LINE_ENDING).map((piece) => rewriteLine(piece, dialect, rowStart)).join("");
|
|
901
|
+
}
|
|
568
902
|
function rewriteMarkers(text, dialect) {
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
903
|
+
const regions = scanFences(text);
|
|
904
|
+
if (regions.length === 0) return rewriteUnfenced(text, dialect);
|
|
905
|
+
let out = "";
|
|
906
|
+
let from = 0;
|
|
907
|
+
for (const region of regions) {
|
|
908
|
+
out += rewriteUnfenced(text.slice(from, region.start), dialect) + text.slice(region.start, region.end);
|
|
909
|
+
from = region.end;
|
|
910
|
+
}
|
|
911
|
+
return out + rewriteUnfenced(text.slice(from), dialect);
|
|
912
|
+
}
|
|
913
|
+
function rewriteUnfenced(text, dialect) {
|
|
914
|
+
const onTableRow = rowLocator(text);
|
|
915
|
+
let crossesRowPipe = false;
|
|
916
|
+
const rewritten = text.replace(PATTERN, (matched, ...args) => {
|
|
917
|
+
if (!crossesRowPipe && matched.includes("|")) {
|
|
918
|
+
crossesRowPipe = onTableRow(args.at(-3));
|
|
577
919
|
}
|
|
578
|
-
return matched;
|
|
920
|
+
return rewriteMatch(matched, args, dialect);
|
|
579
921
|
});
|
|
922
|
+
return crossesRowPipe ? rewriteByLine(text, dialect) : rewritten;
|
|
580
923
|
}
|
|
581
924
|
|
|
582
925
|
// src/text/channel-rendering.ts
|
|
@@ -590,11 +933,24 @@ var RENDERINGS = {
|
|
|
590
933
|
discord: { format: "markdown", translate: identity },
|
|
591
934
|
mattermost: { format: "markdown", translate: identity },
|
|
592
935
|
teams: { format: "markdown", translate: identity },
|
|
936
|
+
signal: { format: "markdown", translate: identity },
|
|
593
937
|
line: { format: "plain", translate: translateWith(DIALECTS.line) },
|
|
594
938
|
sms: { format: "plain", translate: translateWith(DIALECTS.sms) },
|
|
595
939
|
telegram: { format: "plain", translate: translateWith(STRIP) },
|
|
596
940
|
matrix: { format: "plain", translate: translateWith(STRIP) },
|
|
597
|
-
email: { format: "plain", translate: translateWith(STRIP) }
|
|
941
|
+
email: { format: "plain", translate: translateWith(STRIP) },
|
|
942
|
+
imessage: { format: "plain", translate: translateWith(STRIP) },
|
|
943
|
+
google_chat: { format: "plain", translate: translateWith(STRIP) },
|
|
944
|
+
irc: { format: "plain", translate: translateWith(STRIP) },
|
|
945
|
+
nextcloud_talk: { format: "markdown", translate: identity },
|
|
946
|
+
nostr: { format: "plain", translate: translateWith(STRIP) },
|
|
947
|
+
feishu_lark: { format: "plain", translate: translateWith(STRIP) },
|
|
948
|
+
synology_chat: { format: "plain", translate: translateWith(STRIP) },
|
|
949
|
+
tlon_urbit: { format: "plain", translate: translateWith(STRIP) },
|
|
950
|
+
twitch: { format: "plain", translate: translateWith(STRIP) },
|
|
951
|
+
buzz: { format: "plain", translate: translateWith(STRIP) },
|
|
952
|
+
clickclack: { format: "plain", translate: translateWith(STRIP) },
|
|
953
|
+
zalo_personal: { format: "plain", translate: translateWith(STRIP) }
|
|
598
954
|
};
|
|
599
955
|
function channelRendering(platform) {
|
|
600
956
|
const rendering = Object.hasOwn(RENDERINGS, platform) ? RENDERINGS[platform] : void 0;
|
|
@@ -633,6 +989,63 @@ function findCut(remaining, window, boundaries, lastResort, surrogateGuard) {
|
|
|
633
989
|
if (surrogateGuard) cut = guardSurrogate(remaining, cut);
|
|
634
990
|
return cut <= 0 ? window : cut;
|
|
635
991
|
}
|
|
992
|
+
var isLineEnd = (ch) => ch === "\n" || ch === "\r";
|
|
993
|
+
function startsTableRow(text, from) {
|
|
994
|
+
let at = from;
|
|
995
|
+
while (at < text.length && /^[^\S\r\n]$/.test(text[at] ?? "")) at += 1;
|
|
996
|
+
return text[at] === "|";
|
|
997
|
+
}
|
|
998
|
+
function rowSafeCut(text, cut, window) {
|
|
999
|
+
const start = tableRowStart(text, cut);
|
|
1000
|
+
if (start === void 0 || rowLength(text, start, cut, window) > window) return void 0;
|
|
1001
|
+
let end = start;
|
|
1002
|
+
while (end > 0 && isLineEnd(text[end - 1])) end -= 1;
|
|
1003
|
+
return end > 0 ? { end, start } : void 0;
|
|
1004
|
+
}
|
|
1005
|
+
function tableRowStart(text, cut) {
|
|
1006
|
+
if (cut >= text.length || isLineEnd(text[cut])) return void 0;
|
|
1007
|
+
let start = cut;
|
|
1008
|
+
while (start > 0 && !isLineEnd(text[start - 1])) start -= 1;
|
|
1009
|
+
return start > 0 && startsTableRow(text, start) ? start : void 0;
|
|
1010
|
+
}
|
|
1011
|
+
function rowLength(text, start, cut, window) {
|
|
1012
|
+
let rowEnd = cut;
|
|
1013
|
+
while (rowEnd < text.length && rowEnd - start <= window && !isLineEnd(text[rowEnd])) rowEnd += 1;
|
|
1014
|
+
return rowEnd - start;
|
|
1015
|
+
}
|
|
1016
|
+
function rowStep(remaining, cut, window) {
|
|
1017
|
+
const moved = rowSafeCut(remaining, cut, window);
|
|
1018
|
+
if (moved === void 0) return void 0;
|
|
1019
|
+
return { chunk: remaining.slice(0, moved.end), remaining: remaining.slice(moved.start) };
|
|
1020
|
+
}
|
|
1021
|
+
function stepBeforeFence(remaining, region) {
|
|
1022
|
+
let end = region.start;
|
|
1023
|
+
while (end > 0 && isLineEnd(remaining[end - 1])) end -= 1;
|
|
1024
|
+
if (end === 0) return void 0;
|
|
1025
|
+
return { chunk: remaining.slice(0, end), remaining: remaining.slice(region.start) };
|
|
1026
|
+
}
|
|
1027
|
+
function stepThroughFence(remaining, region, window, surrogateGuard) {
|
|
1028
|
+
const eol = openerEol(remaining, region);
|
|
1029
|
+
const room = window - region.closer.length - eol.length;
|
|
1030
|
+
if (room <= region.contentStart) return void 0;
|
|
1031
|
+
let at = remaining.lastIndexOf("\n", room);
|
|
1032
|
+
let rest = at + 1;
|
|
1033
|
+
if (at < region.contentStart) {
|
|
1034
|
+
at = surrogateGuard ? guardSurrogate(remaining, room) : room;
|
|
1035
|
+
rest = at;
|
|
1036
|
+
} else if (remaining[at - 1] === "\r") {
|
|
1037
|
+
at -= 1;
|
|
1038
|
+
}
|
|
1039
|
+
return {
|
|
1040
|
+
chunk: `${remaining.slice(0, at)}${eol}${region.closer}`,
|
|
1041
|
+
remaining: `${region.opener}${eol}${remaining.slice(rest)}`
|
|
1042
|
+
};
|
|
1043
|
+
}
|
|
1044
|
+
function fenceStep(remaining, cut, window, surrogateGuard) {
|
|
1045
|
+
const region = fenceAt(scanFences(remaining), cut);
|
|
1046
|
+
if (region === void 0) return void 0;
|
|
1047
|
+
return cut <= region.openerEnd ? stepBeforeFence(remaining, region) : stepThroughFence(remaining, region, window, surrogateGuard);
|
|
1048
|
+
}
|
|
636
1049
|
function chunkText(text, options) {
|
|
637
1050
|
const {
|
|
638
1051
|
limit,
|
|
@@ -641,7 +1054,8 @@ function chunkText(text, options) {
|
|
|
641
1054
|
lastResort = "window",
|
|
642
1055
|
surrogateGuard = false,
|
|
643
1056
|
stripLeading = /^\n+/,
|
|
644
|
-
trimParts = false
|
|
1057
|
+
trimParts = false,
|
|
1058
|
+
keepTableRows = false
|
|
645
1059
|
} = options;
|
|
646
1060
|
assertPositiveInt("chunkText: limit", limit);
|
|
647
1061
|
assertPositiveInt("chunkText: safeLimit", safeLimit);
|
|
@@ -653,11 +1067,16 @@ function chunkText(text, options) {
|
|
|
653
1067
|
return finalize([text]);
|
|
654
1068
|
}
|
|
655
1069
|
const parts = [];
|
|
1070
|
+
const hasFence = scanFences(text).length > 0;
|
|
656
1071
|
let remaining = text;
|
|
657
1072
|
while (remaining.length > safeLimit) {
|
|
658
1073
|
const cut = findCut(remaining, safeLimit, boundaries, lastResort, surrogateGuard);
|
|
659
|
-
|
|
660
|
-
|
|
1074
|
+
const step = (hasFence ? fenceStep(remaining, cut, safeLimit, surrogateGuard) : void 0) ?? (keepTableRows ? rowStep(remaining, cut, safeLimit) : void 0) ?? {
|
|
1075
|
+
chunk: remaining.slice(0, cut),
|
|
1076
|
+
remaining: remaining.slice(cut).replace(stripLeading, "")
|
|
1077
|
+
};
|
|
1078
|
+
parts.push(step.chunk);
|
|
1079
|
+
remaining = step.remaining;
|
|
661
1080
|
}
|
|
662
1081
|
if (remaining.length > 0) parts.push(remaining);
|
|
663
1082
|
return finalize(parts);
|
|
@@ -668,6 +1087,8 @@ function chunkByGrapheme(text, options) {
|
|
|
668
1087
|
assertPositiveInt("chunkByGrapheme: partLimit", partLimit);
|
|
669
1088
|
if (text.length === 0) return [""];
|
|
670
1089
|
if (text.length <= limit) return [text];
|
|
1090
|
+
const regions = scanFences(text);
|
|
1091
|
+
if (regions.length > 0) return chunkFencedByGrapheme(text, partLimit, regions);
|
|
671
1092
|
const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
|
|
672
1093
|
const parts = [];
|
|
673
1094
|
let buf = "";
|
|
@@ -681,6 +1102,132 @@ function chunkByGrapheme(text, options) {
|
|
|
681
1102
|
if (buf.length > 0) parts.push(buf);
|
|
682
1103
|
return parts;
|
|
683
1104
|
}
|
|
1105
|
+
function graphemeBoundaries(text) {
|
|
1106
|
+
const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
|
|
1107
|
+
const starts = Array.from(segmenter.segment(text), (s) => s.index);
|
|
1108
|
+
starts.push(text.length);
|
|
1109
|
+
return (pos, max) => {
|
|
1110
|
+
const after = starts.filter((b) => b > pos);
|
|
1111
|
+
const within = after.filter((b) => b <= max);
|
|
1112
|
+
return within.at(-1) ?? after[0] ?? text.length;
|
|
1113
|
+
};
|
|
1114
|
+
}
|
|
1115
|
+
function chunkFencedByGrapheme(text, partLimit, regions) {
|
|
1116
|
+
const boundaryUpTo = graphemeBoundaries(text);
|
|
1117
|
+
const parts = [];
|
|
1118
|
+
let pos = 0;
|
|
1119
|
+
let prefix = "";
|
|
1120
|
+
while (prefix.length + (text.length - pos) > partLimit) {
|
|
1121
|
+
const room = partLimit - prefix.length;
|
|
1122
|
+
const plain = boundaryUpTo(pos, pos + room);
|
|
1123
|
+
const region = fenceAt(regions, plain);
|
|
1124
|
+
const next = region === void 0 ? { cut: plain, suffix: "", reopen: "" } : fenceGraphemeCut(text, region, pos, plain, room, boundaryUpTo);
|
|
1125
|
+
parts.push(prefix + text.slice(pos, next.cut) + next.suffix);
|
|
1126
|
+
pos = next.cut;
|
|
1127
|
+
prefix = next.reopen;
|
|
1128
|
+
}
|
|
1129
|
+
parts.push(prefix + text.slice(pos));
|
|
1130
|
+
return parts;
|
|
1131
|
+
}
|
|
1132
|
+
function fenceGraphemeCut(text, region, pos, plain, room, boundaryUpTo) {
|
|
1133
|
+
const none = { cut: plain, suffix: "", reopen: "" };
|
|
1134
|
+
if (plain <= region.openerEnd) {
|
|
1135
|
+
return region.start > pos ? { ...none, cut: region.start } : none;
|
|
1136
|
+
}
|
|
1137
|
+
const eol = openerEol(text, region);
|
|
1138
|
+
const max = pos + room - region.closer.length - eol.length;
|
|
1139
|
+
const floor = Math.max(pos, region.contentStart);
|
|
1140
|
+
if (max <= floor) return none;
|
|
1141
|
+
let at = boundaryUpTo(pos, max);
|
|
1142
|
+
const nl = text.lastIndexOf("\n", at - 1);
|
|
1143
|
+
if (nl >= floor - 1 && nl + 1 > pos) at = nl + 1;
|
|
1144
|
+
if (at <= pos || at > max) return none;
|
|
1145
|
+
if (fenceAt([region], at) === void 0) return { ...none, cut: at };
|
|
1146
|
+
const closes = isLineEnd(text[at - 1]);
|
|
1147
|
+
return { cut: at, suffix: (closes ? "" : eol) + region.closer, reopen: region.opener + eol };
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
// src/text/seen-ids.ts
|
|
1151
|
+
var DEFAULT_LIMIT = 1e3;
|
|
1152
|
+
var SeenIds = class {
|
|
1153
|
+
/** @param limit the most ids held at once; the oldest is forgotten when one more arrives */
|
|
1154
|
+
constructor(limit = DEFAULT_LIMIT) {
|
|
1155
|
+
this.limit = limit;
|
|
1156
|
+
}
|
|
1157
|
+
limit;
|
|
1158
|
+
ids = /* @__PURE__ */ new Set();
|
|
1159
|
+
/**
|
|
1160
|
+
* Record `id`.
|
|
1161
|
+
*
|
|
1162
|
+
* @returns `true` when the id was new, `false` when it was already held
|
|
1163
|
+
*/
|
|
1164
|
+
add(id) {
|
|
1165
|
+
if (this.ids.has(id)) return false;
|
|
1166
|
+
this.ids.add(id);
|
|
1167
|
+
if (this.ids.size > this.limit) {
|
|
1168
|
+
const oldest = this.ids.values().next().value;
|
|
1169
|
+
if (oldest !== void 0) this.ids.delete(oldest);
|
|
1170
|
+
}
|
|
1171
|
+
return true;
|
|
1172
|
+
}
|
|
1173
|
+
/** Whether `id` is held. */
|
|
1174
|
+
has(id) {
|
|
1175
|
+
return this.ids.has(id);
|
|
1176
|
+
}
|
|
1177
|
+
/** How many ids are held. */
|
|
1178
|
+
get size() {
|
|
1179
|
+
return this.ids.size;
|
|
1180
|
+
}
|
|
1181
|
+
};
|
|
1182
|
+
|
|
1183
|
+
// src/text/split-rows.ts
|
|
1184
|
+
var ROW_BLANK = /^[^\S\r\n]$/;
|
|
1185
|
+
function isLineEnd2(character) {
|
|
1186
|
+
return character === "\n" || character === "\r";
|
|
1187
|
+
}
|
|
1188
|
+
function startsTableRow2(text, from) {
|
|
1189
|
+
let at = from;
|
|
1190
|
+
while (at < text.length && ROW_BLANK.test(text[at] ?? "")) at += 1;
|
|
1191
|
+
return text[at] === "|";
|
|
1192
|
+
}
|
|
1193
|
+
function lineStartBefore(text, cut, partStart) {
|
|
1194
|
+
let at = cut;
|
|
1195
|
+
while (at > partStart && !isLineEnd2(text[at - 1])) at -= 1;
|
|
1196
|
+
return at;
|
|
1197
|
+
}
|
|
1198
|
+
function lineEndFrom(text, cut, bound) {
|
|
1199
|
+
let at = cut;
|
|
1200
|
+
while (at < text.length && at <= bound && !isLineEnd2(text[at])) at += 1;
|
|
1201
|
+
return at;
|
|
1202
|
+
}
|
|
1203
|
+
function rowSafeCut2(text, partStart, cut, partLimit) {
|
|
1204
|
+
const lineStart = lineStartBefore(text, cut, partStart);
|
|
1205
|
+
if (lineStart <= partStart || lineStart === cut) return cut;
|
|
1206
|
+
if (isLineEnd2(text[cut]) || !startsTableRow2(text, lineStart)) return cut;
|
|
1207
|
+
const lineEnd = lineEndFrom(text, cut, lineStart + partLimit);
|
|
1208
|
+
return lineEnd - lineStart <= partLimit ? lineStart : cut;
|
|
1209
|
+
}
|
|
1210
|
+
function graphemeCut(segments, start, partLimit) {
|
|
1211
|
+
const cut = start + partLimit;
|
|
1212
|
+
const segment = segments.containing(cut);
|
|
1213
|
+
if (segment === void 0 || segment.index >= cut) return cut;
|
|
1214
|
+
return segment.index > start ? segment.index : segment.index + segment.segment.length;
|
|
1215
|
+
}
|
|
1216
|
+
function splitKeepingRows(text, partLimit) {
|
|
1217
|
+
const segments = new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(text);
|
|
1218
|
+
const parts = [];
|
|
1219
|
+
let start = 0;
|
|
1220
|
+
while (text.length - start > partLimit) {
|
|
1221
|
+
const cut = rowSafeCut2(text, start, graphemeCut(segments, start, partLimit), partLimit);
|
|
1222
|
+
if (cut <= start) {
|
|
1223
|
+
throw new RangeError(`splitKeepingRows: no progress at offset ${start} of ${text.length}`);
|
|
1224
|
+
}
|
|
1225
|
+
parts.push(text.slice(start, cut));
|
|
1226
|
+
start = cut;
|
|
1227
|
+
}
|
|
1228
|
+
if (start < text.length) parts.push(text.slice(start));
|
|
1229
|
+
return parts;
|
|
1230
|
+
}
|
|
684
1231
|
|
|
685
1232
|
// src/webhook/express-server.ts
|
|
686
1233
|
async function loadPeer(load, onMissing) {
|
|
@@ -691,8 +1238,14 @@ async function loadPeer(load, onMissing) {
|
|
|
691
1238
|
onMissing();
|
|
692
1239
|
}
|
|
693
1240
|
}
|
|
694
|
-
function rawBodyCapture(tag) {
|
|
695
|
-
|
|
1241
|
+
function rawBodyCapture(tag, options = {}) {
|
|
1242
|
+
const { maxBytes } = options;
|
|
1243
|
+
if (maxBytes !== void 0 && !(Number.isFinite(maxBytes) && maxBytes >= 0)) {
|
|
1244
|
+
throw new RangeError(
|
|
1245
|
+
`[${tag}] rawBodyCapture: maxBytes must be a finite number of zero or more, got ${maxBytes}`
|
|
1246
|
+
);
|
|
1247
|
+
}
|
|
1248
|
+
return (rawReq, rawRes, next) => {
|
|
696
1249
|
const req = rawReq;
|
|
697
1250
|
if (req.readableEnded === true || req.complete === true) {
|
|
698
1251
|
process.stderr.write(
|
|
@@ -704,17 +1257,48 @@ function rawBodyCapture(tag) {
|
|
|
704
1257
|
return;
|
|
705
1258
|
}
|
|
706
1259
|
let buf = "";
|
|
1260
|
+
let bytes = 0;
|
|
1261
|
+
let refused2 = maxBytes !== void 0 && declaredLength(req) > maxBytes;
|
|
1262
|
+
let settled = false;
|
|
707
1263
|
req.setEncoding("utf8");
|
|
708
1264
|
req.on("data", (chunk) => {
|
|
1265
|
+
if (refused2 || settled) return;
|
|
1266
|
+
bytes += Buffer.byteLength(chunk);
|
|
1267
|
+
if (maxBytes !== void 0 && bytes > maxBytes) {
|
|
1268
|
+
refused2 = true;
|
|
1269
|
+
buf = "";
|
|
1270
|
+
return;
|
|
1271
|
+
}
|
|
709
1272
|
buf += chunk;
|
|
710
1273
|
});
|
|
711
1274
|
req.on("end", () => {
|
|
1275
|
+
if (settled) return;
|
|
1276
|
+
settled = true;
|
|
1277
|
+
if (refused2) {
|
|
1278
|
+
answerTooLarge(rawRes, tag, maxBytes ?? 0);
|
|
1279
|
+
return;
|
|
1280
|
+
}
|
|
712
1281
|
req.rawBody = buf;
|
|
713
1282
|
next();
|
|
714
1283
|
});
|
|
715
|
-
req.on("error", (err) =>
|
|
1284
|
+
req.on("error", (err) => {
|
|
1285
|
+
if (settled) return;
|
|
1286
|
+
settled = true;
|
|
1287
|
+
if (refused2) return;
|
|
1288
|
+
next(err);
|
|
1289
|
+
});
|
|
716
1290
|
};
|
|
717
1291
|
}
|
|
1292
|
+
function declaredLength(req) {
|
|
1293
|
+
const value = req.headers?.["content-length"];
|
|
1294
|
+
const declared = Number(Array.isArray(value) ? value[0] : value);
|
|
1295
|
+
return Number.isFinite(declared) ? declared : 0;
|
|
1296
|
+
}
|
|
1297
|
+
function answerTooLarge(res, tag, maxBytes) {
|
|
1298
|
+
process.stderr.write(`[${tag}] refused a request (413): body larger than ${maxBytes} bytes
|
|
1299
|
+
`);
|
|
1300
|
+
res.status(413).json({ error: "request body too large" });
|
|
1301
|
+
}
|
|
718
1302
|
function listenerLifecycle(opts) {
|
|
719
1303
|
let started = false;
|
|
720
1304
|
let stopped = false;
|
|
@@ -726,8 +1310,17 @@ function listenerLifecycle(opts) {
|
|
|
726
1310
|
return;
|
|
727
1311
|
}
|
|
728
1312
|
stopped = false;
|
|
729
|
-
await new Promise((resolve) => {
|
|
730
|
-
|
|
1313
|
+
await new Promise((resolve, reject) => {
|
|
1314
|
+
const settle = (err) => {
|
|
1315
|
+
if (err === void 0) resolve();
|
|
1316
|
+
else reject(err);
|
|
1317
|
+
};
|
|
1318
|
+
const current = opts.app.listen(opts.port, settle);
|
|
1319
|
+
listener = current;
|
|
1320
|
+
current.once?.("error", settle);
|
|
1321
|
+
}).catch((err) => {
|
|
1322
|
+
listener = void 0;
|
|
1323
|
+
throw err;
|
|
731
1324
|
});
|
|
732
1325
|
started = true;
|
|
733
1326
|
},
|
|
@@ -752,6 +1345,7 @@ exports.GatewayConfigurationError = GatewayConfigurationError;
|
|
|
752
1345
|
exports.GatewayLifecycleError = GatewayLifecycleError;
|
|
753
1346
|
exports.GatewayRunner = GatewayRunner;
|
|
754
1347
|
exports.HookExecutor = HookExecutor;
|
|
1348
|
+
exports.SeenIds = SeenIds;
|
|
755
1349
|
exports.SessionRouter = SessionRouter;
|
|
756
1350
|
exports.channelRendering = channelRendering;
|
|
757
1351
|
exports.chunkByGrapheme = chunkByGrapheme;
|
|
@@ -763,6 +1357,8 @@ exports.loadPeer = loadPeer;
|
|
|
763
1357
|
exports.maskShapes = maskShapes;
|
|
764
1358
|
exports.rawBodyCapture = rawBodyCapture;
|
|
765
1359
|
exports.redactSecrets = redactSecrets;
|
|
1360
|
+
exports.scanFences = scanFences;
|
|
1361
|
+
exports.splitKeepingRows = splitKeepingRows;
|
|
766
1362
|
exports.toDialect = toDialect;
|
|
767
1363
|
//# sourceMappingURL=index.cjs.map
|
|
768
1364
|
//# sourceMappingURL=index.cjs.map
|