@cicord/sdk 0.0.0-bootstrap.0 → 0.1.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/LICENSE +202 -0
- package/README.md +59 -0
- package/dist/index.d.ts +734 -0
- package/dist/index.mjs +34 -0
- package/dist/index.mjs.map +1 -0
- package/dist/testing.d.ts +304 -0
- package/dist/testing.mjs +982 -0
- package/dist/testing.mjs.map +1 -0
- package/package.json +57 -1
package/dist/testing.mjs
ADDED
|
@@ -0,0 +1,982 @@
|
|
|
1
|
+
import { CapabilityError } from "./index.mjs";
|
|
2
|
+
// src/testing.ts
|
|
3
|
+
/** Builds the error the host throws when `capability` is not granted. */
|
|
4
|
+
function capabilityError(capability) {
|
|
5
|
+
return new CapabilityError(`missing capability "${capability}" (add it to grants in bot.yaml)`, { capability });
|
|
6
|
+
}
|
|
7
|
+
/** Every permission name (Administrator and the owner get all of them). */
|
|
8
|
+
const ALL_PERMISSIONS = [
|
|
9
|
+
"CreateInstantInvite",
|
|
10
|
+
"KickMembers",
|
|
11
|
+
"BanMembers",
|
|
12
|
+
"Administrator",
|
|
13
|
+
"ManageChannels",
|
|
14
|
+
"ManageServer",
|
|
15
|
+
"AddReactions",
|
|
16
|
+
"ViewAuditLog",
|
|
17
|
+
"PrioritySpeaker",
|
|
18
|
+
"Stream",
|
|
19
|
+
"ViewChannel",
|
|
20
|
+
"SendMessages",
|
|
21
|
+
"SendTTSMessages",
|
|
22
|
+
"ManageMessages",
|
|
23
|
+
"EmbedLinks",
|
|
24
|
+
"AttachFiles",
|
|
25
|
+
"ReadMessageHistory",
|
|
26
|
+
"MentionEveryone",
|
|
27
|
+
"UseExternalEmojis",
|
|
28
|
+
"ViewServerInsights",
|
|
29
|
+
"Connect",
|
|
30
|
+
"Speak",
|
|
31
|
+
"MuteMembers",
|
|
32
|
+
"DeafenMembers",
|
|
33
|
+
"MoveMembers",
|
|
34
|
+
"UseVAD",
|
|
35
|
+
"ChangeNickname",
|
|
36
|
+
"ManageNicknames",
|
|
37
|
+
"ManageRoles",
|
|
38
|
+
"ManageWebhooks",
|
|
39
|
+
"ManageExpressions",
|
|
40
|
+
"UseApplicationCommands",
|
|
41
|
+
"RequestToSpeak",
|
|
42
|
+
"ManageEvents",
|
|
43
|
+
"ManageThreads",
|
|
44
|
+
"CreatePublicThreads",
|
|
45
|
+
"CreatePrivateThreads",
|
|
46
|
+
"UseExternalStickers",
|
|
47
|
+
"SendMessagesInThreads",
|
|
48
|
+
"UseEmbeddedActivities",
|
|
49
|
+
"ModerateMembers",
|
|
50
|
+
"ViewCreatorMonetizationAnalytics",
|
|
51
|
+
"UseSoundboard",
|
|
52
|
+
"CreateExpressions",
|
|
53
|
+
"CreateEvents",
|
|
54
|
+
"UseExternalSounds",
|
|
55
|
+
"SendVoiceMessages",
|
|
56
|
+
"SendPolls",
|
|
57
|
+
"UseExternalApps"
|
|
58
|
+
];
|
|
59
|
+
const SNOWFLAKE = /^\d{1,20}$/;
|
|
60
|
+
const MAX_MENTION_IDS = 100;
|
|
61
|
+
/**
|
|
62
|
+
* Validates and normalizes `allowedMentions` like the host: `users` / `roles` are a boolean
|
|
63
|
+
* or at most 100 ids (or objects with an id). Ids must be snowflakes, or ids known to the
|
|
64
|
+
* fakes (`known`), since test ids such as `role-staff` are not snowflakes. Throws a
|
|
65
|
+
* TypeError like the host.
|
|
66
|
+
*/
|
|
67
|
+
function normalizeAllowedMentions(input, known = () => false) {
|
|
68
|
+
if (typeof input === "string" || input.allowedMentions === void 0) return void 0;
|
|
69
|
+
const am = input.allowedMentions;
|
|
70
|
+
const list = (name) => {
|
|
71
|
+
const v = am[name];
|
|
72
|
+
if (v === void 0 || v === null) return void 0;
|
|
73
|
+
if (typeof v === "boolean") return v;
|
|
74
|
+
if (!Array.isArray(v)) throw new TypeError(`allowedMentions.${name} must be a boolean or an array of ids`);
|
|
75
|
+
if (v.length > MAX_MENTION_IDS) throw new TypeError(`allowedMentions: at most ${MAX_MENTION_IDS} ${name} ids`);
|
|
76
|
+
return v.map((x) => {
|
|
77
|
+
const id = x !== null && typeof x === "object" ? x.id : x;
|
|
78
|
+
if (typeof id !== "string" || !(SNOWFLAKE.test(id) || known(id))) throw new TypeError(`allowedMentions: ${name} id ${JSON.stringify(id)} is not a snowflake`);
|
|
79
|
+
return id;
|
|
80
|
+
});
|
|
81
|
+
};
|
|
82
|
+
const users = list("users");
|
|
83
|
+
const roles = list("roles");
|
|
84
|
+
return {
|
|
85
|
+
...users !== void 0 ? { users } : {},
|
|
86
|
+
...roles !== void 0 ? { roles } : {},
|
|
87
|
+
...am["everyone"] !== void 0 ? { everyone: Boolean(am["everyone"]) } : {},
|
|
88
|
+
...am["repliedUser"] !== void 0 ? { repliedUser: Boolean(am["repliedUser"]) } : {}
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
function clone(value) {
|
|
92
|
+
return structuredClone(value);
|
|
93
|
+
}
|
|
94
|
+
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
95
|
+
function resolveRef(root, s) {
|
|
96
|
+
for (let i = 0; i < 8; i++) {
|
|
97
|
+
const ref = s["$ref"];
|
|
98
|
+
if (typeof ref !== "string") return s;
|
|
99
|
+
if (!ref.startsWith("#")) return {};
|
|
100
|
+
let cur = root;
|
|
101
|
+
for (const raw of ref.slice(1).split("/")) {
|
|
102
|
+
if (raw === "") continue;
|
|
103
|
+
const part = raw.replaceAll("~1", "/").replaceAll("~0", "~");
|
|
104
|
+
cur = isObject(cur) ? cur[part] : void 0;
|
|
105
|
+
}
|
|
106
|
+
if (!isObject(cur)) return {};
|
|
107
|
+
const { $ref: _ignored, ...siblings } = s;
|
|
108
|
+
s = {
|
|
109
|
+
...cur,
|
|
110
|
+
...siblings
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
return s;
|
|
114
|
+
}
|
|
115
|
+
function defaultsInObject(root, schema, v, depth) {
|
|
116
|
+
if (depth > 32) return;
|
|
117
|
+
schema = resolveRef(root, schema);
|
|
118
|
+
const props = isObject(schema["properties"]) ? schema["properties"] : {};
|
|
119
|
+
for (const [k, raw] of Object.entries(props)) {
|
|
120
|
+
if (!isObject(raw)) continue;
|
|
121
|
+
const sub = resolveRef(root, raw);
|
|
122
|
+
if (!(k in v) && "default" in sub) v[k] = structuredClone(sub["default"]);
|
|
123
|
+
if (k in v) defaultsInValue(root, sub, v[k], depth + 1);
|
|
124
|
+
else if (sub["type"] === "object" && isObject(sub["properties"])) {
|
|
125
|
+
const obj = {};
|
|
126
|
+
defaultsInObject(root, sub, obj, depth + 1);
|
|
127
|
+
const required = Array.isArray(sub["required"]) ? sub["required"] : [];
|
|
128
|
+
if (Object.keys(obj).length > 0 && required.every((r) => typeof r !== "string" || r in obj)) v[k] = obj;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
function defaultsInValue(root, schema, v, depth) {
|
|
133
|
+
if (isObject(v)) defaultsInObject(root, schema, v, depth);
|
|
134
|
+
else if (Array.isArray(v) && depth <= 32) {
|
|
135
|
+
const items = resolveRef(root, schema)["items"];
|
|
136
|
+
if (isObject(items)) for (const e of v) defaultsInValue(root, items, e, depth + 1);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Returns a copy of `config` with the `default`s of a JSON Schema applied, with the runtime's
|
|
141
|
+
* rules (config.ApplyDefaults): nested objects, object elements of arrays and local `$ref`s;
|
|
142
|
+
* not `additionalProperties` values nor `oneOf`/`anyOf` alternatives.
|
|
143
|
+
*/
|
|
144
|
+
function applyDefaults(schema, config) {
|
|
145
|
+
const out = structuredClone(config);
|
|
146
|
+
defaultsInObject(schema, schema, out, 0);
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
function makeUser(init) {
|
|
150
|
+
const username = init.username ?? `user${init.id}`;
|
|
151
|
+
return {
|
|
152
|
+
id: init.id,
|
|
153
|
+
username,
|
|
154
|
+
displayName: init.displayName ?? username,
|
|
155
|
+
...init.avatarUrl ? { avatarUrl: init.avatarUrl } : {},
|
|
156
|
+
bot: init.bot ?? false,
|
|
157
|
+
mention: `<@${init.id}>`
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
function createTestContext(options = {}) {
|
|
161
|
+
const grants = options.grants ? new Set(options.grants) : void 0;
|
|
162
|
+
const need = (capability) => {
|
|
163
|
+
if (grants && !grants.has(capability)) throw capabilityError(capability);
|
|
164
|
+
};
|
|
165
|
+
const logs = [];
|
|
166
|
+
const sent = [];
|
|
167
|
+
const roleChanges = [];
|
|
168
|
+
const links = [];
|
|
169
|
+
const published = [];
|
|
170
|
+
const scheduled = [];
|
|
171
|
+
const edits = [];
|
|
172
|
+
const deletedMessages = [];
|
|
173
|
+
const reactions = [];
|
|
174
|
+
const moderation = [];
|
|
175
|
+
const createdChannels = [];
|
|
176
|
+
const deletedChannels = [];
|
|
177
|
+
const threads = [];
|
|
178
|
+
const requests = [];
|
|
179
|
+
const kvData = /* @__PURE__ */ new Map();
|
|
180
|
+
const kvExpiry = /* @__PURE__ */ new Map();
|
|
181
|
+
const roles = /* @__PURE__ */ new Map();
|
|
182
|
+
const rolePermissions = /* @__PURE__ */ new Map();
|
|
183
|
+
for (const [key, r] of Object.entries(options.roles ?? {})) {
|
|
184
|
+
const id = r.id ?? `role-${key}`;
|
|
185
|
+
roles.set(key, {
|
|
186
|
+
id,
|
|
187
|
+
key,
|
|
188
|
+
name: r.name,
|
|
189
|
+
...r.color ? { color: r.color } : {},
|
|
190
|
+
mention: `<@&${id}>`,
|
|
191
|
+
position: r.position ?? roles.size + 1,
|
|
192
|
+
mentionable: r.mentionable ?? false
|
|
193
|
+
});
|
|
194
|
+
rolePermissions.set(id, r.permissions ?? []);
|
|
195
|
+
}
|
|
196
|
+
const ownerId = options.server?.ownerId;
|
|
197
|
+
const inPrincipals = (p, userId, owned) => !!p && ((p.users ?? []).includes(userId) || (p.roles ?? []).some((key) => {
|
|
198
|
+
const role = roles.get(key);
|
|
199
|
+
return role !== void 0 && owned.has(role.id);
|
|
200
|
+
}));
|
|
201
|
+
const resolveRole = (ref) => {
|
|
202
|
+
if (typeof ref === "string") return roles.get(ref);
|
|
203
|
+
for (const r of roles.values()) if (r.id === ref.id) return r;
|
|
204
|
+
};
|
|
205
|
+
const botUser = makeUser({
|
|
206
|
+
id: "bot",
|
|
207
|
+
username: options.bot?.username ?? "TestBot",
|
|
208
|
+
bot: true
|
|
209
|
+
});
|
|
210
|
+
const messages = /* @__PURE__ */ new Map();
|
|
211
|
+
const history = /* @__PURE__ */ new Map();
|
|
212
|
+
let messageSeq = 0;
|
|
213
|
+
const makeMessage = (channel, author, input) => {
|
|
214
|
+
const message = {
|
|
215
|
+
id: String(1000000000000000n + BigInt(++messageSeq)),
|
|
216
|
+
content: typeof input === "string" ? input : input.content ?? "",
|
|
217
|
+
author,
|
|
218
|
+
channel,
|
|
219
|
+
attachments: [],
|
|
220
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
221
|
+
async reply(reply) {
|
|
222
|
+
need(channel.type === "dm" ? "discord.dm.send" : "discord.messages.send");
|
|
223
|
+
return post(channel, reply);
|
|
224
|
+
},
|
|
225
|
+
async edit(next) {
|
|
226
|
+
if (author.id !== botUser.id) need("discord.messages.manage");
|
|
227
|
+
edits.push({
|
|
228
|
+
id: message.id,
|
|
229
|
+
message: next
|
|
230
|
+
});
|
|
231
|
+
return makeMessage(channel, author, next);
|
|
232
|
+
},
|
|
233
|
+
async delete(reason) {
|
|
234
|
+
need("discord.messages.manage");
|
|
235
|
+
deletedMessages.push({
|
|
236
|
+
id: message.id,
|
|
237
|
+
...reason ? { reason } : {}
|
|
238
|
+
});
|
|
239
|
+
},
|
|
240
|
+
async react(emoji) {
|
|
241
|
+
need("discord.reactions.manage");
|
|
242
|
+
reactions.push({
|
|
243
|
+
message: message.id,
|
|
244
|
+
emoji
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
messages.set(message.id, message);
|
|
249
|
+
const list = history.get(channel.id) ?? [];
|
|
250
|
+
list.push(message);
|
|
251
|
+
history.set(channel.id, list);
|
|
252
|
+
return message;
|
|
253
|
+
};
|
|
254
|
+
/** Records a message sent by the bot. */
|
|
255
|
+
const knownId = (id) => members.has(id) || [...roles.values()].some((r) => r.id === id);
|
|
256
|
+
const post = (channel, input, to) => {
|
|
257
|
+
const allowedMentions = normalizeAllowedMentions(input, knownId);
|
|
258
|
+
const message = makeMessage(channel, botUser, input);
|
|
259
|
+
sent.push({
|
|
260
|
+
to: to ?? channel.key ?? channel.id,
|
|
261
|
+
message: input,
|
|
262
|
+
id: message.id,
|
|
263
|
+
...allowedMentions ? { allowedMentions } : {}
|
|
264
|
+
});
|
|
265
|
+
return message;
|
|
266
|
+
};
|
|
267
|
+
const channels = /* @__PURE__ */ new Map();
|
|
268
|
+
const makeChannel = (key, init) => {
|
|
269
|
+
const id = init.id ?? (key ? `channel-${key}` : `channel-${channels.size + 1}`);
|
|
270
|
+
const channel = {
|
|
271
|
+
id,
|
|
272
|
+
...key ? { key } : {},
|
|
273
|
+
name: init.name,
|
|
274
|
+
type: init.type ?? "text",
|
|
275
|
+
mention: `<#${id}>`,
|
|
276
|
+
async send(input) {
|
|
277
|
+
need(channel.type === "dm" ? "discord.dm.send" : "discord.messages.send");
|
|
278
|
+
return post(channel, input);
|
|
279
|
+
},
|
|
280
|
+
async messages(opts = {}) {
|
|
281
|
+
need("discord.messages.read");
|
|
282
|
+
let list = (history.get(id) ?? []).toReversed();
|
|
283
|
+
const { before, after } = opts;
|
|
284
|
+
if (before) list = list.filter((m) => BigInt(m.id) < BigInt(before));
|
|
285
|
+
if (after) list = list.filter((m) => BigInt(m.id) > BigInt(after)).toReversed();
|
|
286
|
+
return list.slice(0, opts.limit ?? 50);
|
|
287
|
+
},
|
|
288
|
+
async message(messageId) {
|
|
289
|
+
need("discord.messages.read");
|
|
290
|
+
return (history.get(id) ?? []).find((m) => m.id === messageId);
|
|
291
|
+
},
|
|
292
|
+
async createThread(name, opts = {}) {
|
|
293
|
+
need("discord.threads.manage");
|
|
294
|
+
threads.push({
|
|
295
|
+
parent: id,
|
|
296
|
+
name,
|
|
297
|
+
private: opts.private ?? false,
|
|
298
|
+
...opts.fromMessage ? { fromMessage: opts.fromMessage } : {}
|
|
299
|
+
});
|
|
300
|
+
return register(void 0, {
|
|
301
|
+
name,
|
|
302
|
+
type: "thread"
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
return channel;
|
|
307
|
+
};
|
|
308
|
+
const register = (key, init) => {
|
|
309
|
+
const channel = makeChannel(key, init);
|
|
310
|
+
if (key) channels.set(key, channel);
|
|
311
|
+
channels.set(channel.id, channel);
|
|
312
|
+
return channel;
|
|
313
|
+
};
|
|
314
|
+
for (const [key, c] of Object.entries(options.channels ?? {})) register(key, c);
|
|
315
|
+
const members = /* @__PURE__ */ new Map();
|
|
316
|
+
const addMember = (init) => {
|
|
317
|
+
const user = makeUser(init);
|
|
318
|
+
const owned = /* @__PURE__ */ new Set();
|
|
319
|
+
for (const key of init.roles ?? []) {
|
|
320
|
+
const role = roles.get(key);
|
|
321
|
+
if (!role) throw new Error(`createTestContext: member ${init.id} has unknown role "${key}"`);
|
|
322
|
+
owned.add(role.id);
|
|
323
|
+
}
|
|
324
|
+
const change = (ref, action, reason) => {
|
|
325
|
+
need("discord.roles.assign");
|
|
326
|
+
const role = resolveRole(ref);
|
|
327
|
+
if (!role) throw new Error(`unknown role ${JSON.stringify(ref)}`);
|
|
328
|
+
if (action === "add") owned.add(role.id);
|
|
329
|
+
else owned.delete(role.id);
|
|
330
|
+
roleChanges.push({
|
|
331
|
+
member: init.id,
|
|
332
|
+
role: role.key ?? role.id,
|
|
333
|
+
action,
|
|
334
|
+
...reason ? { reason } : {}
|
|
335
|
+
});
|
|
336
|
+
};
|
|
337
|
+
const moderate = (entry) => {
|
|
338
|
+
need(entry.action === "nickname" ? "discord.members.manage" : "discord.members.moderate");
|
|
339
|
+
moderation.push(entry);
|
|
340
|
+
};
|
|
341
|
+
const member = {
|
|
342
|
+
user,
|
|
343
|
+
id: user.id,
|
|
344
|
+
...init.nickname ? { nickname: init.nickname } : {},
|
|
345
|
+
displayName: init.nickname ?? user.displayName,
|
|
346
|
+
mention: user.mention,
|
|
347
|
+
get roles() {
|
|
348
|
+
return [...roles.values()].filter((r) => owned.has(r.id));
|
|
349
|
+
},
|
|
350
|
+
joinedAt: init.joinedAt ?? /* @__PURE__ */ new Date(0),
|
|
351
|
+
get permissions() {
|
|
352
|
+
if (user.id === ownerId) return ALL_PERMISSIONS;
|
|
353
|
+
const set = new Set(options.server?.everyonePermissions ?? []);
|
|
354
|
+
for (const id of owned) for (const p of rolePermissions.get(id) ?? []) set.add(p);
|
|
355
|
+
if (set.has("Administrator")) return ALL_PERMISSIONS;
|
|
356
|
+
return ALL_PERMISSIONS.filter((p) => set.has(p));
|
|
357
|
+
},
|
|
358
|
+
get access() {
|
|
359
|
+
if (user.id === ownerId || inPrincipals(options.access?.admins, user.id, owned)) return "admin";
|
|
360
|
+
if (inPrincipals(options.access?.moderators, user.id, owned)) return "moderator";
|
|
361
|
+
return "member";
|
|
362
|
+
},
|
|
363
|
+
hasRole(ref) {
|
|
364
|
+
const role = resolveRole(ref);
|
|
365
|
+
return role ? owned.has(role.id) : false;
|
|
366
|
+
},
|
|
367
|
+
async addRole(ref, reason) {
|
|
368
|
+
change(ref, "add", reason);
|
|
369
|
+
},
|
|
370
|
+
async removeRole(ref, reason) {
|
|
371
|
+
change(ref, "remove", reason);
|
|
372
|
+
},
|
|
373
|
+
async setNickname(nickname, reason) {
|
|
374
|
+
moderate({
|
|
375
|
+
member: user.id,
|
|
376
|
+
action: "nickname",
|
|
377
|
+
nickname,
|
|
378
|
+
...reason ? { reason } : {}
|
|
379
|
+
});
|
|
380
|
+
},
|
|
381
|
+
async timeout(durationMs, reason) {
|
|
382
|
+
moderate({
|
|
383
|
+
member: user.id,
|
|
384
|
+
action: "timeout",
|
|
385
|
+
durationMs,
|
|
386
|
+
...reason ? { reason } : {}
|
|
387
|
+
});
|
|
388
|
+
},
|
|
389
|
+
async kick(reason) {
|
|
390
|
+
moderate({
|
|
391
|
+
member: user.id,
|
|
392
|
+
action: "kick",
|
|
393
|
+
...reason ? { reason } : {}
|
|
394
|
+
});
|
|
395
|
+
},
|
|
396
|
+
async ban(opts = {}) {
|
|
397
|
+
moderate({
|
|
398
|
+
member: user.id,
|
|
399
|
+
action: "ban",
|
|
400
|
+
...opts.reason ? { reason: opts.reason } : {},
|
|
401
|
+
...opts.deleteMessagesSeconds !== void 0 ? { deleteMessagesSeconds: opts.deleteMessagesSeconds } : {}
|
|
402
|
+
});
|
|
403
|
+
},
|
|
404
|
+
async send(input) {
|
|
405
|
+
need("discord.dm.send");
|
|
406
|
+
const dm = channels.get(`dm-${user.id}`) ?? register(void 0, {
|
|
407
|
+
name: "dm",
|
|
408
|
+
type: "dm",
|
|
409
|
+
id: `dm-${user.id}`
|
|
410
|
+
});
|
|
411
|
+
return post(dm, input, `dm:${user.id}`);
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
members.set(user.id, member);
|
|
415
|
+
return member;
|
|
416
|
+
};
|
|
417
|
+
for (const m of options.members ?? []) addMember(m);
|
|
418
|
+
const findChannel = (ref) => typeof ref === "string" ? channels.get(ref) : channels.get(ref.id);
|
|
419
|
+
const serverKey = options.server?.key ?? "test-server";
|
|
420
|
+
const server = {
|
|
421
|
+
id: options.server?.id ?? "server-1",
|
|
422
|
+
key: serverKey,
|
|
423
|
+
name: options.server?.name ?? "Test Server",
|
|
424
|
+
...options.server?.iconUrl ? { iconUrl: options.server.iconUrl } : {},
|
|
425
|
+
...ownerId !== void 0 ? { ownerId } : {},
|
|
426
|
+
channel(ref) {
|
|
427
|
+
need("discord.channels.read");
|
|
428
|
+
const found = findChannel(ref);
|
|
429
|
+
if (!found) throw new Error(`unknown channel ${JSON.stringify(ref)}`);
|
|
430
|
+
return found;
|
|
431
|
+
},
|
|
432
|
+
role(ref) {
|
|
433
|
+
const role = resolveRole(ref);
|
|
434
|
+
if (!role) throw new Error(`unknown role ${JSON.stringify(ref)}`);
|
|
435
|
+
return role;
|
|
436
|
+
},
|
|
437
|
+
async member(userId) {
|
|
438
|
+
need("discord.members.read");
|
|
439
|
+
return members.get(userId);
|
|
440
|
+
},
|
|
441
|
+
async createChannel(opts) {
|
|
442
|
+
need("discord.channels.manage");
|
|
443
|
+
if (opts.category !== void 0 && !findChannel(opts.category)) throw new Error(`unknown category ${JSON.stringify(opts.category)}`);
|
|
444
|
+
for (const target of Object.keys(opts.overwrites ?? {})) {
|
|
445
|
+
if (target === "@everyone" || /^(role|member):/.test(target)) continue;
|
|
446
|
+
if (!roles.has(target)) throw new Error(`createChannel(): overwrite target "${target}": unknown role`);
|
|
447
|
+
}
|
|
448
|
+
const channel = register(void 0, {
|
|
449
|
+
name: opts.name,
|
|
450
|
+
type: opts.type ?? "text"
|
|
451
|
+
});
|
|
452
|
+
createdChannels.push({
|
|
453
|
+
channel,
|
|
454
|
+
options: opts
|
|
455
|
+
});
|
|
456
|
+
return channel;
|
|
457
|
+
},
|
|
458
|
+
async deleteChannel(ref, reason) {
|
|
459
|
+
need("discord.channels.manage");
|
|
460
|
+
const channel = findChannel(ref);
|
|
461
|
+
if (!channel || !createdChannels.some((c) => c.channel.id === channel.id)) throw new Error(`deleteChannel(): channel ${JSON.stringify(ref)} is not owned by this plugin instance`);
|
|
462
|
+
channels.delete(channel.id);
|
|
463
|
+
deletedChannels.push({
|
|
464
|
+
id: channel.id,
|
|
465
|
+
...reason ? { reason } : {}
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
};
|
|
469
|
+
const live = (key) => {
|
|
470
|
+
const exp = kvExpiry.get(key);
|
|
471
|
+
if (exp !== void 0 && exp <= Date.now()) {
|
|
472
|
+
kvData.delete(key);
|
|
473
|
+
kvExpiry.delete(key);
|
|
474
|
+
return false;
|
|
475
|
+
}
|
|
476
|
+
return kvData.has(key);
|
|
477
|
+
};
|
|
478
|
+
const kv = {
|
|
479
|
+
async get(key) {
|
|
480
|
+
need("storage.kv");
|
|
481
|
+
if (!live(key)) return void 0;
|
|
482
|
+
return clone(kvData.get(key));
|
|
483
|
+
},
|
|
484
|
+
async set(key, value, opts) {
|
|
485
|
+
need("storage.kv");
|
|
486
|
+
kvData.set(key, clone(value));
|
|
487
|
+
if (opts?.ttlSeconds) kvExpiry.set(key, Date.now() + opts.ttlSeconds * 1e3);
|
|
488
|
+
else kvExpiry.delete(key);
|
|
489
|
+
},
|
|
490
|
+
async delete(key) {
|
|
491
|
+
need("storage.kv");
|
|
492
|
+
kvData.delete(key);
|
|
493
|
+
kvExpiry.delete(key);
|
|
494
|
+
},
|
|
495
|
+
async increment(key, by = 1) {
|
|
496
|
+
need("storage.kv");
|
|
497
|
+
const current = live(key) ? kvData.get(key) : void 0;
|
|
498
|
+
const next = (typeof current === "number" ? current : 0) + by;
|
|
499
|
+
kvData.set(key, next);
|
|
500
|
+
return next;
|
|
501
|
+
},
|
|
502
|
+
async list(opts = {}) {
|
|
503
|
+
need("storage.kv");
|
|
504
|
+
const keys = [...kvData.keys()].filter((k) => k.startsWith(opts.prefix ?? "") && live(k)).toSorted();
|
|
505
|
+
const start = opts.cursor ? Number(opts.cursor) : 0;
|
|
506
|
+
const limit = opts.limit ?? 100;
|
|
507
|
+
const items = keys.slice(start, start + limit).map((key) => ({
|
|
508
|
+
key,
|
|
509
|
+
value: clone(kvData.get(key))
|
|
510
|
+
}));
|
|
511
|
+
const next = start + limit < keys.length ? String(start + limit) : void 0;
|
|
512
|
+
return next ? {
|
|
513
|
+
items,
|
|
514
|
+
cursor: next
|
|
515
|
+
} : { items };
|
|
516
|
+
}
|
|
517
|
+
};
|
|
518
|
+
const log = (level) => (message, fields) => {
|
|
519
|
+
logs.push({
|
|
520
|
+
level,
|
|
521
|
+
message,
|
|
522
|
+
...fields ? { fields } : {}
|
|
523
|
+
});
|
|
524
|
+
};
|
|
525
|
+
let scheduleSeq = 0;
|
|
526
|
+
const portalUrl = (options.portalUrl ?? "https://portal.test").replace(/\/$/, "");
|
|
527
|
+
const config = options.schema !== void 0 ? applyDefaults(options.schema, options.config ?? {}) : options.config ?? {};
|
|
528
|
+
return {
|
|
529
|
+
ctx: {
|
|
530
|
+
plugin: {
|
|
531
|
+
name: options.plugin?.name ?? "test-plugin",
|
|
532
|
+
version: options.plugin?.version ?? "0.0.0",
|
|
533
|
+
instance: options.plugin?.instance ?? options.plugin?.name ?? "test-plugin"
|
|
534
|
+
},
|
|
535
|
+
bot: {
|
|
536
|
+
key: options.bot?.key ?? "test-bot",
|
|
537
|
+
user: botUser
|
|
538
|
+
},
|
|
539
|
+
server,
|
|
540
|
+
config,
|
|
541
|
+
log: {
|
|
542
|
+
debug: log("debug"),
|
|
543
|
+
info: log("info"),
|
|
544
|
+
warn: log("warn"),
|
|
545
|
+
error: log("error")
|
|
546
|
+
},
|
|
547
|
+
kv,
|
|
548
|
+
schedule: {
|
|
549
|
+
async after(delayMs, task, payload) {
|
|
550
|
+
need("scheduler");
|
|
551
|
+
const id = `task-${++scheduleSeq}`;
|
|
552
|
+
scheduled.push({
|
|
553
|
+
id,
|
|
554
|
+
delayMs,
|
|
555
|
+
task,
|
|
556
|
+
...payload === void 0 ? {} : { payload }
|
|
557
|
+
});
|
|
558
|
+
return { id };
|
|
559
|
+
},
|
|
560
|
+
async cancel(id) {
|
|
561
|
+
need("scheduler");
|
|
562
|
+
const i = scheduled.findIndex((s) => s.id === id);
|
|
563
|
+
if (i >= 0) scheduled.splice(i, 1);
|
|
564
|
+
}
|
|
565
|
+
},
|
|
566
|
+
http: { async fetch(url, init) {
|
|
567
|
+
need("http.fetch");
|
|
568
|
+
if (!options.fetch) throw new Error("createTestContext: ctx.http.fetch is not faked; pass `fetch` in the options");
|
|
569
|
+
requests.push({
|
|
570
|
+
url,
|
|
571
|
+
init
|
|
572
|
+
});
|
|
573
|
+
const r = await options.fetch(url, init);
|
|
574
|
+
const body = typeof r.body === "string" ? r.body : r.body === void 0 ? "" : JSON.stringify(r.body);
|
|
575
|
+
return {
|
|
576
|
+
status: r.status ?? 200,
|
|
577
|
+
headers: r.headers ?? {},
|
|
578
|
+
text: async () => body,
|
|
579
|
+
json: async () => JSON.parse(body)
|
|
580
|
+
};
|
|
581
|
+
} },
|
|
582
|
+
events: { async publish(topic, payload) {
|
|
583
|
+
need("events.publish");
|
|
584
|
+
published.push({
|
|
585
|
+
topic,
|
|
586
|
+
payload
|
|
587
|
+
});
|
|
588
|
+
} },
|
|
589
|
+
portal: { async link(path, opts) {
|
|
590
|
+
need("portal.links");
|
|
591
|
+
const memberId = opts?.member?.id;
|
|
592
|
+
const token = `test-${memberId ?? "anonymous"}`;
|
|
593
|
+
const url = `${portalUrl}${path.startsWith("/") ? path : `/${path}`}?cicord_token=${token}`;
|
|
594
|
+
links.push({
|
|
595
|
+
path,
|
|
596
|
+
...memberId ? { member: memberId } : {},
|
|
597
|
+
url
|
|
598
|
+
});
|
|
599
|
+
return url;
|
|
600
|
+
} }
|
|
601
|
+
},
|
|
602
|
+
logs,
|
|
603
|
+
sent,
|
|
604
|
+
roleChanges,
|
|
605
|
+
links,
|
|
606
|
+
published,
|
|
607
|
+
scheduled,
|
|
608
|
+
edits,
|
|
609
|
+
deletedMessages,
|
|
610
|
+
reactions,
|
|
611
|
+
moderation,
|
|
612
|
+
createdChannels,
|
|
613
|
+
deletedChannels,
|
|
614
|
+
threads,
|
|
615
|
+
requests,
|
|
616
|
+
kv: kvData,
|
|
617
|
+
member: (id) => members.get(id),
|
|
618
|
+
addMember,
|
|
619
|
+
message: (id) => messages.get(id),
|
|
620
|
+
channel: (ref) => channels.get(ref),
|
|
621
|
+
removeMember: (id) => {
|
|
622
|
+
members.delete(id);
|
|
623
|
+
}
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
/**
|
|
627
|
+
* The runtime's reading of `RouteResponse`: an object whose only keys are `status` (number),
|
|
628
|
+
* `body` and `headers` is a response envelope; anything else is a 200 JSON body.
|
|
629
|
+
*/
|
|
630
|
+
function normalizeRouteResponse(response) {
|
|
631
|
+
if (response !== null && typeof response === "object" && !Array.isArray(response) && typeof response.status === "number" && Object.keys(response).every((k) => k === "status" || k === "body" || k === "headers")) {
|
|
632
|
+
const env = response;
|
|
633
|
+
return {
|
|
634
|
+
status: env.status,
|
|
635
|
+
body: env.body,
|
|
636
|
+
headers: env.headers ?? {}
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
if (response === void 0) return {
|
|
640
|
+
status: 204,
|
|
641
|
+
body: void 0,
|
|
642
|
+
headers: {}
|
|
643
|
+
};
|
|
644
|
+
return {
|
|
645
|
+
status: 200,
|
|
646
|
+
body: response,
|
|
647
|
+
headers: {}
|
|
648
|
+
};
|
|
649
|
+
}
|
|
650
|
+
/**
|
|
651
|
+
* Calls a plugin route like the runtime does. `route` is `"<METHOD> <path>"`; the path may
|
|
652
|
+
* be concrete (`"POST /answers/42"`) and is matched against declared patterns (`/answers/:id`).
|
|
653
|
+
* Route `access` is checked: anonymous viewers get 401 unless the route is public.
|
|
654
|
+
*/
|
|
655
|
+
async function callRoute(plugin, harness, route, call = {}) {
|
|
656
|
+
const [method = "", rawPath = "/"] = route.trim().split(/\s+/, 2);
|
|
657
|
+
const [path = "/", search = ""] = rawPath.split("?", 2);
|
|
658
|
+
const query = {
|
|
659
|
+
...Object.fromEntries(new URLSearchParams(search)),
|
|
660
|
+
...call.query
|
|
661
|
+
};
|
|
662
|
+
for (const [key, definition] of Object.entries(plugin.routes ?? {})) {
|
|
663
|
+
if (!definition) continue;
|
|
664
|
+
const [m = "", pattern = ""] = key.split(" ", 2);
|
|
665
|
+
if (m !== method.toUpperCase()) continue;
|
|
666
|
+
const params = matchPath(pattern, path);
|
|
667
|
+
if (!params) continue;
|
|
668
|
+
let viewer;
|
|
669
|
+
if (call.viewer !== void 0) {
|
|
670
|
+
const member = harness.member(call.viewer);
|
|
671
|
+
viewer = member ? {
|
|
672
|
+
user: member.user,
|
|
673
|
+
member
|
|
674
|
+
} : { user: makeUser({ id: call.viewer }) };
|
|
675
|
+
}
|
|
676
|
+
if (definition.access !== "public" && !viewer) return {
|
|
677
|
+
status: 401,
|
|
678
|
+
body: { error: {
|
|
679
|
+
code: "unauthenticated",
|
|
680
|
+
message: "login required"
|
|
681
|
+
} },
|
|
682
|
+
headers: {}
|
|
683
|
+
};
|
|
684
|
+
if (definition.access === "member" && !viewer?.member) return {
|
|
685
|
+
status: 403,
|
|
686
|
+
body: { error: {
|
|
687
|
+
code: "forbidden",
|
|
688
|
+
message: "members only"
|
|
689
|
+
} },
|
|
690
|
+
headers: {}
|
|
691
|
+
};
|
|
692
|
+
return normalizeRouteResponse(await definition.handler(harness.ctx, {
|
|
693
|
+
params,
|
|
694
|
+
query,
|
|
695
|
+
body: call.body,
|
|
696
|
+
...viewer ? { viewer } : {}
|
|
697
|
+
}));
|
|
698
|
+
}
|
|
699
|
+
return {
|
|
700
|
+
status: 404,
|
|
701
|
+
body: { error: {
|
|
702
|
+
code: "not_found",
|
|
703
|
+
message: `no route ${method} ${path}`
|
|
704
|
+
} },
|
|
705
|
+
headers: {}
|
|
706
|
+
};
|
|
707
|
+
}
|
|
708
|
+
function matchPath(pattern, path) {
|
|
709
|
+
const p = pattern.split("/").filter(Boolean);
|
|
710
|
+
const s = path.split("/").filter(Boolean);
|
|
711
|
+
if (p.length !== s.length) return void 0;
|
|
712
|
+
const params = {};
|
|
713
|
+
for (let i = 0; i < p.length; i++) {
|
|
714
|
+
const seg = p[i];
|
|
715
|
+
const val = s[i];
|
|
716
|
+
if (seg.startsWith(":")) params[seg.slice(1)] = decodeURIComponent(val);
|
|
717
|
+
else if (seg !== val) return void 0;
|
|
718
|
+
}
|
|
719
|
+
return params;
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* A recording interaction following the runtime's rules (docs/plugins.md, "Interactions"):
|
|
723
|
+
* `reply()` once (or after a deferral), then `followUp()`; `showModal()` first; `update()`
|
|
724
|
+
* for components only.
|
|
725
|
+
*/
|
|
726
|
+
function fakeInteraction(harness, kind, id, call, result) {
|
|
727
|
+
const member = harness.member(call.user);
|
|
728
|
+
const user = member?.user ?? makeUser({ id: call.user });
|
|
729
|
+
const channel = call.channel !== void 0 ? harness.channel(call.channel) : void 0;
|
|
730
|
+
if (call.channel !== void 0 && !channel) throw new Error(`unknown channel ${JSON.stringify(call.channel)} for the interaction`);
|
|
731
|
+
let phase = "none";
|
|
732
|
+
let deferredUpdate = false;
|
|
733
|
+
const known = (candidate) => {
|
|
734
|
+
if (harness.member(candidate)) return true;
|
|
735
|
+
try {
|
|
736
|
+
harness.ctx.server.role({ id: candidate });
|
|
737
|
+
return true;
|
|
738
|
+
} catch {
|
|
739
|
+
return false;
|
|
740
|
+
}
|
|
741
|
+
};
|
|
742
|
+
const checkMentions = (message) => {
|
|
743
|
+
normalizeAllowedMentions(message, known);
|
|
744
|
+
};
|
|
745
|
+
const followUp = async (message) => {
|
|
746
|
+
if (phase === "none") throw new Error("followUp(): the interaction has not been answered yet");
|
|
747
|
+
checkMentions(message);
|
|
748
|
+
result.followUps.push(message);
|
|
749
|
+
return {
|
|
750
|
+
id: `followup-${result.followUps.length}`,
|
|
751
|
+
content: typeof message === "string" ? message : message.content ?? "",
|
|
752
|
+
author: harness.ctx.bot.user,
|
|
753
|
+
channel: channel ?? {
|
|
754
|
+
id: "interaction-channel",
|
|
755
|
+
name: "interaction",
|
|
756
|
+
type: "text",
|
|
757
|
+
mention: "<#interaction-channel>",
|
|
758
|
+
send: async () => {
|
|
759
|
+
throw new Error("not supported in tests: pass `channel` in the call");
|
|
760
|
+
},
|
|
761
|
+
messages: async () => [],
|
|
762
|
+
message: async () => void 0,
|
|
763
|
+
createThread: async () => {
|
|
764
|
+
throw new Error("not supported in tests: pass `channel` in the call");
|
|
765
|
+
}
|
|
766
|
+
},
|
|
767
|
+
attachments: [],
|
|
768
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
769
|
+
reply: async () => {
|
|
770
|
+
throw new Error("not supported in tests: pass `channel` in the call");
|
|
771
|
+
},
|
|
772
|
+
edit: async () => {
|
|
773
|
+
throw new Error("not supported in tests: pass `channel` in the call");
|
|
774
|
+
},
|
|
775
|
+
delete: async () => {},
|
|
776
|
+
react: async () => {}
|
|
777
|
+
};
|
|
778
|
+
};
|
|
779
|
+
return {
|
|
780
|
+
id: `interaction-${kind}-${id}`,
|
|
781
|
+
user,
|
|
782
|
+
...member ? { member } : {},
|
|
783
|
+
...channel ? { channel } : {},
|
|
784
|
+
get replied() {
|
|
785
|
+
return phase === "replied" || phase === "updated" || phase === "modal";
|
|
786
|
+
},
|
|
787
|
+
get deferred() {
|
|
788
|
+
return phase === "deferred";
|
|
789
|
+
},
|
|
790
|
+
async reply(message) {
|
|
791
|
+
if (phase === "replied" || phase === "modal") throw new Error("reply(): the interaction was already answered: use followUp()");
|
|
792
|
+
if (phase === "updated" || phase === "deferred" && deferredUpdate) {
|
|
793
|
+
await followUp(message);
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
checkMentions(message);
|
|
797
|
+
phase = "replied";
|
|
798
|
+
result.replies.push(message);
|
|
799
|
+
},
|
|
800
|
+
async defer(opts) {
|
|
801
|
+
if (phase === "deferred") return;
|
|
802
|
+
if (phase !== "none") throw new Error("defer(): the interaction was already answered");
|
|
803
|
+
phase = "deferred";
|
|
804
|
+
deferredUpdate = kind === "component" && opts?.ephemeral === void 0;
|
|
805
|
+
result.deferred = opts ?? {};
|
|
806
|
+
},
|
|
807
|
+
followUp,
|
|
808
|
+
async showModal(modal) {
|
|
809
|
+
if (kind === "modal") throw new Error("showModal(): a modal cannot open another modal");
|
|
810
|
+
if (phase !== "none") throw new Error("showModal(): must be the first response");
|
|
811
|
+
phase = "modal";
|
|
812
|
+
result.modal = modal;
|
|
813
|
+
},
|
|
814
|
+
async update(message) {
|
|
815
|
+
if (kind !== "component") throw new Error("update(): only for component interactions");
|
|
816
|
+
if (phase === "replied" || phase === "modal" || phase === "deferred" && !deferredUpdate) throw new Error("update(): the interaction was already answered");
|
|
817
|
+
checkMentions(message);
|
|
818
|
+
phase = "updated";
|
|
819
|
+
result.updates.push(message);
|
|
820
|
+
}
|
|
821
|
+
};
|
|
822
|
+
}
|
|
823
|
+
const emptyResult = () => ({
|
|
824
|
+
replies: [],
|
|
825
|
+
followUps: [],
|
|
826
|
+
updates: [],
|
|
827
|
+
deferred: void 0,
|
|
828
|
+
modal: void 0
|
|
829
|
+
});
|
|
830
|
+
/** Like the runtime: the full local id, then the part before the first ":" (`"vote:42"` → `vote`). */
|
|
831
|
+
function lookup(table, id) {
|
|
832
|
+
if (!table) return void 0;
|
|
833
|
+
if (Object.hasOwn(table, id)) return table[id];
|
|
834
|
+
const i = id.indexOf(":");
|
|
835
|
+
return i > 0 && Object.hasOwn(table, id.slice(0, i)) ? table[id.slice(0, i)] : void 0;
|
|
836
|
+
}
|
|
837
|
+
/**
|
|
838
|
+
* Like the runtime: resolves a command path ("poll", "polls close", "polls admin purge") to
|
|
839
|
+
* the command or subcommand that runs.
|
|
840
|
+
*/
|
|
841
|
+
function resolveCommand(plugin, path, caller) {
|
|
842
|
+
const [command = "", ...rest] = path.trim().split(/\s+/);
|
|
843
|
+
const c = plugin.commands && Object.hasOwn(plugin.commands, command) ? plugin.commands[command] : void 0;
|
|
844
|
+
if (!c) throw new Error(`${caller}: no command "${command}"`);
|
|
845
|
+
const withSubs = c;
|
|
846
|
+
const hasSubs = withSubs.subcommands !== void 0 || withSubs.groups !== void 0;
|
|
847
|
+
if (rest.length === 0) {
|
|
848
|
+
if (hasSubs) throw new Error(`${caller}: command "${command}" needs a subcommand ("${command} <subcommand>")`);
|
|
849
|
+
return {
|
|
850
|
+
command,
|
|
851
|
+
definition: c
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
const own = (table, key) => table && Object.hasOwn(table, key) ? table[key] : void 0;
|
|
855
|
+
if (rest.length === 1) {
|
|
856
|
+
const sub = own(withSubs.subcommands, rest[0]);
|
|
857
|
+
if (!sub) throw new Error(`${caller}: command "${command}" has no subcommand "${rest[0]}"`);
|
|
858
|
+
return {
|
|
859
|
+
command,
|
|
860
|
+
subcommand: rest[0],
|
|
861
|
+
definition: sub
|
|
862
|
+
};
|
|
863
|
+
}
|
|
864
|
+
const group = own(withSubs.groups, rest[0]);
|
|
865
|
+
const sub = rest.length === 2 ? own(group?.subcommands, rest[1]) : void 0;
|
|
866
|
+
if (!sub) throw new Error(`${caller}: no subcommand "${path}"`);
|
|
867
|
+
return {
|
|
868
|
+
command,
|
|
869
|
+
group: rest[0],
|
|
870
|
+
subcommand: rest[1],
|
|
871
|
+
definition: sub
|
|
872
|
+
};
|
|
873
|
+
}
|
|
874
|
+
/**
|
|
875
|
+
* Runs a slash command handler with a recording fake interaction. `path` is the command
|
|
876
|
+
* name, or the subcommand path for commands with subcommands: `"polls close"`,
|
|
877
|
+
* `"polls admin purge"` (`interaction.subcommand` / `interaction.group` are set).
|
|
878
|
+
*/
|
|
879
|
+
async function runCommand(plugin, harness, path, call) {
|
|
880
|
+
const leaf = resolveCommand(plugin, path, "runCommand");
|
|
881
|
+
const result = emptyResult();
|
|
882
|
+
const base = fakeInteraction(harness, "command", path, call, result);
|
|
883
|
+
const { update: _update, ...rest } = base;
|
|
884
|
+
const interaction = Object.defineProperties({
|
|
885
|
+
...rest,
|
|
886
|
+
command: leaf.command,
|
|
887
|
+
...leaf.group ? { group: leaf.group } : {},
|
|
888
|
+
...leaf.subcommand ? { subcommand: leaf.subcommand } : {},
|
|
889
|
+
options: call.options ?? {}
|
|
890
|
+
}, {
|
|
891
|
+
replied: { get: () => base.replied },
|
|
892
|
+
deferred: { get: () => base.deferred }
|
|
893
|
+
});
|
|
894
|
+
await leaf.definition.run(harness.ctx, interaction);
|
|
895
|
+
return result;
|
|
896
|
+
}
|
|
897
|
+
/** Length in Unicode code points, like Discord (and the runtime) count characters. */
|
|
898
|
+
function codePoints(s) {
|
|
899
|
+
let n = 0;
|
|
900
|
+
for (const _ of s) n++;
|
|
901
|
+
return n;
|
|
902
|
+
}
|
|
903
|
+
/**
|
|
904
|
+
* Runs the `autocomplete` handler of an option like the runtime does and returns the
|
|
905
|
+
* choices. The result is checked like the runtime checks it (at most 25 choices, names of
|
|
906
|
+
* 1–100 characters, values of the option's type): an invalid result throws.
|
|
907
|
+
*/
|
|
908
|
+
async function runAutocomplete(plugin, harness, path, call) {
|
|
909
|
+
const leaf = resolveCommand(plugin, path, "runAutocomplete");
|
|
910
|
+
const option = leaf.definition.options?.[call.focused];
|
|
911
|
+
if (!option?.autocomplete) throw new Error(`runAutocomplete: option "${call.focused}" of /${path} has no autocomplete`);
|
|
912
|
+
const member = harness.member(call.user);
|
|
913
|
+
const channel = call.channel !== void 0 ? harness.channel(call.channel) : void 0;
|
|
914
|
+
if (call.channel !== void 0 && !channel) throw new Error(`unknown channel ${JSON.stringify(call.channel)} for the interaction`);
|
|
915
|
+
const interaction = {
|
|
916
|
+
id: `interaction-autocomplete-${path}`,
|
|
917
|
+
user: member?.user ?? makeUser({ id: call.user }),
|
|
918
|
+
...member ? { member } : {},
|
|
919
|
+
...channel ? { channel } : {},
|
|
920
|
+
command: leaf.command,
|
|
921
|
+
...leaf.group ? { group: leaf.group } : {},
|
|
922
|
+
...leaf.subcommand ? { subcommand: leaf.subcommand } : {},
|
|
923
|
+
options: { ...call.options }
|
|
924
|
+
};
|
|
925
|
+
const out = [...await option.autocomplete(harness.ctx, interaction, {
|
|
926
|
+
name: call.focused,
|
|
927
|
+
value: call.value ?? ""
|
|
928
|
+
}) ?? []];
|
|
929
|
+
if (out.length > 25) throw new Error(`autocomplete returned ${out.length} choices (at most 25)`);
|
|
930
|
+
for (const c of out) {
|
|
931
|
+
if (typeof c?.name !== "string" || c.name.length < 1 || codePoints(c.name) > 100) throw new Error("autocomplete choice: name must be 1-100 characters");
|
|
932
|
+
if (!(option.type === "string" ? typeof c.value === "string" && codePoints(c.value) <= 100 : typeof c.value === "number" && (option.type !== "integer" || Number.isInteger(c.value)))) throw new Error(`autocomplete choice "${c.name}": value must be a ${option.type}`);
|
|
933
|
+
}
|
|
934
|
+
return out;
|
|
935
|
+
}
|
|
936
|
+
/**
|
|
937
|
+
* Runs the component handler for a local component id (`"vote:42"` is routed to
|
|
938
|
+
* `components.vote`, `componentId` stays `"vote:42"`).
|
|
939
|
+
*/
|
|
940
|
+
async function runComponent(plugin, harness, componentId, call) {
|
|
941
|
+
const handler = lookup(plugin.components, componentId);
|
|
942
|
+
if (!handler) throw new Error(`runComponent: no component handler for "${componentId}"`);
|
|
943
|
+
const message = typeof call.message === "string" ? harness.message(call.message) : call.message;
|
|
944
|
+
if (call.message !== void 0 && !message) throw new Error(`runComponent: unknown message ${JSON.stringify(call.message)}`);
|
|
945
|
+
const result = emptyResult();
|
|
946
|
+
const base = fakeInteraction(harness, "component", componentId, {
|
|
947
|
+
...call,
|
|
948
|
+
...call.channel === void 0 && message ? { channel: message.channel.id } : {}
|
|
949
|
+
}, result);
|
|
950
|
+
const interaction = Object.defineProperties({
|
|
951
|
+
...base,
|
|
952
|
+
componentId,
|
|
953
|
+
values: [...call.values ?? []],
|
|
954
|
+
...message ? { message } : {}
|
|
955
|
+
}, {
|
|
956
|
+
replied: { get: () => base.replied },
|
|
957
|
+
deferred: { get: () => base.deferred }
|
|
958
|
+
});
|
|
959
|
+
await handler(harness.ctx, interaction);
|
|
960
|
+
return result;
|
|
961
|
+
}
|
|
962
|
+
/** Runs the modal submit handler for a modal id (same id fallback as components). */
|
|
963
|
+
async function submitModal(plugin, harness, modalId, call) {
|
|
964
|
+
const handler = lookup(plugin.modals, modalId);
|
|
965
|
+
if (!handler) throw new Error(`submitModal: no modal handler for "${modalId}"`);
|
|
966
|
+
const result = emptyResult();
|
|
967
|
+
const base = fakeInteraction(harness, "modal", modalId, call, result);
|
|
968
|
+
const { update: _update, ...rest } = base;
|
|
969
|
+
const interaction = Object.defineProperties({
|
|
970
|
+
...rest,
|
|
971
|
+
modalId,
|
|
972
|
+
fields: { ...call.fields }
|
|
973
|
+
}, {
|
|
974
|
+
replied: { get: () => base.replied },
|
|
975
|
+
deferred: { get: () => base.deferred }
|
|
976
|
+
});
|
|
977
|
+
await handler(harness.ctx, interaction);
|
|
978
|
+
return result;
|
|
979
|
+
}
|
|
980
|
+
export { applyDefaults, callRoute, capabilityError, createTestContext, normalizeAllowedMentions, normalizeRouteResponse, runAutocomplete, runCommand, runComponent, submitModal };
|
|
981
|
+
|
|
982
|
+
//# sourceMappingURL=testing.mjs.map
|