@theokit/gateway 0.18.0 → 0.19.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 +15 -0
- package/README.md +99 -0
- package/dist/index.cjs +399 -29
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +236 -1
- package/dist/index.d.ts +236 -1
- package/dist/index.js +391 -30
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -216,7 +216,7 @@ function channelRendering(platform) {
|
|
|
216
216
|
}
|
|
217
217
|
|
|
218
218
|
// src/adapter/base.ts
|
|
219
|
-
var BasePlatformAdapter = class {
|
|
219
|
+
var BasePlatformAdapter = class _BasePlatformAdapter {
|
|
220
220
|
/**
|
|
221
221
|
* Run a subscribed handler and contain its failure. The body of {@link deliver}, written once.
|
|
222
222
|
*
|
|
@@ -307,6 +307,27 @@ var BasePlatformAdapter = class {
|
|
|
307
307
|
* `boolean` so that an adapter that sends images can override it with `true`.
|
|
308
308
|
*/
|
|
309
309
|
supportsAttachments = false;
|
|
310
|
+
/**
|
|
311
|
+
* The attachment kinds {@link sendMessage} can send. `undefined` means "not declared": the
|
|
312
|
+
* `capabilities` getter then reports `["image"]` when `supportsAttachments` is `true`, else `[]`.
|
|
313
|
+
*/
|
|
314
|
+
attachmentKinds = void 0;
|
|
315
|
+
/**
|
|
316
|
+
* What this adapter can do, for an app that renders differently per channel.
|
|
317
|
+
*
|
|
318
|
+
* Derived from the members above and from which lifecycle methods the subclass overrides; an
|
|
319
|
+
* adapter overrides the getter only for what derivation cannot know. Read it at call time.
|
|
320
|
+
*/
|
|
321
|
+
get capabilities() {
|
|
322
|
+
const proto = _BasePlatformAdapter.prototype;
|
|
323
|
+
return {
|
|
324
|
+
edit: this.supportsEdit,
|
|
325
|
+
attachments: this.attachmentKinds ?? (this.supportsAttachments ? ["image"] : []),
|
|
326
|
+
typing: this.startTyping !== proto.startTyping,
|
|
327
|
+
reactions: this.react !== proto.react,
|
|
328
|
+
threads: false
|
|
329
|
+
};
|
|
330
|
+
}
|
|
310
331
|
/**
|
|
311
332
|
* Replace the text of a message this adapter sent, keeping its id.
|
|
312
333
|
*
|
|
@@ -533,6 +554,11 @@ var WeixinAdapterBase = class extends BasePlatformAdapter {
|
|
|
533
554
|
}
|
|
534
555
|
};
|
|
535
556
|
|
|
557
|
+
// src/channel/channel-descriptor.ts
|
|
558
|
+
function isAuthenticatedSender(descriptor) {
|
|
559
|
+
return descriptor.senderIdentity === "authenticated";
|
|
560
|
+
}
|
|
561
|
+
|
|
536
562
|
// src/errors/config-error.ts
|
|
537
563
|
var GatewayConfigurationError = class extends Error {
|
|
538
564
|
name = "GatewayConfigurationError";
|
|
@@ -672,6 +698,72 @@ var GatewayLifecycleError = class extends Error {
|
|
|
672
698
|
this.code = opts.code;
|
|
673
699
|
}
|
|
674
700
|
};
|
|
701
|
+
|
|
702
|
+
// src/hooks/chat-command.ts
|
|
703
|
+
var LEADING_MENTION = /^(?:<@[^>]+>|@\S+)\s+/;
|
|
704
|
+
var DEFAULT_PREFIXES = ["/"];
|
|
705
|
+
function matchPrefix(text, prefixes) {
|
|
706
|
+
let best;
|
|
707
|
+
for (const p of prefixes) {
|
|
708
|
+
if (p.length > 0 && text.startsWith(p) && (best === void 0 || p.length > best.length)) {
|
|
709
|
+
best = p;
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
return best;
|
|
713
|
+
}
|
|
714
|
+
function parseChatCommand(text, options) {
|
|
715
|
+
const body = text.trim().replace(LEADING_MENTION, "");
|
|
716
|
+
const prefix = matchPrefix(body, options?.prefixes ?? DEFAULT_PREFIXES);
|
|
717
|
+
if (prefix === void 0) return void 0;
|
|
718
|
+
const rest = body.slice(prefix.length);
|
|
719
|
+
const m = /^([^\s@]+)(?:@\S+)?(?:\s+([\s\S]*))?$/.exec(rest);
|
|
720
|
+
if (!m?.[1]) return void 0;
|
|
721
|
+
return { name: m[1].toLowerCase(), arg: (m[2] ?? "").trim() };
|
|
722
|
+
}
|
|
723
|
+
function usageOf(c) {
|
|
724
|
+
return c.usage ?? `/${c.name}`;
|
|
725
|
+
}
|
|
726
|
+
function helpText(commands) {
|
|
727
|
+
return commands.map((c) => `${usageOf(c)} - ${c.description}`).join("\n");
|
|
728
|
+
}
|
|
729
|
+
function assertUnique(names) {
|
|
730
|
+
const seen = /* @__PURE__ */ new Set();
|
|
731
|
+
for (const raw of names) {
|
|
732
|
+
const name = raw.toLowerCase();
|
|
733
|
+
if (seen.has(name)) {
|
|
734
|
+
throw new GatewayConfigurationError("gateway", {
|
|
735
|
+
code: "duplicate_command",
|
|
736
|
+
message: `gateway: duplicate_command: ${raw}`,
|
|
737
|
+
detail: raw
|
|
738
|
+
});
|
|
739
|
+
}
|
|
740
|
+
seen.add(name);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
function badArity(c, arg) {
|
|
744
|
+
const mode = c.arg ?? "optional";
|
|
745
|
+
return mode === "none" && arg !== "" || mode === "required" && arg === "";
|
|
746
|
+
}
|
|
747
|
+
function commandHook(commands, options) {
|
|
748
|
+
const helpName = options?.helpCommand === void 0 ? "help" : options.helpCommand;
|
|
749
|
+
assertUnique([...commands.map((c) => c.name), ...helpName === false ? [] : [helpName]]);
|
|
750
|
+
const byName = new Map(commands.map((c) => [c.name.toLowerCase(), c]));
|
|
751
|
+
const help = helpText(commands);
|
|
752
|
+
return {
|
|
753
|
+
name: options?.name ?? "chat-commands",
|
|
754
|
+
async pre_inbound({ event }) {
|
|
755
|
+
const parsed = parseChatCommand(event.text);
|
|
756
|
+
if (!parsed) return void 0;
|
|
757
|
+
if (helpName !== false && parsed.name === helpName.toLowerCase()) {
|
|
758
|
+
return { block: true, message: help };
|
|
759
|
+
}
|
|
760
|
+
const command = byName.get(parsed.name);
|
|
761
|
+
if (!command) return void 0;
|
|
762
|
+
if (badArity(command, parsed.arg)) return { block: true, message: usageOf(command) };
|
|
763
|
+
return command.run(event, parsed.arg);
|
|
764
|
+
}
|
|
765
|
+
};
|
|
766
|
+
}
|
|
675
767
|
var UNCOVERED_TABLE = `gateway-qq \`appSecret\` :: a QQ Bot AppSecret, an opaque 32-character string with no prefix or fixed shape. It travels only to the access-token endpoint and into the webhook signature derivation; the adapter never logs it.
|
|
676
768
|
gateway-x \`clientSecret\`, \`refreshToken\`, \`bearerToken\` :: an X OAuth 2.0 client secret, a rotating refresh token and an app bearer token, opaque strings with no fixed prefix. They travel only to the X API in Authorization headers and the token request body, which the adapter never logs.
|
|
677
769
|
gateway-buzz \`token\` :: a Buzz bot token with no fixed shape this package could confirm. It travels only in Authorization headers, which the adapter never logs.
|
|
@@ -749,6 +841,12 @@ function maskShapes(text) {
|
|
|
749
841
|
function redactSecrets(value) {
|
|
750
842
|
return sdk.Security.redact(maskShapes(typeof value === "string" ? value : String(value)));
|
|
751
843
|
}
|
|
844
|
+
function maskSecrets(text, secrets) {
|
|
845
|
+
const ordered = [...new Set(secrets)].filter((s) => s.length > 0).sort((a, b) => b.length - a.length);
|
|
846
|
+
let out = text;
|
|
847
|
+
for (const secret of ordered) out = out.split(secret).join("[redacted]");
|
|
848
|
+
return out;
|
|
849
|
+
}
|
|
752
850
|
|
|
753
851
|
// src/hooks/executor.ts
|
|
754
852
|
var HOOK_PHASES = ["pre_inbound", "post_outbound", "on_error"];
|
|
@@ -862,10 +960,10 @@ function keepTyping(adapter, channelId) {
|
|
|
862
960
|
};
|
|
863
961
|
}
|
|
864
962
|
var DEFAULT_COMMAND_PREFIXES = ["/"];
|
|
865
|
-
function connectFailureReason(outcome) {
|
|
963
|
+
function connectFailureReason(outcome, redact) {
|
|
866
964
|
if (outcome.status === "fulfilled") return "connect returned false";
|
|
867
965
|
const message = outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason);
|
|
868
|
-
return
|
|
966
|
+
return redact(message);
|
|
869
967
|
}
|
|
870
968
|
function isTerminalConnectError(err) {
|
|
871
969
|
if (typeof err !== "object" || err === null) return false;
|
|
@@ -879,7 +977,7 @@ function isTerminalConnectError(err) {
|
|
|
879
977
|
message
|
|
880
978
|
);
|
|
881
979
|
}
|
|
882
|
-
async function releaseAdapters(adapters, during) {
|
|
980
|
+
async function releaseAdapters(adapters, during, redact = redactSecrets) {
|
|
883
981
|
await Promise.all(
|
|
884
982
|
adapters.map(async (a) => {
|
|
885
983
|
try {
|
|
@@ -887,7 +985,7 @@ async function releaseAdapters(adapters, during) {
|
|
|
887
985
|
} catch (err) {
|
|
888
986
|
const message = err instanceof Error ? err.message : String(err);
|
|
889
987
|
process.stderr.write(
|
|
890
|
-
`[gateway] adapter "${a.platform}" disconnect failed while ${during}: ${
|
|
988
|
+
`[gateway] adapter "${a.platform}" disconnect failed while ${during}: ${redact(message)}
|
|
891
989
|
`
|
|
892
990
|
);
|
|
893
991
|
}
|
|
@@ -898,6 +996,8 @@ var GatewayRunner = class {
|
|
|
898
996
|
constructor(opts) {
|
|
899
997
|
this.opts = opts;
|
|
900
998
|
this.hookExecutor = new HookExecutor(opts.hooks ?? []);
|
|
999
|
+
const secrets = opts.secrets ?? [];
|
|
1000
|
+
this.redact = (text) => redactSecrets(maskSecrets(text, secrets));
|
|
901
1001
|
}
|
|
902
1002
|
opts;
|
|
903
1003
|
hookExecutor;
|
|
@@ -910,6 +1010,23 @@ var GatewayRunner = class {
|
|
|
910
1010
|
startInFlight;
|
|
911
1011
|
stopped = false;
|
|
912
1012
|
retryTimers = /* @__PURE__ */ new Set();
|
|
1013
|
+
connectedPlatforms = /* @__PURE__ */ new Set();
|
|
1014
|
+
redact;
|
|
1015
|
+
/** The registered adapter for a platform, connected or not. */
|
|
1016
|
+
adapter(platform) {
|
|
1017
|
+
return this.opts.adapters.find((a) => a.platform === platform);
|
|
1018
|
+
}
|
|
1019
|
+
/** Platforms whose adapter is connected now; updated by connects, retries and `stop()`. */
|
|
1020
|
+
get connected() {
|
|
1021
|
+
return this.connectedPlatforms;
|
|
1022
|
+
}
|
|
1023
|
+
emitState(platform, state, reason) {
|
|
1024
|
+
if ((this.opts.connectFailure ?? "rollback") !== "isolate") return;
|
|
1025
|
+
try {
|
|
1026
|
+
this.opts.onAdapterState?.(platform, state, reason);
|
|
1027
|
+
} catch {
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
913
1030
|
/**
|
|
914
1031
|
* Register a slash command. Match rule (EC-A): text === "/" + name
|
|
915
1032
|
* OR text.startsWith("/" + name + " ") OR text.startsWith("/" + name + "@").
|
|
@@ -964,11 +1081,17 @@ var GatewayRunner = class {
|
|
|
964
1081
|
async runStart() {
|
|
965
1082
|
const result = (this.opts.connectFailure ?? "rollback") === "isolate" ? await this.connectIsolated() : await this.connectAllOrRollback();
|
|
966
1083
|
if (this.stopped) {
|
|
967
|
-
await releaseAdapters(
|
|
1084
|
+
await releaseAdapters(
|
|
1085
|
+
result.connected,
|
|
1086
|
+
"releasing a start that stop() overtook",
|
|
1087
|
+
this.redact
|
|
1088
|
+
);
|
|
1089
|
+
this.connectedPlatforms.clear();
|
|
968
1090
|
this.startResult = { connected: [], failed: result.failed };
|
|
969
1091
|
return this.startResult;
|
|
970
1092
|
}
|
|
971
1093
|
this.wireInbound(result.connected);
|
|
1094
|
+
for (const a of result.connected) this.connectedPlatforms.add(a.platform);
|
|
972
1095
|
this.startResult = {
|
|
973
1096
|
connected: result.connected.map((a) => a.platform),
|
|
974
1097
|
failed: result.failed
|
|
@@ -1001,16 +1124,23 @@ var GatewayRunner = class {
|
|
|
1001
1124
|
`[gateway] adapter "${adapter.platform}" reconnect attempt ${attempt} in ${delay}ms
|
|
1002
1125
|
`
|
|
1003
1126
|
);
|
|
1127
|
+
this.emitState(adapter.platform, "retrying", `reconnect attempt ${attempt} in ${delay}ms`);
|
|
1004
1128
|
}
|
|
1005
1129
|
async reconnectOnce(adapter, attempt) {
|
|
1006
1130
|
if (this.stopped) return;
|
|
1007
1131
|
try {
|
|
1008
1132
|
if (await adapter.connect()) {
|
|
1009
1133
|
if (this.stopped) {
|
|
1010
|
-
await releaseAdapters(
|
|
1134
|
+
await releaseAdapters(
|
|
1135
|
+
[adapter],
|
|
1136
|
+
"releasing a reconnect that stop() overtook",
|
|
1137
|
+
this.redact
|
|
1138
|
+
);
|
|
1011
1139
|
return;
|
|
1012
1140
|
}
|
|
1013
1141
|
this.wireInbound([adapter]);
|
|
1142
|
+
this.connectedPlatforms.add(adapter.platform);
|
|
1143
|
+
this.emitState(adapter.platform, "connected");
|
|
1014
1144
|
const prev = this.startResult ?? { connected: [], failed: [] };
|
|
1015
1145
|
this.startResult = {
|
|
1016
1146
|
connected: [...prev.connected, adapter.platform],
|
|
@@ -1028,8 +1158,9 @@ var GatewayRunner = class {
|
|
|
1028
1158
|
);
|
|
1029
1159
|
return;
|
|
1030
1160
|
} catch (err) {
|
|
1031
|
-
const reason = connectFailureReason({ status: "rejected", reason: err });
|
|
1161
|
+
const reason = connectFailureReason({ status: "rejected", reason: err }, this.redact);
|
|
1032
1162
|
if (isTerminalConnectError(err)) {
|
|
1163
|
+
this.emitState(adapter.platform, "failed", reason);
|
|
1033
1164
|
process.stderr.write(
|
|
1034
1165
|
`[gateway] adapter "${adapter.platform}" credentials rejected: ${reason}; not retrying
|
|
1035
1166
|
`
|
|
@@ -1069,7 +1200,7 @@ var GatewayRunner = class {
|
|
|
1069
1200
|
);
|
|
1070
1201
|
if (failures.length > 0) {
|
|
1071
1202
|
const connected = adapters.filter((_, i) => settled[i]?.status === "fulfilled");
|
|
1072
|
-
await releaseAdapters(connected, "rolling back a failed start");
|
|
1203
|
+
await releaseAdapters(connected, "rolling back a failed start", this.redact);
|
|
1073
1204
|
throw failures[0];
|
|
1074
1205
|
}
|
|
1075
1206
|
return { connected: [...adapters], failed: [], retryable: [] };
|
|
@@ -1081,22 +1212,55 @@ var GatewayRunner = class {
|
|
|
1081
1212
|
*/
|
|
1082
1213
|
async connectIsolated() {
|
|
1083
1214
|
const adapters = this.opts.adapters;
|
|
1084
|
-
const
|
|
1215
|
+
const results = await Promise.all(adapters.map((a) => this.connectOne(a)));
|
|
1085
1216
|
const connected = [];
|
|
1086
1217
|
const failed = [];
|
|
1087
1218
|
const retryable = [];
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
if (outcome.status === "rejected" && !isTerminalConnectError(outcome.reason)) {
|
|
1094
|
-
retryable.push(adapter);
|
|
1095
|
-
}
|
|
1096
|
-
}
|
|
1097
|
-
});
|
|
1219
|
+
for (const r of results) {
|
|
1220
|
+
if (r.failure === void 0) connected.push(r.adapter);
|
|
1221
|
+
else failed.push(r.failure);
|
|
1222
|
+
if (r.retry) retryable.push(r.adapter);
|
|
1223
|
+
}
|
|
1098
1224
|
return { connected, failed, retryable };
|
|
1099
1225
|
}
|
|
1226
|
+
/** Connect one adapter, bounded by `connectTimeoutMs`, and report its state as it settles. */
|
|
1227
|
+
async connectOne(adapter) {
|
|
1228
|
+
const attempt = Promise.allSettled([(async () => adapter.connect())()]).then(
|
|
1229
|
+
([r]) => r
|
|
1230
|
+
);
|
|
1231
|
+
const ms = this.opts.connectTimeoutMs;
|
|
1232
|
+
if (ms === void 0) return this.classify(adapter, await attempt);
|
|
1233
|
+
let timer;
|
|
1234
|
+
const first = await Promise.race([
|
|
1235
|
+
attempt,
|
|
1236
|
+
new Promise((resolve) => {
|
|
1237
|
+
timer = setTimeout(() => resolve("timeout"), ms);
|
|
1238
|
+
})
|
|
1239
|
+
]);
|
|
1240
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
1241
|
+
if (first !== "timeout") return this.classify(adapter, first);
|
|
1242
|
+
void attempt.then((late) => this.releaseLateConnect(adapter, late));
|
|
1243
|
+
const reason = `connect timed out after ${ms}ms`;
|
|
1244
|
+
this.emitState(adapter.platform, "timed_out", reason);
|
|
1245
|
+
return { adapter, failure: { platform: adapter.platform, reason }, retry: true };
|
|
1246
|
+
}
|
|
1247
|
+
/** A connect that finished after the runner gave up on it must not stay connected unseen. */
|
|
1248
|
+
releaseLateConnect(adapter, late) {
|
|
1249
|
+
if (late.status !== "fulfilled" || !late.value) return;
|
|
1250
|
+
if (this.connectedPlatforms.has(adapter.platform)) return;
|
|
1251
|
+
void releaseAdapters([adapter], "releasing a connect that timed out", this.redact);
|
|
1252
|
+
}
|
|
1253
|
+
classify(adapter, outcome) {
|
|
1254
|
+
if (outcome.status === "fulfilled" && outcome.value) {
|
|
1255
|
+
this.connectedPlatforms.add(adapter.platform);
|
|
1256
|
+
this.emitState(adapter.platform, "connected");
|
|
1257
|
+
return { adapter, failure: void 0, retry: false };
|
|
1258
|
+
}
|
|
1259
|
+
const reason = connectFailureReason(outcome, this.redact);
|
|
1260
|
+
this.emitState(adapter.platform, "failed", reason);
|
|
1261
|
+
const retry = outcome.status === "rejected" && !isTerminalConnectError(outcome.reason);
|
|
1262
|
+
return { adapter, failure: { platform: adapter.platform, reason }, retry };
|
|
1263
|
+
}
|
|
1100
1264
|
wireInbound(adapters) {
|
|
1101
1265
|
for (const a of adapters) {
|
|
1102
1266
|
const unsub = a.onInbound(async (event) => {
|
|
@@ -1128,6 +1292,7 @@ var GatewayRunner = class {
|
|
|
1128
1292
|
this.unsubs.length = 0;
|
|
1129
1293
|
for (const t of this.retryTimers) clearTimeout(t);
|
|
1130
1294
|
this.retryTimers.clear();
|
|
1295
|
+
this.connectedPlatforms.clear();
|
|
1131
1296
|
const drainMs = this.opts.drainTimeoutMs ?? DEFAULT_DRAIN_MS;
|
|
1132
1297
|
if (this.inflight.size > 0) {
|
|
1133
1298
|
let timer;
|
|
@@ -1142,7 +1307,7 @@ var GatewayRunner = class {
|
|
|
1142
1307
|
if (timer !== void 0) clearTimeout(timer);
|
|
1143
1308
|
}
|
|
1144
1309
|
}
|
|
1145
|
-
await releaseAdapters([...new Set(this.opts.adapters)], "stopping the runner");
|
|
1310
|
+
await releaseAdapters([...new Set(this.opts.adapters)], "stopping the runner", this.redact);
|
|
1146
1311
|
}
|
|
1147
1312
|
/**
|
|
1148
1313
|
* @internal Test seam, following `EmailAdapter._threadStoreSize`. The drain set must SHRINK: a
|
|
@@ -1162,7 +1327,7 @@ var GatewayRunner = class {
|
|
|
1162
1327
|
await ctx.reply(decision.message).catch(async (err) => {
|
|
1163
1328
|
const error = err;
|
|
1164
1329
|
await this.hookExecutor.fireOnError({ event, error });
|
|
1165
|
-
process.stderr.write(`[gateway] auto-reply error: ${
|
|
1330
|
+
process.stderr.write(`[gateway] auto-reply error: ${this.redact(error.message)}
|
|
1166
1331
|
`);
|
|
1167
1332
|
});
|
|
1168
1333
|
}
|
|
@@ -1176,7 +1341,7 @@ var GatewayRunner = class {
|
|
|
1176
1341
|
await handler(event, ctx);
|
|
1177
1342
|
} catch (err) {
|
|
1178
1343
|
await this.hookExecutor.fireOnError({ event, error: err });
|
|
1179
|
-
process.stderr.write(`[gateway] handler error: ${
|
|
1344
|
+
process.stderr.write(`[gateway] handler error: ${this.redact(err.message)}
|
|
1180
1345
|
`);
|
|
1181
1346
|
} finally {
|
|
1182
1347
|
await stopTyping();
|
|
@@ -1328,6 +1493,67 @@ var SessionRouter = class {
|
|
|
1328
1493
|
}
|
|
1329
1494
|
};
|
|
1330
1495
|
|
|
1496
|
+
// src/session/bindings.ts
|
|
1497
|
+
function unknownAgent(agent) {
|
|
1498
|
+
return new GatewayConfigurationError("gateway", {
|
|
1499
|
+
code: "unknown_agent",
|
|
1500
|
+
message: `gateway: unknown_agent: ${agent}`,
|
|
1501
|
+
detail: agent
|
|
1502
|
+
});
|
|
1503
|
+
}
|
|
1504
|
+
function createAgentBindings(options) {
|
|
1505
|
+
const known = new Set(options.agents);
|
|
1506
|
+
if (!known.has(options.defaultAgent)) throw unknownAgent(options.defaultAgent);
|
|
1507
|
+
for (const rule of options.rules) {
|
|
1508
|
+
if (!known.has(rule.agent)) throw unknownAgent(rule.agent);
|
|
1509
|
+
if (rule.platform === void 0 && rule.account === void 0 && rule.peer === void 0) {
|
|
1510
|
+
throw new GatewayConfigurationError("gateway", {
|
|
1511
|
+
code: "empty_binding_rule",
|
|
1512
|
+
message: `gateway: empty_binding_rule: ${rule.agent}`,
|
|
1513
|
+
detail: rule.agent
|
|
1514
|
+
});
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
const rules = [...options.rules];
|
|
1518
|
+
const { accountOf } = options;
|
|
1519
|
+
return {
|
|
1520
|
+
agentFor(event) {
|
|
1521
|
+
const ctx = {
|
|
1522
|
+
platform: event.platform,
|
|
1523
|
+
account: accountOf?.(event),
|
|
1524
|
+
peer: event.channel.type === "dm" ? event.sender.id : event.channel.id
|
|
1525
|
+
};
|
|
1526
|
+
let best = options.defaultAgent;
|
|
1527
|
+
let bestScore = 0;
|
|
1528
|
+
for (const rule of rules) {
|
|
1529
|
+
const score = scoreRule(rule, ctx);
|
|
1530
|
+
if (score > bestScore) {
|
|
1531
|
+
best = rule.agent;
|
|
1532
|
+
bestScore = score;
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
return best;
|
|
1536
|
+
}
|
|
1537
|
+
};
|
|
1538
|
+
}
|
|
1539
|
+
function scoreRule(rule, ctx) {
|
|
1540
|
+
const fields = [
|
|
1541
|
+
[rule.platform, ctx.platform, 1],
|
|
1542
|
+
[rule.account, ctx.account, 2],
|
|
1543
|
+
[rule.peer, ctx.peer, 4]
|
|
1544
|
+
];
|
|
1545
|
+
let score = 0;
|
|
1546
|
+
for (const [want, got, weight] of fields) {
|
|
1547
|
+
if (want === void 0) continue;
|
|
1548
|
+
if (want !== got) return 0;
|
|
1549
|
+
score += weight;
|
|
1550
|
+
}
|
|
1551
|
+
return score;
|
|
1552
|
+
}
|
|
1553
|
+
function bindingStrategy(bindings, inner) {
|
|
1554
|
+
return (event) => `${sanitize(bindings.agentFor(event))}-${inner(event)}`;
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1331
1557
|
// src/text/chunk.ts
|
|
1332
1558
|
function searchBoundary(remaining, window, boundaries) {
|
|
1333
1559
|
let cut = window;
|
|
@@ -1485,9 +1711,9 @@ function chunkFencedByGrapheme(text, partLimit, regions) {
|
|
|
1485
1711
|
let prefix = "";
|
|
1486
1712
|
while (prefix.length + (text.length - pos) > partLimit) {
|
|
1487
1713
|
const room = partLimit - prefix.length;
|
|
1488
|
-
const
|
|
1489
|
-
const region = fenceAt(regions,
|
|
1490
|
-
const next = region === void 0 ? { cut:
|
|
1714
|
+
const plain2 = boundaryUpTo(pos, pos + room);
|
|
1715
|
+
const region = fenceAt(regions, plain2);
|
|
1716
|
+
const next = region === void 0 ? { cut: plain2, suffix: "", reopen: "" } : fenceGraphemeCut(text, region, pos, plain2, room, boundaryUpTo);
|
|
1491
1717
|
parts.push(prefix + text.slice(pos, next.cut) + next.suffix);
|
|
1492
1718
|
pos = next.cut;
|
|
1493
1719
|
prefix = next.reopen;
|
|
@@ -1495,9 +1721,9 @@ function chunkFencedByGrapheme(text, partLimit, regions) {
|
|
|
1495
1721
|
parts.push(prefix + text.slice(pos));
|
|
1496
1722
|
return parts;
|
|
1497
1723
|
}
|
|
1498
|
-
function fenceGraphemeCut(text, region, pos,
|
|
1499
|
-
const none = { cut:
|
|
1500
|
-
if (
|
|
1724
|
+
function fenceGraphemeCut(text, region, pos, plain2, room, boundaryUpTo) {
|
|
1725
|
+
const none = { cut: plain2, suffix: "", reopen: "" };
|
|
1726
|
+
if (plain2 <= region.openerEnd) {
|
|
1501
1727
|
return region.start > pos ? { ...none, cut: region.start } : none;
|
|
1502
1728
|
}
|
|
1503
1729
|
const eol = openerEol(text, region);
|
|
@@ -1562,6 +1788,21 @@ function splitKeepingRows(text, partLimit) {
|
|
|
1562
1788
|
return parts;
|
|
1563
1789
|
}
|
|
1564
1790
|
|
|
1791
|
+
// src/webhook/deliver-status.ts
|
|
1792
|
+
function statusForDeliver(outcomes) {
|
|
1793
|
+
let status = 200;
|
|
1794
|
+
for (const outcome of outcomes) {
|
|
1795
|
+
if (outcome === "handler_threw") {
|
|
1796
|
+
status = 500;
|
|
1797
|
+
} else if (outcome === "no_handler") {
|
|
1798
|
+
if (status === 200) status = 503;
|
|
1799
|
+
} else if (outcome !== "ok") {
|
|
1800
|
+
throw new Error(`unknown deliver outcome: ${outcome}`);
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
return status;
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1565
1806
|
// src/webhook/express-server.ts
|
|
1566
1807
|
async function loadPeer(load, onMissing) {
|
|
1567
1808
|
try {
|
|
@@ -1672,6 +1913,126 @@ function listenerLifecycle(opts) {
|
|
|
1672
1913
|
};
|
|
1673
1914
|
}
|
|
1674
1915
|
|
|
1916
|
+
// src/webhook/fetch-handler.ts
|
|
1917
|
+
var TOO_LARGE = /* @__PURE__ */ Symbol("too-large");
|
|
1918
|
+
function defaultPlatformFor(url) {
|
|
1919
|
+
const marker = "/webhooks/";
|
|
1920
|
+
const at = url.pathname.lastIndexOf(marker);
|
|
1921
|
+
if (at < 0) return void 0;
|
|
1922
|
+
const rest = url.pathname.slice(at + marker.length).replace(/\/+$/, "");
|
|
1923
|
+
const last = rest.split("/").pop();
|
|
1924
|
+
return last ? last : void 0;
|
|
1925
|
+
}
|
|
1926
|
+
function plain(status, extra) {
|
|
1927
|
+
return new Response(null, { status, headers: extra });
|
|
1928
|
+
}
|
|
1929
|
+
function tooLarge() {
|
|
1930
|
+
return plain(413, { connection: "close" });
|
|
1931
|
+
}
|
|
1932
|
+
async function readCapped(request, max) {
|
|
1933
|
+
const declared = request.headers.get("content-length");
|
|
1934
|
+
if (declared !== null && Number(declared) > max) return TOO_LARGE;
|
|
1935
|
+
if (request.body === null) return "";
|
|
1936
|
+
const reader = request.body.getReader();
|
|
1937
|
+
const chunks = [];
|
|
1938
|
+
let total = 0;
|
|
1939
|
+
for (; ; ) {
|
|
1940
|
+
const { done, value } = await reader.read();
|
|
1941
|
+
if (done) break;
|
|
1942
|
+
total += value.byteLength;
|
|
1943
|
+
if (total > max) {
|
|
1944
|
+
await reader.cancel().catch(() => void 0);
|
|
1945
|
+
return TOO_LARGE;
|
|
1946
|
+
}
|
|
1947
|
+
chunks.push(value);
|
|
1948
|
+
}
|
|
1949
|
+
const joined = new Uint8Array(total);
|
|
1950
|
+
let offset = 0;
|
|
1951
|
+
for (const chunk of chunks) {
|
|
1952
|
+
joined.set(chunk, offset);
|
|
1953
|
+
offset += chunk.byteLength;
|
|
1954
|
+
}
|
|
1955
|
+
return new TextDecoder().decode(joined);
|
|
1956
|
+
}
|
|
1957
|
+
function answerResponse(answer) {
|
|
1958
|
+
const headers = {};
|
|
1959
|
+
if (answer.contentType !== void 0) headers["content-type"] = answer.contentType;
|
|
1960
|
+
return new Response(answer.body ?? null, { status: answer.status, headers });
|
|
1961
|
+
}
|
|
1962
|
+
async function runDefault(webhook, adapter, request) {
|
|
1963
|
+
if (!webhook.verify(adapter, request)) return plain(401);
|
|
1964
|
+
let payload;
|
|
1965
|
+
try {
|
|
1966
|
+
payload = JSON.parse(request.rawBody);
|
|
1967
|
+
} catch {
|
|
1968
|
+
return plain(400);
|
|
1969
|
+
}
|
|
1970
|
+
const result = await webhook.ingest(adapter, payload);
|
|
1971
|
+
if (result === "delivered") return plain(200);
|
|
1972
|
+
return plain(result === "no_handler" ? 503 : 400);
|
|
1973
|
+
}
|
|
1974
|
+
function headersOf(request) {
|
|
1975
|
+
const out = {};
|
|
1976
|
+
request.headers.forEach((value, key) => {
|
|
1977
|
+
out[key] = value;
|
|
1978
|
+
});
|
|
1979
|
+
return out;
|
|
1980
|
+
}
|
|
1981
|
+
async function readBody(request, max) {
|
|
1982
|
+
let body;
|
|
1983
|
+
try {
|
|
1984
|
+
body = await readCapped(request, max);
|
|
1985
|
+
} catch {
|
|
1986
|
+
return plain(400);
|
|
1987
|
+
}
|
|
1988
|
+
return body === TOO_LARGE ? tooLarge() : body;
|
|
1989
|
+
}
|
|
1990
|
+
function createWebhookHandler(options) {
|
|
1991
|
+
const max = options.maxBodyBytes ?? DEFAULT_WEBHOOK_MAX_BYTES;
|
|
1992
|
+
const platformFor = options.platformFor ?? defaultPlatformFor;
|
|
1993
|
+
const routes = /* @__PURE__ */ new Map();
|
|
1994
|
+
for (const channel of options.channels) {
|
|
1995
|
+
if (channel.descriptor.transport === "webhook")
|
|
1996
|
+
routes.set(channel.descriptor.platform, channel);
|
|
1997
|
+
}
|
|
1998
|
+
const route = (url) => {
|
|
1999
|
+
const platform = platformFor(url);
|
|
2000
|
+
return platform === void 0 ? void 0 : routes.get(platform);
|
|
2001
|
+
};
|
|
2002
|
+
return async (request) => {
|
|
2003
|
+
const channel = route(new URL(request.url));
|
|
2004
|
+
if (channel === void 0) return plain(404);
|
|
2005
|
+
const platform = channel.descriptor.platform;
|
|
2006
|
+
if (!options.isStarted(platform)) return plain(503);
|
|
2007
|
+
const webhook = channel.descriptor.webhook;
|
|
2008
|
+
const refused2 = refuseMethod(webhook, request);
|
|
2009
|
+
if (refused2 !== void 0) return refused2;
|
|
2010
|
+
const rawBody = await readBody(request, max);
|
|
2011
|
+
if (typeof rawBody !== "string") return rawBody;
|
|
2012
|
+
try {
|
|
2013
|
+
return await dispatch(webhook, channel.adapter, {
|
|
2014
|
+
rawBody,
|
|
2015
|
+
headers: headersOf(request),
|
|
2016
|
+
method: request.method.toUpperCase(),
|
|
2017
|
+
url: request.url
|
|
2018
|
+
});
|
|
2019
|
+
} catch (error) {
|
|
2020
|
+
options.onError?.(platform, error);
|
|
2021
|
+
return plain(500);
|
|
2022
|
+
}
|
|
2023
|
+
};
|
|
2024
|
+
}
|
|
2025
|
+
function refuseMethod(webhook, request) {
|
|
2026
|
+
const methods = webhook.methods ?? ["POST"];
|
|
2027
|
+
const method = request.method.toUpperCase();
|
|
2028
|
+
if (methods.some((m) => m.toUpperCase() === method)) return void 0;
|
|
2029
|
+
return plain(405, { allow: methods.join(", ") });
|
|
2030
|
+
}
|
|
2031
|
+
async function dispatch(webhook, adapter, request) {
|
|
2032
|
+
if (webhook.handle !== void 0) return answerResponse(await webhook.handle(adapter, request));
|
|
2033
|
+
return runDefault(webhook, adapter, request);
|
|
2034
|
+
}
|
|
2035
|
+
|
|
1675
2036
|
exports.BasePlatformAdapter = BasePlatformAdapter;
|
|
1676
2037
|
exports.CREDENTIAL_SHAPES = CREDENTIAL_SHAPES;
|
|
1677
2038
|
exports.DEFAULT_WEBHOOK_MAX_BYTES = DEFAULT_WEBHOOK_MAX_BYTES;
|
|
@@ -1683,19 +2044,28 @@ exports.HookExecutor = HookExecutor;
|
|
|
1683
2044
|
exports.SeenIds = SeenIds;
|
|
1684
2045
|
exports.SessionRouter = SessionRouter;
|
|
1685
2046
|
exports.WeixinAdapterBase = WeixinAdapterBase;
|
|
2047
|
+
exports.bindingStrategy = bindingStrategy;
|
|
1686
2048
|
exports.channelRendering = channelRendering;
|
|
1687
2049
|
exports.chunkByGrapheme = chunkByGrapheme;
|
|
1688
2050
|
exports.chunkText = chunkText;
|
|
2051
|
+
exports.commandHook = commandHook;
|
|
2052
|
+
exports.createAgentBindings = createAgentBindings;
|
|
1689
2053
|
exports.createChannels = createChannels;
|
|
2054
|
+
exports.createWebhookHandler = createWebhookHandler;
|
|
1690
2055
|
exports.defaultStrategy = defaultStrategy;
|
|
2056
|
+
exports.helpText = helpText;
|
|
2057
|
+
exports.isAuthenticatedSender = isAuthenticatedSender;
|
|
1691
2058
|
exports.listenerLifecycle = listenerLifecycle;
|
|
1692
2059
|
exports.loadPeer = loadPeer;
|
|
2060
|
+
exports.maskSecrets = maskSecrets;
|
|
1693
2061
|
exports.maskShapes = maskShapes;
|
|
2062
|
+
exports.parseChatCommand = parseChatCommand;
|
|
1694
2063
|
exports.parseFlatXml = parseFlatXml;
|
|
1695
2064
|
exports.rawBodyCapture = rawBodyCapture;
|
|
1696
2065
|
exports.redactSecrets = redactSecrets;
|
|
1697
2066
|
exports.scanFences = scanFences;
|
|
1698
2067
|
exports.splitKeepingRows = splitKeepingRows;
|
|
2068
|
+
exports.statusForDeliver = statusForDeliver;
|
|
1699
2069
|
exports.toDialect = toDialect;
|
|
1700
2070
|
exports.withMediaUnderstanding = withMediaUnderstanding;
|
|
1701
2071
|
//# sourceMappingURL=index.cjs.map
|