@theokit/gateway 0.12.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 +157 -0
- package/README.md +104 -15
- package/dist/index.cjs +437 -30
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +383 -86
- package/dist/index.d.ts +383 -86
- package/dist/index.js +435 -31
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -36,6 +36,14 @@ var BasePlatformAdapter = class {
|
|
|
36
36
|
* edit-capable adapter can override it with `true`.
|
|
37
37
|
*/
|
|
38
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;
|
|
39
47
|
/**
|
|
40
48
|
* Replace the text of a message this adapter sent, keeping its id.
|
|
41
49
|
*
|
|
@@ -134,6 +142,7 @@ function createAdapter(entry, values) {
|
|
|
134
142
|
}
|
|
135
143
|
function createChannels(entries) {
|
|
136
144
|
const adapters = [];
|
|
145
|
+
const channels = [];
|
|
137
146
|
const rejected = [];
|
|
138
147
|
const builtPlatforms = /* @__PURE__ */ new Set();
|
|
139
148
|
for (const entry of entries) {
|
|
@@ -144,9 +153,28 @@ function createChannels(entries) {
|
|
|
144
153
|
continue;
|
|
145
154
|
}
|
|
146
155
|
adapters.push(outcome.adapter);
|
|
156
|
+
channels.push({ descriptor: entry.descriptor, adapter: outcome.adapter });
|
|
147
157
|
builtPlatforms.add(entry.descriptor.platform);
|
|
148
158
|
}
|
|
149
|
-
return { adapters, rejected };
|
|
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;
|
|
170
|
+
}
|
|
171
|
+
return {
|
|
172
|
+
ok: false,
|
|
173
|
+
error: {
|
|
174
|
+
code: "attachments_unsupported",
|
|
175
|
+
message: `${adapter.platform} adapter cannot send attachments`
|
|
176
|
+
}
|
|
177
|
+
};
|
|
150
178
|
}
|
|
151
179
|
|
|
152
180
|
// src/delivery/router.ts
|
|
@@ -163,12 +191,14 @@ var DeliveryRouter = class {
|
|
|
163
191
|
error: { code: "no_adapter", message: `no adapter for platform "${req.platform}"` }
|
|
164
192
|
};
|
|
165
193
|
}
|
|
166
|
-
|
|
194
|
+
const outbound = {
|
|
167
195
|
channel: req.channel,
|
|
168
196
|
text: req.text,
|
|
169
197
|
...req.format !== void 0 ? { format: req.format } : {},
|
|
170
|
-
...req.replyTo !== void 0 ? { replyTo: req.replyTo } : {}
|
|
171
|
-
|
|
198
|
+
...req.replyTo !== void 0 ? { replyTo: req.replyTo } : {},
|
|
199
|
+
...attachmentsOf(req.attachments)
|
|
200
|
+
};
|
|
201
|
+
return refuseUnsupportedAttachments(adapter, outbound) ?? adapter.sendMessage(outbound);
|
|
172
202
|
}
|
|
173
203
|
};
|
|
174
204
|
|
|
@@ -213,9 +243,46 @@ var CREDENTIAL_SHAPES = {
|
|
|
213
243
|
field: "gateway-teams `clientSecret`",
|
|
214
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,
|
|
215
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"
|
|
216
251
|
}
|
|
217
252
|
],
|
|
218
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
|
+
},
|
|
219
286
|
{
|
|
220
287
|
field: "gateway-sms `authToken` (Twilio), gateway-line `channelSecret`",
|
|
221
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."
|
|
@@ -386,11 +453,9 @@ async function releaseAdapters(adapters, during) {
|
|
|
386
453
|
var GatewayRunner = class {
|
|
387
454
|
constructor(opts) {
|
|
388
455
|
this.opts = opts;
|
|
389
|
-
for (const a of opts.adapters) this.adaptersByPlatform.set(a.platform, a);
|
|
390
456
|
this.hookExecutor = new HookExecutor(opts.hooks ?? []);
|
|
391
457
|
}
|
|
392
458
|
opts;
|
|
393
|
-
adaptersByPlatform = /* @__PURE__ */ new Map();
|
|
394
459
|
hookExecutor;
|
|
395
460
|
inflight = /* @__PURE__ */ new Set();
|
|
396
461
|
unsubs = [];
|
|
@@ -516,7 +581,7 @@ var GatewayRunner = class {
|
|
|
516
581
|
wireInbound(adapters) {
|
|
517
582
|
for (const a of adapters) {
|
|
518
583
|
const unsub = a.onInbound(async (event) => {
|
|
519
|
-
const p = this.dispatch(event);
|
|
584
|
+
const p = this.dispatch(event, a);
|
|
520
585
|
this.inflight.add(p);
|
|
521
586
|
p.finally(() => this.inflight.delete(p));
|
|
522
587
|
});
|
|
@@ -556,7 +621,7 @@ var GatewayRunner = class {
|
|
|
556
621
|
if (timer !== void 0) clearTimeout(timer);
|
|
557
622
|
}
|
|
558
623
|
}
|
|
559
|
-
await releaseAdapters([...this.
|
|
624
|
+
await releaseAdapters([...new Set(this.opts.adapters)], "stopping the runner");
|
|
560
625
|
}
|
|
561
626
|
/**
|
|
562
627
|
* @internal Test seam, following `EmailAdapter._threadStoreSize`. The drain set must SHRINK: a
|
|
@@ -568,12 +633,17 @@ var GatewayRunner = class {
|
|
|
568
633
|
return this.inflight.size;
|
|
569
634
|
}
|
|
570
635
|
/** @internal */
|
|
571
|
-
async dispatch(event) {
|
|
572
|
-
const ctx = this.buildContext(event);
|
|
636
|
+
async dispatch(event, adapter) {
|
|
637
|
+
const ctx = this.buildContext(event, adapter);
|
|
573
638
|
const decision = await this.hookExecutor.firePreInbound({ event });
|
|
574
639
|
if (decision.block === true) {
|
|
575
640
|
if (decision.message !== void 0 && decision.message.length > 0) {
|
|
576
|
-
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
|
+
});
|
|
577
647
|
}
|
|
578
648
|
return;
|
|
579
649
|
}
|
|
@@ -618,13 +688,14 @@ var GatewayRunner = class {
|
|
|
618
688
|
return void 0;
|
|
619
689
|
}
|
|
620
690
|
/** EC-G: per-event ctx whose reply routes to the matching adapter. */
|
|
621
|
-
buildContext(event) {
|
|
691
|
+
buildContext(event, adapter) {
|
|
622
692
|
return {
|
|
623
693
|
event,
|
|
624
|
-
reply: async (text, opts) => this.deliver(event, {
|
|
694
|
+
reply: async (text, opts) => this.deliver(event, adapter, {
|
|
625
695
|
channel: event.channel,
|
|
626
696
|
text,
|
|
627
|
-
...opts?.format !== void 0 ? { format: opts.format } : {}
|
|
697
|
+
...opts?.format !== void 0 ? { format: opts.format } : {},
|
|
698
|
+
...attachmentsOf(opts?.attachments)
|
|
628
699
|
})
|
|
629
700
|
};
|
|
630
701
|
}
|
|
@@ -636,6 +707,10 @@ var GatewayRunner = class {
|
|
|
636
707
|
* adapter for the platform. An audit hook that counted only the deliveries
|
|
637
708
|
* which reached a transport would omit precisely the ones that went nowhere.
|
|
638
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
|
+
*
|
|
639
714
|
* `post_outbound` observes; it does not intercept. The adapter's `SendResult`
|
|
640
715
|
* is returned to the caller unchanged, and `HookExecutor` already contains a
|
|
641
716
|
* throwing hook, so a broken observer cannot turn a delivered reply into a
|
|
@@ -643,9 +718,9 @@ var GatewayRunner = class {
|
|
|
643
718
|
*
|
|
644
719
|
* @internal
|
|
645
720
|
*/
|
|
646
|
-
async deliver(event, outbound) {
|
|
647
|
-
const
|
|
648
|
-
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);
|
|
649
724
|
await this.hookExecutor.firePostOutbound({ event, outbound, result });
|
|
650
725
|
return result;
|
|
651
726
|
}
|
|
@@ -681,6 +756,64 @@ var SessionRouter = class {
|
|
|
681
756
|
}
|
|
682
757
|
};
|
|
683
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
|
+
|
|
684
817
|
// src/text/dialect.ts
|
|
685
818
|
var DIALECTS = {
|
|
686
819
|
// WhatsApp emphasis is inline and single-character: *bold*, _italic_, ~strike~, ```mono```.
|
|
@@ -703,18 +836,90 @@ function toDialect(text, platform) {
|
|
|
703
836
|
if (dialect === void 0) return text;
|
|
704
837
|
return rewriteMarkers(text, dialect);
|
|
705
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
|
+
}
|
|
706
902
|
function rewriteMarkers(text, dialect) {
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
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));
|
|
715
919
|
}
|
|
716
|
-
return matched;
|
|
920
|
+
return rewriteMatch(matched, args, dialect);
|
|
717
921
|
});
|
|
922
|
+
return crossesRowPipe ? rewriteByLine(text, dialect) : rewritten;
|
|
718
923
|
}
|
|
719
924
|
|
|
720
925
|
// src/text/channel-rendering.ts
|
|
@@ -737,7 +942,15 @@ var RENDERINGS = {
|
|
|
737
942
|
imessage: { format: "plain", translate: translateWith(STRIP) },
|
|
738
943
|
google_chat: { format: "plain", translate: translateWith(STRIP) },
|
|
739
944
|
irc: { format: "plain", translate: translateWith(STRIP) },
|
|
740
|
-
nextcloud_talk: { format: "markdown", translate: identity }
|
|
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) }
|
|
741
954
|
};
|
|
742
955
|
function channelRendering(platform) {
|
|
743
956
|
const rendering = Object.hasOwn(RENDERINGS, platform) ? RENDERINGS[platform] : void 0;
|
|
@@ -776,6 +989,63 @@ function findCut(remaining, window, boundaries, lastResort, surrogateGuard) {
|
|
|
776
989
|
if (surrogateGuard) cut = guardSurrogate(remaining, cut);
|
|
777
990
|
return cut <= 0 ? window : cut;
|
|
778
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
|
+
}
|
|
779
1049
|
function chunkText(text, options) {
|
|
780
1050
|
const {
|
|
781
1051
|
limit,
|
|
@@ -784,7 +1054,8 @@ function chunkText(text, options) {
|
|
|
784
1054
|
lastResort = "window",
|
|
785
1055
|
surrogateGuard = false,
|
|
786
1056
|
stripLeading = /^\n+/,
|
|
787
|
-
trimParts = false
|
|
1057
|
+
trimParts = false,
|
|
1058
|
+
keepTableRows = false
|
|
788
1059
|
} = options;
|
|
789
1060
|
assertPositiveInt("chunkText: limit", limit);
|
|
790
1061
|
assertPositiveInt("chunkText: safeLimit", safeLimit);
|
|
@@ -796,11 +1067,16 @@ function chunkText(text, options) {
|
|
|
796
1067
|
return finalize([text]);
|
|
797
1068
|
}
|
|
798
1069
|
const parts = [];
|
|
1070
|
+
const hasFence = scanFences(text).length > 0;
|
|
799
1071
|
let remaining = text;
|
|
800
1072
|
while (remaining.length > safeLimit) {
|
|
801
1073
|
const cut = findCut(remaining, safeLimit, boundaries, lastResort, surrogateGuard);
|
|
802
|
-
|
|
803
|
-
|
|
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;
|
|
804
1080
|
}
|
|
805
1081
|
if (remaining.length > 0) parts.push(remaining);
|
|
806
1082
|
return finalize(parts);
|
|
@@ -811,6 +1087,8 @@ function chunkByGrapheme(text, options) {
|
|
|
811
1087
|
assertPositiveInt("chunkByGrapheme: partLimit", partLimit);
|
|
812
1088
|
if (text.length === 0) return [""];
|
|
813
1089
|
if (text.length <= limit) return [text];
|
|
1090
|
+
const regions = scanFences(text);
|
|
1091
|
+
if (regions.length > 0) return chunkFencedByGrapheme(text, partLimit, regions);
|
|
814
1092
|
const segmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
|
|
815
1093
|
const parts = [];
|
|
816
1094
|
let buf = "";
|
|
@@ -824,6 +1102,132 @@ function chunkByGrapheme(text, options) {
|
|
|
824
1102
|
if (buf.length > 0) parts.push(buf);
|
|
825
1103
|
return parts;
|
|
826
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
|
+
}
|
|
827
1231
|
|
|
828
1232
|
// src/webhook/express-server.ts
|
|
829
1233
|
async function loadPeer(load, onMissing) {
|
|
@@ -941,6 +1345,7 @@ exports.GatewayConfigurationError = GatewayConfigurationError;
|
|
|
941
1345
|
exports.GatewayLifecycleError = GatewayLifecycleError;
|
|
942
1346
|
exports.GatewayRunner = GatewayRunner;
|
|
943
1347
|
exports.HookExecutor = HookExecutor;
|
|
1348
|
+
exports.SeenIds = SeenIds;
|
|
944
1349
|
exports.SessionRouter = SessionRouter;
|
|
945
1350
|
exports.channelRendering = channelRendering;
|
|
946
1351
|
exports.chunkByGrapheme = chunkByGrapheme;
|
|
@@ -952,6 +1357,8 @@ exports.loadPeer = loadPeer;
|
|
|
952
1357
|
exports.maskShapes = maskShapes;
|
|
953
1358
|
exports.rawBodyCapture = rawBodyCapture;
|
|
954
1359
|
exports.redactSecrets = redactSecrets;
|
|
1360
|
+
exports.scanFences = scanFences;
|
|
1361
|
+
exports.splitKeepingRows = splitKeepingRows;
|
|
955
1362
|
exports.toDialect = toDialect;
|
|
956
1363
|
//# sourceMappingURL=index.cjs.map
|
|
957
1364
|
//# sourceMappingURL=index.cjs.map
|