@theokit/gateway 0.12.0 → 0.15.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/dist/index.js CHANGED
@@ -1,5 +1,216 @@
1
1
  import { Security } from '@theokit/sdk';
2
2
 
3
+ // src/text/fence.ts
4
+ var MAY_FENCE = /^ {0,3}(?:`{3}|~{3})/m;
5
+ var OPENING = /^ {0,3}(`{3,}|~{3,})(.*)$/;
6
+ var CLOSING = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
7
+ function lineEndAt(text, from) {
8
+ let end = from;
9
+ while (end < text.length && text[end] !== "\n" && text[end] !== "\r") end += 1;
10
+ let next = end;
11
+ if (text[next] === "\r" && text[next + 1] === "\n") next += 2;
12
+ else if (next < text.length) next += 1;
13
+ return { end, next };
14
+ }
15
+ function findClose(text, from, run) {
16
+ for (let scan = from; scan < text.length; ) {
17
+ const line = lineEndAt(text, scan);
18
+ const found = CLOSING.exec(text.slice(scan, line.end))?.[1];
19
+ if (found !== void 0 && found[0] === run[0] && found.length >= run.length) return line;
20
+ scan = line.next;
21
+ }
22
+ return void 0;
23
+ }
24
+ function scanFences(text) {
25
+ if (!MAY_FENCE.test(text)) return [];
26
+ const regions = [];
27
+ let pos = 0;
28
+ while (pos < text.length) {
29
+ const start = pos;
30
+ const line = lineEndAt(text, start);
31
+ const open = OPENING.exec(text.slice(start, line.end));
32
+ const run = open?.[1];
33
+ if (run === void 0 || run.startsWith("`") && (open?.[2] ?? "").includes("`")) {
34
+ pos = line.next;
35
+ continue;
36
+ }
37
+ const close = findClose(text, line.next, run);
38
+ pos = close?.next ?? text.length;
39
+ const end = close?.end ?? text.length;
40
+ const closed = close !== void 0;
41
+ regions.push({
42
+ start,
43
+ openerEnd: line.end,
44
+ contentStart: line.next,
45
+ end,
46
+ opener: text.slice(start, line.end),
47
+ closer: run,
48
+ closed
49
+ });
50
+ }
51
+ return regions;
52
+ }
53
+ function fenceAt(regions, offset) {
54
+ return regions.find((r) => r.start < offset && offset < r.end);
55
+ }
56
+ function openerEol(text, region) {
57
+ if (text.startsWith("\r\n", region.openerEnd)) return "\r\n";
58
+ return text[region.openerEnd] === "\r" ? "\r" : "\n";
59
+ }
60
+
61
+ // src/text/dialect.ts
62
+ var DIALECTS = {
63
+ // WhatsApp emphasis is inline and single-character: *bold*, _italic_, ~strike~, ```mono```.
64
+ whatsapp: { bold: "*", italic: "_", strike: "~", code: "```" },
65
+ // LINE text messages carry no rich text at all — decoration is emoji-only. Markers are dropped.
66
+ line: {},
67
+ // SMS is plain text by definition of the medium.
68
+ sms: {}
69
+ };
70
+ var PATTERN = /\*\*(?<bold>.+?)\*\*|~~(?<strike>.+?)~~|(?<![*\w])\*(?!\s)(?<italicStar>.+?)(?<!\s)\*(?!\*)|(?<![_\w])_(?!\s)(?<italicUnderscore>.+?)(?<!\s)_(?!\w)|`(?<code>.+?)`/gu;
71
+ var GROUP_MARKERS = [
72
+ ["bold", "bold"],
73
+ ["strike", "strike"],
74
+ ["italicStar", "italic"],
75
+ ["italicUnderscore", "italic"],
76
+ ["code", "code"]
77
+ ];
78
+ function toDialect(text, platform) {
79
+ const dialect = DIALECTS[platform];
80
+ if (dialect === void 0) return text;
81
+ return rewriteMarkers(text, dialect);
82
+ }
83
+ function markerFor(matched, groups, dialect) {
84
+ if (groups === void 0) return matched;
85
+ for (const [group, marker] of GROUP_MARKERS) {
86
+ const content = groups[group];
87
+ if (content === void 0) continue;
88
+ const wrap = dialect[marker];
89
+ return wrap === void 0 ? content : `${wrap}${content}${wrap}`;
90
+ }
91
+ return matched;
92
+ }
93
+ function rewriteMatch(matched, args, dialect) {
94
+ return markerFor(matched, args.at(-1), dialect);
95
+ }
96
+ function replaceMarkers(text, dialect) {
97
+ return text.replace(PATTERN, (matched, ...args) => rewriteMatch(matched, args, dialect));
98
+ }
99
+ var ROW_START = /[^\S\r\n]*\|/y;
100
+ var LINE_ENDING = /(\r\n|\r|\n)/;
101
+ var MARKER_CHARACTER = /[*_~\x60]/;
102
+ var PIPE = 124;
103
+ var BACKSLASH = 92;
104
+ var LF = 10;
105
+ var CR = 13;
106
+ function rowLocator(text) {
107
+ const rowStart = new RegExp(ROW_START);
108
+ let lineStart = 0;
109
+ let scanned = 0;
110
+ return (offset) => {
111
+ for (; scanned < offset; scanned += 1) {
112
+ const code = text.charCodeAt(scanned);
113
+ if (code === LF || code === CR) lineStart = scanned + 1;
114
+ }
115
+ rowStart.lastIndex = lineStart;
116
+ return rowStart.test(text);
117
+ };
118
+ }
119
+ function rewriteTableRow(row, dialect) {
120
+ let out = "";
121
+ let from = 0;
122
+ let backslashes = 0;
123
+ for (let i = 0; i < row.length; i += 1) {
124
+ const code = row.charCodeAt(i);
125
+ if (code === BACKSLASH) {
126
+ backslashes += 1;
127
+ continue;
128
+ }
129
+ if (code === PIPE && backslashes % 2 === 0) {
130
+ out += `${replaceMarkers(row.slice(from, i), dialect)}|`;
131
+ from = i + 1;
132
+ }
133
+ backslashes = 0;
134
+ }
135
+ return out + replaceMarkers(row.slice(from), dialect);
136
+ }
137
+ function rewriteLine(line, dialect, rowStart) {
138
+ rowStart.lastIndex = 0;
139
+ if (!rowStart.test(line)) return replaceMarkers(line, dialect);
140
+ return MARKER_CHARACTER.test(line) ? rewriteTableRow(line, dialect) : line;
141
+ }
142
+ function rewriteByLine(text, dialect) {
143
+ const rowStart = new RegExp(ROW_START);
144
+ return text.split(LINE_ENDING).map((piece) => rewriteLine(piece, dialect, rowStart)).join("");
145
+ }
146
+ function rewriteMarkers(text, dialect) {
147
+ const regions = scanFences(text);
148
+ if (regions.length === 0) return rewriteUnfenced(text, dialect);
149
+ let out = "";
150
+ let from = 0;
151
+ for (const region of regions) {
152
+ out += rewriteUnfenced(text.slice(from, region.start), dialect) + text.slice(region.start, region.end);
153
+ from = region.end;
154
+ }
155
+ return out + rewriteUnfenced(text.slice(from), dialect);
156
+ }
157
+ function rewriteUnfenced(text, dialect) {
158
+ const onTableRow = rowLocator(text);
159
+ let crossesRowPipe = false;
160
+ const rewritten = text.replace(PATTERN, (matched, ...args) => {
161
+ if (!crossesRowPipe && matched.includes("|")) {
162
+ crossesRowPipe = onTableRow(args.at(-3));
163
+ }
164
+ return rewriteMatch(matched, args, dialect);
165
+ });
166
+ return crossesRowPipe ? rewriteByLine(text, dialect) : rewritten;
167
+ }
168
+
169
+ // src/text/channel-rendering.ts
170
+ var SLACK = { bold: "*", italic: "_", strike: "~", code: "`" };
171
+ var STRIP = {};
172
+ var identity = (text) => text;
173
+ var translateWith = (dialect) => (text) => rewriteMarkers(text, dialect);
174
+ var RENDERINGS = {
175
+ whatsapp: { format: "plain", translate: translateWith(DIALECTS.whatsapp) },
176
+ slack: { format: "markdown", translate: translateWith(SLACK) },
177
+ discord: { format: "markdown", translate: identity },
178
+ mattermost: { format: "markdown", translate: identity },
179
+ teams: { format: "markdown", translate: identity },
180
+ signal: { format: "markdown", translate: identity },
181
+ line: { format: "plain", translate: translateWith(DIALECTS.line) },
182
+ sms: { format: "plain", translate: translateWith(DIALECTS.sms) },
183
+ telegram: { format: "plain", translate: translateWith(STRIP) },
184
+ matrix: { format: "plain", translate: translateWith(STRIP) },
185
+ email: { format: "plain", translate: translateWith(STRIP) },
186
+ imessage: { format: "plain", translate: translateWith(STRIP) },
187
+ google_chat: { format: "plain", translate: translateWith(STRIP) },
188
+ irc: { format: "plain", translate: translateWith(STRIP) },
189
+ nextcloud_talk: { format: "markdown", translate: identity },
190
+ nostr: { format: "plain", translate: translateWith(STRIP) },
191
+ feishu_lark: { format: "plain", translate: translateWith(STRIP) },
192
+ synology_chat: { format: "plain", translate: translateWith(STRIP) },
193
+ tlon_urbit: { format: "plain", translate: translateWith(STRIP) },
194
+ twitch: { format: "plain", translate: translateWith(STRIP) },
195
+ buzz: { format: "plain", translate: translateWith(STRIP) },
196
+ clickclack: { format: "plain", translate: translateWith(STRIP) },
197
+ zalo_personal: { format: "plain", translate: translateWith(STRIP) },
198
+ zalo: { format: "plain", translate: translateWith(STRIP) },
199
+ wechat: { format: "plain", translate: translateWith(STRIP) },
200
+ wecom: { format: "plain", translate: translateWith(STRIP) },
201
+ yuanbao: { format: "plain", translate: translateWith(STRIP) },
202
+ raft: { format: "plain", translate: translateWith(STRIP) }
203
+ };
204
+ function channelRendering(platform) {
205
+ const rendering = Object.hasOwn(RENDERINGS, platform) ? RENDERINGS[platform] : void 0;
206
+ if (rendering === void 0) {
207
+ throw new RangeError(
208
+ `channelRendering: unknown platform "${String(platform)}"; expected one of ${Object.keys(RENDERINGS).join(", ")}`
209
+ );
210
+ }
211
+ return rendering;
212
+ }
213
+
3
214
  // src/adapter/base.ts
4
215
  var BasePlatformAdapter = class {
5
216
  /**
@@ -26,6 +237,56 @@ var BasePlatformAdapter = class {
26
237
  }
27
238
  return "ok";
28
239
  }
240
+ /** The handler {@link subscribe} holds; `undefined` while nobody is subscribed. */
241
+ subscribedHandler;
242
+ /** The body of {@link onInbound}: replace the handler, and unsubscribe only if it is still the one held. */
243
+ subscribe(handler) {
244
+ this.subscribedHandler = handler;
245
+ return () => {
246
+ if (this.subscribedHandler === handler) this.subscribedHandler = void 0;
247
+ };
248
+ }
249
+ /** The body of {@link deliver} for an adapter that subscribed through {@link subscribe}. */
250
+ deliverInbound(event) {
251
+ return this.runHandler(this.subscribedHandler, event);
252
+ }
253
+ /**
254
+ * Dispatch a webhook event once: `duplicate` when `seen` holds its id, `no_handler` when nobody
255
+ * subscribed (the id is then NOT remembered, so a redelivery is handled), otherwise remember the
256
+ * id and run the handler. A handler's throw is also logged under `label`.
257
+ */
258
+ async dispatchOnce(seen, event, label) {
259
+ if (seen.has(event.id)) return "duplicate";
260
+ if (this.subscribedHandler === void 0) return "no_handler";
261
+ seen.add(event.id);
262
+ const outcome = await this.runHandler(this.subscribedHandler, event);
263
+ if (outcome === "handler_threw") process.stderr.write(`[${label}] handler threw
264
+ `);
265
+ return outcome;
266
+ }
267
+ /** `out.text`, translated to the platform's markup when `out.format` is `markdown`. */
268
+ outboundText(out) {
269
+ return out.format === "markdown" ? channelRendering(this.platform).translate(out.text) : out.text;
270
+ }
271
+ /**
272
+ * The local checks every text-only `sendMessage` makes before a request, in this order:
273
+ * `empty_text`, `not_connected`, then `invalid_channel` when `channel.valid` rejects the id.
274
+ * Returns the refusal, or `undefined` when the message may be sent.
275
+ */
276
+ refuseUnsendable(out, check) {
277
+ const refuse = (code, message) => ({
278
+ ok: false,
279
+ error: { code, message }
280
+ });
281
+ if (out.text.length === 0) return refuse("empty_text", "outbound text is empty");
282
+ if (!check.connected) {
283
+ return refuse("not_connected", `${check.className}.connect() has not succeeded`);
284
+ }
285
+ if (check.channel !== void 0 && !check.channel.valid(out.channel.id)) {
286
+ return refuse("invalid_channel", check.channel.message);
287
+ }
288
+ return void 0;
289
+ }
29
290
  /**
30
291
  * Whether {@link editMessage} can replace the text of a message this adapter sent.
31
292
  *
@@ -34,6 +295,14 @@ var BasePlatformAdapter = class {
34
295
  * edit-capable adapter can override it with `true`.
35
296
  */
36
297
  supportsEdit = false;
298
+ /**
299
+ * Whether {@link sendMessage} can send the images of `out.attachments` (B-674).
300
+ *
301
+ * Read it before attaching: on `false`, the adapter refuses a non-empty list with
302
+ * `attachments_unsupported`. Set at construction, never changed by `connect()`. Annotated as
303
+ * `boolean` so that an adapter that sends images can override it with `true`.
304
+ */
305
+ supportsAttachments = false;
37
306
  /**
38
307
  * Replace the text of a message this adapter sent, keeping its id.
39
308
  *
@@ -55,6 +324,25 @@ var BasePlatformAdapter = class {
55
324
  }
56
325
  };
57
326
  }
327
+ /**
328
+ * React to an inbound message with an emoji (for example 👀 as an acknowledgement).
329
+ *
330
+ * Returns `{ ok: true, messageId }` on success and a `SendResult` error otherwise; it never
331
+ * throws on platform errors. `channelId` is the channel the message is in and `messageId` the
332
+ * id the inbound event carried.
333
+ *
334
+ * Default: resolves `{ ok: false, error: { code: "react_unsupported" } }` and makes no
335
+ * platform call.
336
+ */
337
+ async react(_channelId, _messageId, _emoji) {
338
+ return {
339
+ ok: false,
340
+ error: {
341
+ code: "react_unsupported",
342
+ message: `${this.platform} adapter cannot react to a message`
343
+ }
344
+ };
345
+ }
58
346
  /** Lifecycle: emit a typing indicator. Default: noop. */
59
347
  async startTyping(_channelId) {
60
348
  }
@@ -63,6 +351,184 @@ var BasePlatformAdapter = class {
63
351
  }
64
352
  };
65
353
 
354
+ // src/text/seen-ids.ts
355
+ var DEFAULT_LIMIT = 1e3;
356
+ var SeenIds = class {
357
+ /** @param limit the most ids held at once; the oldest is forgotten when one more arrives */
358
+ constructor(limit = DEFAULT_LIMIT) {
359
+ this.limit = limit;
360
+ }
361
+ limit;
362
+ ids = /* @__PURE__ */ new Set();
363
+ /**
364
+ * Record `id`.
365
+ *
366
+ * @returns `true` when the id was new, `false` when it was already held
367
+ */
368
+ add(id) {
369
+ if (this.ids.has(id)) return false;
370
+ this.ids.add(id);
371
+ if (this.ids.size > this.limit) {
372
+ const oldest = this.ids.values().next().value;
373
+ if (oldest !== void 0) this.ids.delete(oldest);
374
+ }
375
+ return true;
376
+ }
377
+ /** Whether `id` is held. */
378
+ has(id) {
379
+ return this.ids.has(id);
380
+ }
381
+ /** How many ids are held. */
382
+ get size() {
383
+ return this.ids.size;
384
+ }
385
+ };
386
+
387
+ // src/adapter/weixin-xml.ts
388
+ function parseFlatXml(xml) {
389
+ const out = {};
390
+ const tag = /<([A-Za-z][A-Za-z0-9]*)>(?:<!\[CDATA\[([\s\S]*?)\]\]>|([^<]*))<\/\1>/g;
391
+ for (const m of xml.matchAll(tag)) {
392
+ const name = m[1];
393
+ if (name !== void 0 && name !== "xml") out[name] = m[2] ?? decodeEntities(m[3] ?? "");
394
+ }
395
+ return out;
396
+ }
397
+ function decodeEntities(s) {
398
+ return s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&");
399
+ }
400
+
401
+ // src/adapter/weixin-base.ts
402
+ var REQUEST_TIMEOUT_MS = 3e4;
403
+ var TOKEN_MARGIN_MS = 6e4;
404
+ var defaultFetch = async (url, init) => {
405
+ const res = await fetch(url, { ...init, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
406
+ return { status: res.status, text: () => res.text() };
407
+ };
408
+ function weixinMessageOf(err) {
409
+ return err instanceof Error ? err.message : String(err);
410
+ }
411
+ function weixinAck(reason) {
412
+ return { status: 200, body: "success", reason };
413
+ }
414
+ var WeixinAdapterBase = class extends BasePlatformAdapter {
415
+ cfg;
416
+ doFetch;
417
+ connected = false;
418
+ accessToken;
419
+ seen = new SeenIds();
420
+ constructor(cfg) {
421
+ super();
422
+ this.cfg = cfg;
423
+ this.doFetch = cfg.fetch ?? defaultFetch;
424
+ }
425
+ async connect() {
426
+ if (this.connected) return true;
427
+ try {
428
+ await this.token(true);
429
+ this.connected = true;
430
+ return true;
431
+ } catch (err) {
432
+ process.stderr.write(`[${this.cfg.label}] connect failed: ${weixinMessageOf(err)}
433
+ `);
434
+ return false;
435
+ }
436
+ }
437
+ async disconnect() {
438
+ this.connected = false;
439
+ this.accessToken = void 0;
440
+ }
441
+ /** Send text only; a subclass's `sendMessage` refuses attachments first, then calls this. */
442
+ async sendText(out) {
443
+ if (out.text.length === 0) {
444
+ return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
445
+ }
446
+ if (!this.connected) {
447
+ return {
448
+ ok: false,
449
+ error: {
450
+ code: "not_connected",
451
+ message: `${this.cfg.className}.connect() has not succeeded`
452
+ }
453
+ };
454
+ }
455
+ if (out.channel.id === "") {
456
+ return {
457
+ ok: false,
458
+ error: { code: "invalid_channel", message: `channel.id must be ${this.cfg.userNoun}` }
459
+ };
460
+ }
461
+ return this.sendParts(out);
462
+ }
463
+ async sendParts(out) {
464
+ const failed = `${this.platform}_send_failed`;
465
+ try {
466
+ for (const content of this.split(this.outboundText(out))) {
467
+ const token = await this.token(false);
468
+ const req = this.sendRequest(token, out.channel.id, content);
469
+ const body = await this.call("POST", req.path, req.payload);
470
+ if (body.errcode !== 0) {
471
+ return {
472
+ ok: false,
473
+ error: {
474
+ code: failed,
475
+ message: `${this.cfg.brand} error ${String(body.errcode)}: ${String(body.errmsg)}`
476
+ }
477
+ };
478
+ }
479
+ }
480
+ } catch (err) {
481
+ return { ok: false, error: { code: failed, message: weixinMessageOf(err) } };
482
+ }
483
+ return { ok: true, messageId: "" };
484
+ }
485
+ onInbound(handler) {
486
+ return this.subscribe(handler);
487
+ }
488
+ /** Deliver an event that arrived out of band, through `runHandler`. */
489
+ async deliver(event) {
490
+ return this.deliverInbound(event);
491
+ }
492
+ /** Turn a plain (decrypted) XML body into one event, dispatch it and answer the webhook. */
493
+ async handleMessage(xml) {
494
+ const event = this.toEvent(parseFlatXml(xml));
495
+ if (event === "skip") return weixinAck("not a text message");
496
+ if (event === void 0) return { status: 400, body: "", reason: "incomplete" };
497
+ const outcome = await this.dispatchOnce(this.seen, event, this.cfg.label);
498
+ if (outcome === "no_handler") return { status: 503, body: "", reason: "no handler subscribed" };
499
+ return weixinAck(outcome);
500
+ }
501
+ async token(force) {
502
+ const cached = this.accessToken;
503
+ if (!force && cached !== void 0 && cached.expiresAt - TOKEN_MARGIN_MS > Date.now()) {
504
+ return cached.value;
505
+ }
506
+ const body = await this.call("GET", this.tokenPath());
507
+ if (body.errcode !== void 0 && body.errcode !== 0) {
508
+ throw new Error(`token answered error ${String(body.errcode)}: ${String(body.errmsg)}`);
509
+ }
510
+ if (!body.access_token) throw new Error("token answer has no access_token");
511
+ this.accessToken = {
512
+ value: body.access_token,
513
+ expiresAt: Date.now() + (body.expires_in ?? 7200) * 1e3
514
+ };
515
+ return body.access_token;
516
+ }
517
+ async call(method, path, payload) {
518
+ const res = await this.doFetch((this.cfg.apiBase ?? this.cfg.defaultBase) + path, {
519
+ method,
520
+ headers: { "Content-Type": "application/json" },
521
+ ...payload === void 0 ? {} : { body: JSON.stringify(payload) }
522
+ });
523
+ const text = await res.text();
524
+ try {
525
+ return JSON.parse(text);
526
+ } catch {
527
+ throw new Error(`${this.cfg.brand} answered HTTP ${res.status} with a non-JSON body`);
528
+ }
529
+ }
530
+ };
531
+
66
532
  // src/errors/config-error.ts
67
533
  var GatewayConfigurationError = class extends Error {
68
534
  name = "GatewayConfigurationError";
@@ -132,6 +598,7 @@ function createAdapter(entry, values) {
132
598
  }
133
599
  function createChannels(entries) {
134
600
  const adapters = [];
601
+ const channels = [];
135
602
  const rejected = [];
136
603
  const builtPlatforms = /* @__PURE__ */ new Set();
137
604
  for (const entry of entries) {
@@ -142,9 +609,28 @@ function createChannels(entries) {
142
609
  continue;
143
610
  }
144
611
  adapters.push(outcome.adapter);
612
+ channels.push({ descriptor: entry.descriptor, adapter: outcome.adapter });
145
613
  builtPlatforms.add(entry.descriptor.platform);
146
614
  }
147
- return { adapters, rejected };
615
+ return { adapters, channels, rejected };
616
+ }
617
+
618
+ // src/delivery/attachments.ts
619
+ function attachmentsOf(attachments) {
620
+ return attachments != null && attachments.length !== 0 ? { attachments } : {};
621
+ }
622
+ function refuseUnsupportedAttachments(adapter, outbound) {
623
+ const { attachments } = outbound;
624
+ if (adapter.supportsAttachments || attachments == null || attachments.length === 0) {
625
+ return void 0;
626
+ }
627
+ return {
628
+ ok: false,
629
+ error: {
630
+ code: "attachments_unsupported",
631
+ message: `${adapter.platform} adapter cannot send attachments`
632
+ }
633
+ };
148
634
  }
149
635
 
150
636
  // src/delivery/router.ts
@@ -161,12 +647,14 @@ var DeliveryRouter = class {
161
647
  error: { code: "no_adapter", message: `no adapter for platform "${req.platform}"` }
162
648
  };
163
649
  }
164
- return adapter.sendMessage({
650
+ const outbound = {
165
651
  channel: req.channel,
166
652
  text: req.text,
167
653
  ...req.format !== void 0 ? { format: req.format } : {},
168
- ...req.replyTo !== void 0 ? { replyTo: req.replyTo } : {}
169
- });
654
+ ...req.replyTo !== void 0 ? { replyTo: req.replyTo } : {},
655
+ ...attachmentsOf(req.attachments)
656
+ };
657
+ return refuseUnsupportedAttachments(adapter, outbound) ?? adapter.sendMessage(outbound);
170
658
  }
171
659
  };
172
660
 
@@ -211,9 +699,62 @@ var CREDENTIAL_SHAPES = {
211
699
  field: "gateway-teams `clientSecret`",
212
700
  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,
213
701
  alsoMatches: "an Entra-style secret is the only common value with a tilde in that position"
702
+ },
703
+ {
704
+ field: "gateway-nostr `secretKey` (nsec1 form)",
705
+ pattern: /(?<![a-z0-9])nsec1[02-9ac-hj-np-z]{58}(?![a-z0-9])/g,
706
+ alsoMatches: "nothing plausible \u2014 `nsec1` is NIP-19's prefix for a secret key"
214
707
  }
215
708
  ],
216
709
  uncovered: [
710
+ {
711
+ field: "gateway-buzz `token`",
712
+ why: "a Buzz bot token with no fixed shape this package could confirm. It travels only in Authorization headers, which the adapter never logs."
713
+ },
714
+ {
715
+ field: "gateway-clickclack `token`",
716
+ 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."
717
+ },
718
+ {
719
+ field: "gateway-zalo `accessToken`, `oaSecretKey`",
720
+ why: "a Zalo Official Account access token and OA secret key: opaque strings with no prefix or fixed shape to recognise. The token travels only in an `access_token` header and the key only into the signature check, and the adapter never logs either."
721
+ },
722
+ {
723
+ field: "gateway-wechat `appSecret`, `token`",
724
+ why: "a WeChat Official Account AppSecret (32 hex characters, indistinguishable from any other hex string) and the server-URL verification token (a string the operator chooses). The secret travels only to the access-token endpoint and the token only into the signature check; the adapter never logs either."
725
+ },
726
+ {
727
+ field: "gateway-wecom `corpSecret`, `token`, `encodingAesKey`",
728
+ why: "a WeCom application Secret (43 URL-safe base64 characters, indistinguishable from other opaque strings), the callback Token (a string the operator chooses) and the EncodingAESKey (43 base64 characters). The secret travels only to the access-token endpoint, the token into the signature check and the key into the decryption; the adapter never logs any of them."
729
+ },
730
+ {
731
+ field: "gateway-yuanbao `appSecret`, `callbackSecret`",
732
+ why: "a Yuanbao bot AppSecret and the callback signing secret, both opaque strings with no prefix or fixed shape. The app secret travels only to the access-token endpoint and the callback secret only into the signature check; the adapter never logs either."
733
+ },
734
+ {
735
+ field: "gateway-zalo-personal `credentials`",
736
+ 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."
737
+ },
738
+ {
739
+ field: "gateway-twitch `accessToken`",
740
+ 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."
741
+ },
742
+ {
743
+ field: "gateway-tlon-urbit `code`",
744
+ 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."
745
+ },
746
+ {
747
+ field: "gateway-synology-chat `botToken` and `incomingUrl`",
748
+ 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."
749
+ },
750
+ {
751
+ field: "gateway-feishu-lark `appSecret`",
752
+ 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."
753
+ },
754
+ {
755
+ field: "gateway-nostr `secretKey` (64-hex form)",
756
+ 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."
757
+ },
217
758
  {
218
759
  field: "gateway-sms `authToken` (Twilio), gateway-line `channelSecret`",
219
760
  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."
@@ -360,12 +901,36 @@ var HookExecutor = class {
360
901
 
361
902
  // src/runner/gateway-runner.ts
362
903
  var DEFAULT_DRAIN_MS = 1e4;
904
+ var TYPING_RENEW_MS = 4e3;
905
+ function keepTyping(adapter, channelId) {
906
+ const swallow = (p) => p.catch(() => void 0);
907
+ const start = () => swallow(Promise.resolve().then(() => adapter.startTyping(channelId)));
908
+ void start();
909
+ const timer = setInterval(() => void start(), TYPING_RENEW_MS);
910
+ timer.unref();
911
+ return async () => {
912
+ clearInterval(timer);
913
+ await swallow(Promise.resolve().then(() => adapter.stopTyping(channelId)));
914
+ };
915
+ }
363
916
  var DEFAULT_COMMAND_PREFIXES = ["/"];
364
917
  function connectFailureReason(outcome) {
365
918
  if (outcome.status === "fulfilled") return "connect returned false";
366
919
  const message = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
367
920
  return redactSecrets(message);
368
921
  }
922
+ function isTerminalConnectError(err) {
923
+ if (typeof err !== "object" || err === null) return false;
924
+ const e = err;
925
+ for (const key of ["status", "statusCode", "httpStatus"]) {
926
+ if (e[key] === 401 || e[key] === 403) return true;
927
+ }
928
+ if (e.errcode === "M_UNKNOWN_TOKEN" || e.errcode === "M_FORBIDDEN") return true;
929
+ const message = typeof e.message === "string" ? e.message : "";
930
+ return /\b(?:http|status(?: code)?)\s*:?\s*(?:401|403)\b|unauthori[sz]ed|forbidden/i.test(
931
+ message
932
+ );
933
+ }
369
934
  async function releaseAdapters(adapters, during) {
370
935
  await Promise.all(
371
936
  adapters.map(async (a) => {
@@ -384,11 +949,9 @@ async function releaseAdapters(adapters, during) {
384
949
  var GatewayRunner = class {
385
950
  constructor(opts) {
386
951
  this.opts = opts;
387
- for (const a of opts.adapters) this.adaptersByPlatform.set(a.platform, a);
388
952
  this.hookExecutor = new HookExecutor(opts.hooks ?? []);
389
953
  }
390
954
  opts;
391
- adaptersByPlatform = /* @__PURE__ */ new Map();
392
955
  hookExecutor;
393
956
  inflight = /* @__PURE__ */ new Set();
394
957
  unsubs = [];
@@ -398,6 +961,7 @@ var GatewayRunner = class {
398
961
  /** The start that has not settled yet, shared by every overlapping `start()` call. */
399
962
  startInFlight;
400
963
  stopped = false;
964
+ retryTimers = /* @__PURE__ */ new Set();
401
965
  /**
402
966
  * Register a slash command. Match rule (EC-A): text === "/" + name
403
967
  * OR text.startsWith("/" + name + " ") OR text.startsWith("/" + name + "@").
@@ -461,8 +1025,76 @@ var GatewayRunner = class {
461
1025
  connected: result.connected.map((a) => a.platform),
462
1026
  failed: result.failed
463
1027
  };
1028
+ for (const adapter of result.retryable) this.scheduleReconnect(adapter, 1);
464
1029
  return this.startResult;
465
1030
  }
1031
+ /** Retry one adapter after its backoff delay; reschedules itself until it connects or gives up. */
1032
+ scheduleReconnect(adapter, attempt) {
1033
+ const policy = this.opts.reconnect;
1034
+ if (policy === void 0 || this.stopped) return;
1035
+ if (policy.maxAttempts !== void 0 && attempt > policy.maxAttempts) {
1036
+ process.stderr.write(
1037
+ `[gateway] adapter "${adapter.platform}" gave up reconnecting after ${policy.maxAttempts} attempts
1038
+ `
1039
+ );
1040
+ return;
1041
+ }
1042
+ const delay = Math.min(
1043
+ (policy.initialDelayMs ?? 1e3) * (policy.factor ?? 2) ** (attempt - 1),
1044
+ policy.maxDelayMs ?? 6e4
1045
+ );
1046
+ const timer = setTimeout(() => {
1047
+ this.retryTimers.delete(timer);
1048
+ void this.reconnectOnce(adapter, attempt);
1049
+ }, delay);
1050
+ timer.unref();
1051
+ this.retryTimers.add(timer);
1052
+ process.stderr.write(
1053
+ `[gateway] adapter "${adapter.platform}" reconnect attempt ${attempt} in ${delay}ms
1054
+ `
1055
+ );
1056
+ }
1057
+ async reconnectOnce(adapter, attempt) {
1058
+ if (this.stopped) return;
1059
+ try {
1060
+ if (await adapter.connect()) {
1061
+ if (this.stopped) {
1062
+ await releaseAdapters([adapter], "releasing a reconnect that stop() overtook");
1063
+ return;
1064
+ }
1065
+ this.wireInbound([adapter]);
1066
+ const prev = this.startResult ?? { connected: [], failed: [] };
1067
+ this.startResult = {
1068
+ connected: [...prev.connected, adapter.platform],
1069
+ failed: prev.failed.filter((f) => f.platform !== adapter.platform)
1070
+ };
1071
+ process.stderr.write(
1072
+ `[gateway] adapter "${adapter.platform}" connected on attempt ${attempt}
1073
+ `
1074
+ );
1075
+ return;
1076
+ }
1077
+ process.stderr.write(
1078
+ `[gateway] adapter "${adapter.platform}" refused to connect; not retrying
1079
+ `
1080
+ );
1081
+ return;
1082
+ } catch (err) {
1083
+ const reason = connectFailureReason({ status: "rejected", reason: err });
1084
+ if (isTerminalConnectError(err)) {
1085
+ process.stderr.write(
1086
+ `[gateway] adapter "${adapter.platform}" credentials rejected: ${reason}; not retrying
1087
+ `
1088
+ );
1089
+ return;
1090
+ }
1091
+ process.stderr.write(
1092
+ `[gateway] adapter "${adapter.platform}" reconnect attempt ${attempt} failed: ${reason}
1093
+ `
1094
+ );
1095
+ }
1096
+ this.scheduleReconnect(adapter, attempt + 1);
1097
+ }
466
1098
  /**
467
1099
  * All or nothing: when any connect fails, disconnect the adapters that did connect, then rethrow
468
1100
  * the first failure. Every connect settles before the rollback: rolling back while one is still
@@ -492,7 +1124,7 @@ var GatewayRunner = class {
492
1124
  await releaseAdapters(connected, "rolling back a failed start");
493
1125
  throw failures[0];
494
1126
  }
495
- return { connected: [...adapters], failed: [] };
1127
+ return { connected: [...adapters], failed: [], retryable: [] };
496
1128
  }
497
1129
  /**
498
1130
  * Connect every adapter and keep the ones that connected. The `async` wrapper turns a
@@ -504,17 +1136,23 @@ var GatewayRunner = class {
504
1136
  const settled = await Promise.allSettled(adapters.map(async (a) => a.connect()));
505
1137
  const connected = [];
506
1138
  const failed = [];
1139
+ const retryable = [];
507
1140
  settled.forEach((outcome, i) => {
508
1141
  const adapter = adapters[i];
509
1142
  if (outcome.status === "fulfilled" && outcome.value) connected.push(adapter);
510
- else failed.push({ platform: adapter.platform, reason: connectFailureReason(outcome) });
1143
+ else {
1144
+ failed.push({ platform: adapter.platform, reason: connectFailureReason(outcome) });
1145
+ if (outcome.status === "rejected" && !isTerminalConnectError(outcome.reason)) {
1146
+ retryable.push(adapter);
1147
+ }
1148
+ }
511
1149
  });
512
- return { connected, failed };
1150
+ return { connected, failed, retryable };
513
1151
  }
514
1152
  wireInbound(adapters) {
515
1153
  for (const a of adapters) {
516
1154
  const unsub = a.onInbound(async (event) => {
517
- const p = this.dispatch(event);
1155
+ const p = this.dispatch(event, a);
518
1156
  this.inflight.add(p);
519
1157
  p.finally(() => this.inflight.delete(p));
520
1158
  });
@@ -540,6 +1178,8 @@ var GatewayRunner = class {
540
1178
  }
541
1179
  }
542
1180
  this.unsubs.length = 0;
1181
+ for (const t of this.retryTimers) clearTimeout(t);
1182
+ this.retryTimers.clear();
543
1183
  const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;
544
1184
  if (this.inflight.size > 0) {
545
1185
  let timer;
@@ -554,7 +1194,7 @@ var GatewayRunner = class {
554
1194
  if (timer !== void 0) clearTimeout(timer);
555
1195
  }
556
1196
  }
557
- await releaseAdapters([...this.adaptersByPlatform.values()], "stopping the runner");
1197
+ await releaseAdapters([...new Set(this.opts.adapters)], "stopping the runner");
558
1198
  }
559
1199
  /**
560
1200
  * @internal Test seam, following `EmailAdapter._threadStoreSize`. The drain set must SHRINK: a
@@ -566,24 +1206,32 @@ var GatewayRunner = class {
566
1206
  return this.inflight.size;
567
1207
  }
568
1208
  /** @internal */
569
- async dispatch(event) {
570
- const ctx = this.buildContext(event);
1209
+ async dispatch(event, adapter) {
1210
+ const ctx = this.buildContext(event, adapter);
571
1211
  const decision = await this.hookExecutor.firePreInbound({ event });
572
1212
  if (decision.block === true) {
573
1213
  if (decision.message !== void 0 && decision.message.length > 0) {
574
- await ctx.reply(decision.message).catch(() => void 0);
1214
+ await ctx.reply(decision.message).catch(async (err) => {
1215
+ const error = err;
1216
+ await this.hookExecutor.fireOnError({ event, error });
1217
+ process.stderr.write(`[gateway] auto-reply error: ${redactSecrets(error.message)}
1218
+ `);
1219
+ });
575
1220
  }
576
1221
  return;
577
1222
  }
578
1223
  const slashHandler = this.matchSlashCommand(event);
579
1224
  const handler = slashHandler ?? this.opts.handler;
580
1225
  const work = (async () => {
1226
+ const stopTyping = keepTyping(adapter, event.channel.id);
581
1227
  try {
582
1228
  await handler(event, ctx);
583
1229
  } catch (err) {
584
1230
  await this.hookExecutor.fireOnError({ event, error: err });
585
1231
  process.stderr.write(`[gateway] handler error: ${redactSecrets(err.message)}
586
1232
  `);
1233
+ } finally {
1234
+ await stopTyping();
587
1235
  }
588
1236
  })();
589
1237
  this.inflight.add(work);
@@ -616,13 +1264,14 @@ var GatewayRunner = class {
616
1264
  return void 0;
617
1265
  }
618
1266
  /** EC-G: per-event ctx whose reply routes to the matching adapter. */
619
- buildContext(event) {
1267
+ buildContext(event, adapter) {
620
1268
  return {
621
1269
  event,
622
- reply: async (text, opts) => this.deliver(event, {
1270
+ reply: async (text, opts) => this.deliver(event, adapter, {
623
1271
  channel: event.channel,
624
1272
  text,
625
- ...opts?.format !== void 0 ? { format: opts.format } : {}
1273
+ ...opts?.format !== void 0 ? { format: opts.format } : {},
1274
+ ...attachmentsOf(opts?.attachments)
626
1275
  })
627
1276
  };
628
1277
  }
@@ -634,6 +1283,10 @@ var GatewayRunner = class {
634
1283
  * adapter for the platform. An audit hook that counted only the deliveries
635
1284
  * which reached a transport would omit precisely the ones that went nowhere.
636
1285
  *
1286
+ * An outbound with attachments for an adapter that does not declare `supportsAttachments` is
1287
+ * refused here as `attachments_unsupported`, with no `sendMessage` call, so an adapter that
1288
+ * ignores the field cannot drop the image and report success (B-674).
1289
+ *
637
1290
  * `post_outbound` observes; it does not intercept. The adapter's `SendResult`
638
1291
  * is returned to the caller unchanged, and `HookExecutor` already contains a
639
1292
  * throwing hook, so a broken observer cannot turn a delivered reply into a
@@ -641,9 +1294,9 @@ var GatewayRunner = class {
641
1294
  *
642
1295
  * @internal
643
1296
  */
644
- async deliver(event, outbound) {
645
- const adapter = this.adaptersByPlatform.get(event.platform);
646
- const result = adapter === void 0 ? { ok: false, error: { code: "no_adapter", message: `no adapter for ${event.platform}` } } : await adapter.sendMessage(outbound);
1297
+ async deliver(event, adapter, outbound) {
1298
+ const target = adapter?.platform === event.platform ? adapter : void 0;
1299
+ const result = target === void 0 ? { ok: false, error: { code: "no_adapter", message: `no adapter for ${event.platform}` } } : refuseUnsupportedAttachments(target, outbound) ?? await target.sendMessage(outbound);
647
1300
  await this.hookExecutor.firePostOutbound({ event, outbound, result });
648
1301
  return result;
649
1302
  }
@@ -679,74 +1332,6 @@ var SessionRouter = class {
679
1332
  }
680
1333
  };
681
1334
 
682
- // src/text/dialect.ts
683
- var DIALECTS = {
684
- // WhatsApp emphasis is inline and single-character: *bold*, _italic_, ~strike~, ```mono```.
685
- whatsapp: { bold: "*", italic: "_", strike: "~", code: "```" },
686
- // LINE text messages carry no rich text at all — decoration is emoji-only. Markers are dropped.
687
- line: {},
688
- // SMS is plain text by definition of the medium.
689
- sms: {}
690
- };
691
- var PATTERN = /\*\*(?<bold>.+?)\*\*|~~(?<strike>.+?)~~|(?<![*\w])\*(?!\s)(?<italicStar>.+?)(?<!\s)\*(?!\*)|(?<![_\w])_(?!\s)(?<italicUnderscore>.+?)(?<!\s)_(?!\w)|`(?<code>.+?)`/gu;
692
- var GROUP_MARKERS = [
693
- ["bold", "bold"],
694
- ["strike", "strike"],
695
- ["italicStar", "italic"],
696
- ["italicUnderscore", "italic"],
697
- ["code", "code"]
698
- ];
699
- function toDialect(text, platform) {
700
- const dialect = DIALECTS[platform];
701
- if (dialect === void 0) return text;
702
- return rewriteMarkers(text, dialect);
703
- }
704
- function rewriteMarkers(text, dialect) {
705
- return text.replace(PATTERN, (matched, ...args) => {
706
- const groups = args.at(-1);
707
- if (groups === void 0) return matched;
708
- for (const [group, marker] of GROUP_MARKERS) {
709
- const content = groups[group];
710
- if (content === void 0) continue;
711
- const wrap = dialect[marker];
712
- return wrap === void 0 ? content : `${wrap}${content}${wrap}`;
713
- }
714
- return matched;
715
- });
716
- }
717
-
718
- // src/text/channel-rendering.ts
719
- var SLACK = { bold: "*", italic: "_", strike: "~", code: "`" };
720
- var STRIP = {};
721
- var identity = (text) => text;
722
- var translateWith = (dialect) => (text) => rewriteMarkers(text, dialect);
723
- var RENDERINGS = {
724
- whatsapp: { format: "plain", translate: translateWith(DIALECTS.whatsapp) },
725
- slack: { format: "markdown", translate: translateWith(SLACK) },
726
- discord: { format: "markdown", translate: identity },
727
- mattermost: { format: "markdown", translate: identity },
728
- teams: { format: "markdown", translate: identity },
729
- signal: { format: "markdown", translate: identity },
730
- line: { format: "plain", translate: translateWith(DIALECTS.line) },
731
- sms: { format: "plain", translate: translateWith(DIALECTS.sms) },
732
- telegram: { format: "plain", translate: translateWith(STRIP) },
733
- matrix: { format: "plain", translate: translateWith(STRIP) },
734
- email: { format: "plain", translate: translateWith(STRIP) },
735
- imessage: { format: "plain", translate: translateWith(STRIP) },
736
- google_chat: { format: "plain", translate: translateWith(STRIP) },
737
- irc: { format: "plain", translate: translateWith(STRIP) },
738
- nextcloud_talk: { format: "markdown", translate: identity }
739
- };
740
- function channelRendering(platform) {
741
- const rendering = Object.hasOwn(RENDERINGS, platform) ? RENDERINGS[platform] : void 0;
742
- if (rendering === void 0) {
743
- throw new RangeError(
744
- `channelRendering: unknown platform "${String(platform)}"; expected one of ${Object.keys(RENDERINGS).join(", ")}`
745
- );
746
- }
747
- return rendering;
748
- }
749
-
750
1335
  // src/text/chunk.ts
751
1336
  function searchBoundary(remaining, window, boundaries) {
752
1337
  let cut = window;
@@ -774,6 +1359,63 @@ function findCut(remaining, window, boundaries, lastResort, surrogateGuard) {
774
1359
  if (surrogateGuard) cut = guardSurrogate(remaining, cut);
775
1360
  return cut <= 0 ? window : cut;
776
1361
  }
1362
+ var isLineEnd = (ch) => ch === "\n" || ch === "\r";
1363
+ function startsTableRow(text, from) {
1364
+ let at = from;
1365
+ while (at < text.length && /^[^\S\r\n]$/.test(text[at] ?? "")) at += 1;
1366
+ return text[at] === "|";
1367
+ }
1368
+ function rowSafeCut(text, cut, window) {
1369
+ const start = tableRowStart(text, cut);
1370
+ if (start === void 0 || rowLength(text, start, cut, window) > window) return void 0;
1371
+ let end = start;
1372
+ while (end > 0 && isLineEnd(text[end - 1])) end -= 1;
1373
+ return end > 0 ? { end, start } : void 0;
1374
+ }
1375
+ function tableRowStart(text, cut) {
1376
+ if (cut >= text.length || isLineEnd(text[cut])) return void 0;
1377
+ let start = cut;
1378
+ while (start > 0 && !isLineEnd(text[start - 1])) start -= 1;
1379
+ return start > 0 && startsTableRow(text, start) ? start : void 0;
1380
+ }
1381
+ function rowLength(text, start, cut, window) {
1382
+ let rowEnd = cut;
1383
+ while (rowEnd < text.length && rowEnd - start <= window && !isLineEnd(text[rowEnd])) rowEnd += 1;
1384
+ return rowEnd - start;
1385
+ }
1386
+ function rowStep(remaining, cut, window) {
1387
+ const moved = rowSafeCut(remaining, cut, window);
1388
+ if (moved === void 0) return void 0;
1389
+ return { chunk: remaining.slice(0, moved.end), remaining: remaining.slice(moved.start) };
1390
+ }
1391
+ function stepBeforeFence(remaining, region) {
1392
+ let end = region.start;
1393
+ while (end > 0 && isLineEnd(remaining[end - 1])) end -= 1;
1394
+ if (end === 0) return void 0;
1395
+ return { chunk: remaining.slice(0, end), remaining: remaining.slice(region.start) };
1396
+ }
1397
+ function stepThroughFence(remaining, region, window, surrogateGuard) {
1398
+ const eol = openerEol(remaining, region);
1399
+ const room = window - region.closer.length - eol.length;
1400
+ if (room <= region.contentStart) return void 0;
1401
+ let at = remaining.lastIndexOf("\n", room);
1402
+ let rest = at + 1;
1403
+ if (at < region.contentStart) {
1404
+ at = surrogateGuard ? guardSurrogate(remaining, room) : room;
1405
+ rest = at;
1406
+ } else if (remaining[at - 1] === "\r") {
1407
+ at -= 1;
1408
+ }
1409
+ return {
1410
+ chunk: `${remaining.slice(0, at)}${eol}${region.closer}`,
1411
+ remaining: `${region.opener}${eol}${remaining.slice(rest)}`
1412
+ };
1413
+ }
1414
+ function fenceStep(remaining, cut, window, surrogateGuard) {
1415
+ const region = fenceAt(scanFences(remaining), cut);
1416
+ if (region === void 0) return void 0;
1417
+ return cut <= region.openerEnd ? stepBeforeFence(remaining, region) : stepThroughFence(remaining, region, window, surrogateGuard);
1418
+ }
777
1419
  function chunkText(text, options) {
778
1420
  const {
779
1421
  limit,
@@ -782,7 +1424,8 @@ function chunkText(text, options) {
782
1424
  lastResort = "window",
783
1425
  surrogateGuard = false,
784
1426
  stripLeading = /^\n+/,
785
- trimParts = false
1427
+ trimParts = false,
1428
+ keepTableRows = false
786
1429
  } = options;
787
1430
  assertPositiveInt("chunkText: limit", limit);
788
1431
  assertPositiveInt("chunkText: safeLimit", safeLimit);
@@ -794,11 +1437,16 @@ function chunkText(text, options) {
794
1437
  return finalize([text]);
795
1438
  }
796
1439
  const parts = [];
1440
+ const hasFence = scanFences(text).length > 0;
797
1441
  let remaining = text;
798
1442
  while (remaining.length > safeLimit) {
799
1443
  const cut = findCut(remaining, safeLimit, boundaries, lastResort, surrogateGuard);
800
- parts.push(remaining.slice(0, cut));
801
- remaining = remaining.slice(cut).replace(stripLeading, "");
1444
+ const step = (hasFence ? fenceStep(remaining, cut, safeLimit, surrogateGuard) : void 0) ?? (keepTableRows ? rowStep(remaining, cut, safeLimit) : void 0) ?? {
1445
+ chunk: remaining.slice(0, cut),
1446
+ remaining: remaining.slice(cut).replace(stripLeading, "")
1447
+ };
1448
+ parts.push(step.chunk);
1449
+ remaining = step.remaining;
802
1450
  }
803
1451
  if (remaining.length > 0) parts.push(remaining);
804
1452
  return finalize(parts);
@@ -809,6 +1457,8 @@ function chunkByGrapheme(text, options) {
809
1457
  assertPositiveInt("chunkByGrapheme: partLimit", partLimit);
810
1458
  if (text.length === 0) return [""];
811
1459
  if (text.length <= limit) return [text];
1460
+ const regions = scanFences(text);
1461
+ if (regions.length > 0) return chunkFencedByGrapheme(text, partLimit, regions);
812
1462
  const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
813
1463
  const parts = [];
814
1464
  let buf = "";
@@ -822,6 +1472,99 @@ function chunkByGrapheme(text, options) {
822
1472
  if (buf.length > 0) parts.push(buf);
823
1473
  return parts;
824
1474
  }
1475
+ function graphemeBoundaries(text) {
1476
+ const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
1477
+ const starts = Array.from(segmenter.segment(text), (s) => s.index);
1478
+ starts.push(text.length);
1479
+ return (pos, max) => {
1480
+ const after = starts.filter((b) => b > pos);
1481
+ const within = after.filter((b) => b <= max);
1482
+ return within.at(-1) ?? after[0] ?? text.length;
1483
+ };
1484
+ }
1485
+ function chunkFencedByGrapheme(text, partLimit, regions) {
1486
+ const boundaryUpTo = graphemeBoundaries(text);
1487
+ const parts = [];
1488
+ let pos = 0;
1489
+ let prefix = "";
1490
+ while (prefix.length + (text.length - pos) > partLimit) {
1491
+ const room = partLimit - prefix.length;
1492
+ const plain = boundaryUpTo(pos, pos + room);
1493
+ const region = fenceAt(regions, plain);
1494
+ const next = region === void 0 ? { cut: plain, suffix: "", reopen: "" } : fenceGraphemeCut(text, region, pos, plain, room, boundaryUpTo);
1495
+ parts.push(prefix + text.slice(pos, next.cut) + next.suffix);
1496
+ pos = next.cut;
1497
+ prefix = next.reopen;
1498
+ }
1499
+ parts.push(prefix + text.slice(pos));
1500
+ return parts;
1501
+ }
1502
+ function fenceGraphemeCut(text, region, pos, plain, room, boundaryUpTo) {
1503
+ const none = { cut: plain, suffix: "", reopen: "" };
1504
+ if (plain <= region.openerEnd) {
1505
+ return region.start > pos ? { ...none, cut: region.start } : none;
1506
+ }
1507
+ const eol = openerEol(text, region);
1508
+ const max = pos + room - region.closer.length - eol.length;
1509
+ const floor = Math.max(pos, region.contentStart);
1510
+ if (max <= floor) return none;
1511
+ let at = boundaryUpTo(pos, max);
1512
+ const nl = text.lastIndexOf("\n", at - 1);
1513
+ if (nl >= floor - 1 && nl + 1 > pos) at = nl + 1;
1514
+ if (at <= pos || at > max) return none;
1515
+ if (fenceAt([region], at) === void 0) return { ...none, cut: at };
1516
+ const closes = isLineEnd(text[at - 1]);
1517
+ return { cut: at, suffix: (closes ? "" : eol) + region.closer, reopen: region.opener + eol };
1518
+ }
1519
+
1520
+ // src/text/split-rows.ts
1521
+ var ROW_BLANK = /^[^\S\r\n]$/;
1522
+ function isLineEnd2(character) {
1523
+ return character === "\n" || character === "\r";
1524
+ }
1525
+ function startsTableRow2(text, from) {
1526
+ let at = from;
1527
+ while (at < text.length && ROW_BLANK.test(text[at] ?? "")) at += 1;
1528
+ return text[at] === "|";
1529
+ }
1530
+ function lineStartBefore(text, cut, partStart) {
1531
+ let at = cut;
1532
+ while (at > partStart && !isLineEnd2(text[at - 1])) at -= 1;
1533
+ return at;
1534
+ }
1535
+ function lineEndFrom(text, cut, bound) {
1536
+ let at = cut;
1537
+ while (at < text.length && at <= bound && !isLineEnd2(text[at])) at += 1;
1538
+ return at;
1539
+ }
1540
+ function rowSafeCut2(text, partStart, cut, partLimit) {
1541
+ const lineStart = lineStartBefore(text, cut, partStart);
1542
+ if (lineStart <= partStart || lineStart === cut) return cut;
1543
+ if (isLineEnd2(text[cut]) || !startsTableRow2(text, lineStart)) return cut;
1544
+ const lineEnd = lineEndFrom(text, cut, lineStart + partLimit);
1545
+ return lineEnd - lineStart <= partLimit ? lineStart : cut;
1546
+ }
1547
+ function graphemeCut(segments, start, partLimit) {
1548
+ const cut = start + partLimit;
1549
+ const segment = segments.containing(cut);
1550
+ if (segment === void 0 || segment.index >= cut) return cut;
1551
+ return segment.index > start ? segment.index : segment.index + segment.segment.length;
1552
+ }
1553
+ function splitKeepingRows(text, partLimit) {
1554
+ const segments = new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(text);
1555
+ const parts = [];
1556
+ let start = 0;
1557
+ while (text.length - start > partLimit) {
1558
+ const cut = rowSafeCut2(text, start, graphemeCut(segments, start, partLimit), partLimit);
1559
+ if (cut <= start) {
1560
+ throw new RangeError(`splitKeepingRows: no progress at offset ${start} of ${text.length}`);
1561
+ }
1562
+ parts.push(text.slice(start, cut));
1563
+ start = cut;
1564
+ }
1565
+ if (start < text.length) parts.push(text.slice(start));
1566
+ return parts;
1567
+ }
825
1568
 
826
1569
  // src/webhook/express-server.ts
827
1570
  async function loadPeer(load, onMissing) {
@@ -932,6 +1675,6 @@ function listenerLifecycle(opts) {
932
1675
  };
933
1676
  }
934
1677
 
935
- export { BasePlatformAdapter, CREDENTIAL_SHAPES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SessionRouter, channelRendering, chunkByGrapheme, chunkText, createChannels, defaultStrategy, listenerLifecycle, loadPeer, maskShapes, rawBodyCapture, redactSecrets, toDialect };
1678
+ export { BasePlatformAdapter, CREDENTIAL_SHAPES, DeliveryRouter, GatewayConfigurationError, GatewayLifecycleError, GatewayRunner, HookExecutor, SeenIds, SessionRouter, WeixinAdapterBase, channelRendering, chunkByGrapheme, chunkText, createChannels, defaultStrategy, listenerLifecycle, loadPeer, maskShapes, parseFlatXml, rawBodyCapture, redactSecrets, scanFences, splitKeepingRows, toDialect };
936
1679
  //# sourceMappingURL=index.js.map
937
1680
  //# sourceMappingURL=index.js.map