micup.ts 0.0.0-stage → 1.0.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.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +79 -2
  3. package/dist/events/mux.d.ts +82 -0
  4. package/dist/events/mux.js +23 -0
  5. package/dist/events/router.d.ts +11 -0
  6. package/dist/events/router.js +54 -0
  7. package/dist/gateway/connection.d.ts +30 -0
  8. package/dist/gateway/connection.js +272 -0
  9. package/dist/gateway/protocol.d.ts +40 -0
  10. package/dist/gateway/protocol.js +59 -0
  11. package/dist/index.d.ts +29 -0
  12. package/dist/index.js +12 -0
  13. package/dist/model/guild.d.ts +69 -0
  14. package/dist/model/guild.js +1 -0
  15. package/dist/model/interaction.d.ts +137 -0
  16. package/dist/model/interaction.js +18 -0
  17. package/dist/model/permissions.d.ts +47 -0
  18. package/dist/model/permissions.js +81 -0
  19. package/dist/model/presence.d.ts +16 -0
  20. package/dist/model/presence.js +30 -0
  21. package/dist/rest/channels.d.ts +82 -0
  22. package/dist/rest/channels.js +68 -0
  23. package/dist/rest/client.d.ts +48 -0
  24. package/dist/rest/client.js +151 -0
  25. package/dist/rest/commands.d.ts +18 -0
  26. package/dist/rest/commands.js +94 -0
  27. package/dist/rest/errors.d.ts +24 -0
  28. package/dist/rest/errors.js +26 -0
  29. package/dist/rest/guilds.d.ts +76 -0
  30. package/dist/rest/guilds.js +90 -0
  31. package/dist/rest/interactions.d.ts +30 -0
  32. package/dist/rest/interactions.js +79 -0
  33. package/dist/rest/messages.d.ts +65 -0
  34. package/dist/rest/messages.js +38 -0
  35. package/dist/rest/transport.d.ts +16 -0
  36. package/dist/rest/transport.js +154 -0
  37. package/dist/session/requests.d.ts +39 -0
  38. package/dist/session/requests.js +144 -0
  39. package/dist/session/session.d.ts +63 -0
  40. package/dist/session/session.js +193 -0
  41. package/dist/session/voice.d.ts +41 -0
  42. package/dist/session/voice.js +168 -0
  43. package/dist/shard/manager.d.ts +20 -0
  44. package/dist/shard/manager.js +93 -0
  45. package/dist/state/cache.d.ts +15 -0
  46. package/dist/state/cache.js +257 -0
  47. package/package.json +39 -4
@@ -0,0 +1,151 @@
1
+ import { GatewaySession } from '../session/session.js';
2
+ import { ShardManager } from '../shard/manager.js';
3
+ import { MicupAPIError } from './errors.js';
4
+ import { RestTransport } from './transport.js';
5
+ import { messageBody, messageQuery, messagesPath, snowflake } from './messages.js';
6
+ import { MicupCommands } from './commands.js';
7
+ import { MicupInteractions } from './interactions.js';
8
+ import { MicupGuilds } from './guilds.js';
9
+ import { MicupChannels } from './channels.js';
10
+ const defaultOrigin = 'https://micup.gg';
11
+ const connection = Symbol('Micup connection');
12
+ export class MicupClient {
13
+ #token;
14
+ #rest;
15
+ #gateway;
16
+ #botId;
17
+ #commands;
18
+ interactions;
19
+ guilds;
20
+ channels;
21
+ constructor(key, token, api, gateway, maxAttempts) {
22
+ if (key !== connection) {
23
+ throw new TypeError('Use MicupClient.connect() to create a client');
24
+ }
25
+ this.#token = token;
26
+ this.#rest = new RestTransport(api, token, maxAttempts);
27
+ this.interactions = new MicupInteractions(this.#rest);
28
+ this.guilds = new MicupGuilds(this.#rest);
29
+ this.channels = new MicupChannels(this.#rest);
30
+ this.#gateway = gateway;
31
+ }
32
+ static async connect({ token, origin = defaultOrigin, maxRestAttempts }, { signal } = {}) {
33
+ if (typeof token !== 'string' || !/^[\x21-\x7E]+$/.test(token)) {
34
+ throw new TypeError('A valid Micup bot token is required');
35
+ }
36
+ const url = new URL(origin);
37
+ if (url.protocol !== 'https:' || url.username || url.password ||
38
+ url.pathname !== '/' || url.search || url.hash) {
39
+ throw new TypeError('Micup origin must be an HTTPS origin');
40
+ }
41
+ const response = await fetch(new URL('/.well-known/fluxer', url), {
42
+ redirect: 'error',
43
+ signal,
44
+ });
45
+ if (!response.ok) {
46
+ await response.body?.cancel();
47
+ throw new MicupAPIError(response);
48
+ }
49
+ const discovery = await response.json();
50
+ const endpoint = discovery?.endpoints?.api_public;
51
+ if (typeof endpoint !== 'string') {
52
+ throw new Error('Micup discovery returned no API endpoint');
53
+ }
54
+ const api = new URL(endpoint);
55
+ if (api.origin !== url.origin || api.username || api.password || api.search || api.hash) {
56
+ throw new Error('Micup discovery returned an invalid API endpoint');
57
+ }
58
+ const gateway = discovery.endpoints?.gateway;
59
+ if (gateway !== undefined) {
60
+ if (typeof gateway !== 'string')
61
+ throw new Error('Micup discovery returned an invalid Gateway endpoint');
62
+ const endpoint = new URL(gateway);
63
+ if (endpoint.protocol !== 'wss:' || endpoint.host !== url.host || endpoint.username ||
64
+ endpoint.password || endpoint.hash) {
65
+ throw new Error('Micup discovery returned an invalid Gateway endpoint');
66
+ }
67
+ }
68
+ const client = new MicupClient(connection, token, `${api.href.replace(/\/+$/, '')}/v1`, gateway, maxRestAttempts);
69
+ const user = await client.getCurrentUser({ signal });
70
+ if (user?.bot !== true) {
71
+ throw new Error('The credential must belong to a Micup bot');
72
+ }
73
+ client.#botId = user.id;
74
+ return client;
75
+ }
76
+ get commands() {
77
+ if (!this.#botId)
78
+ throw new Error('Micup did not return the bot ID');
79
+ return this.#commands ??= new MicupCommands(this.#rest, this.#botId);
80
+ }
81
+ newSession(options, shard = {}) {
82
+ if (!this.#gateway)
83
+ throw new Error('Micup discovery returned no Gateway endpoint');
84
+ return new GatewaySession({ ...shard, endpoint: this.#gateway, token: this.#token, botId: this.#botId }, options);
85
+ }
86
+ newShardManager(options) {
87
+ if (!this.#gateway)
88
+ throw new Error('Micup discovery returned no Gateway endpoint');
89
+ return new ShardManager({ endpoint: this.#gateway, token: this.#token, botId: this.#botId }, options);
90
+ }
91
+ getCurrentUser({ signal } = {}) {
92
+ return this.request('GET', '/users/@me', { signal });
93
+ }
94
+ sendMessage(channelId, content, { replyTo, signal } = {}) {
95
+ const path = messagesPath(channelId);
96
+ const input = typeof content === 'string' ? { content } : content;
97
+ if (!input?.content?.trim() && !input?.embeds?.length && !input?.components?.length &&
98
+ !input?.files?.length && !input?.attachments?.length) {
99
+ throw new TypeError('Message content, embeds, components or attachments are required');
100
+ }
101
+ const reply = replyTo === undefined ? undefined : { message_id: snowflake(replyTo, 'Reply message ID'), channel_id: channelId };
102
+ return this.request('POST', path, { body: messageBody(input, reply), signal });
103
+ }
104
+ getMessage(channelId, messageId, options) {
105
+ return this.request('GET', messagesPath(channelId, messageId), options);
106
+ }
107
+ listMessages(channelId, options = {}) {
108
+ return this.request('GET', messagesPath(channelId), { query: messageQuery(options), signal: options.signal });
109
+ }
110
+ async *iterateMessages(channelId, options = {}) {
111
+ if (options.before !== undefined && options.after !== undefined)
112
+ throw new TypeError('Only one message cursor can be used');
113
+ let cursor = options.after ?? options.before;
114
+ const forward = options.after !== undefined;
115
+ while (true) {
116
+ const page = await this.listMessages(channelId, {
117
+ ...(forward ? { after: cursor } : { before: cursor }), limit: 100, signal: options.signal,
118
+ });
119
+ if (!page.length)
120
+ return;
121
+ page.sort((a, b) => {
122
+ const x = BigInt(a.id);
123
+ const y = BigInt(b.id);
124
+ if (x === y)
125
+ return 0;
126
+ return (x < y) === forward ? -1 : 1;
127
+ });
128
+ for (const message of page) {
129
+ if (cursor === undefined || (forward ? BigInt(message.id) > BigInt(cursor) : BigInt(message.id) < BigInt(cursor))) {
130
+ yield message;
131
+ }
132
+ }
133
+ const next = page.at(-1).id;
134
+ if (page.length < 100 || next === cursor || (cursor !== undefined && (forward ? BigInt(next) <= BigInt(cursor) : BigInt(next) >= BigInt(cursor))))
135
+ return;
136
+ cursor = next;
137
+ }
138
+ }
139
+ editMessage(channelId, messageId, edit, options) {
140
+ return this.request('PATCH', messagesPath(channelId, messageId), { ...options, body: messageBody(edit) });
141
+ }
142
+ deleteMessage(channelId, messageId, options) {
143
+ return this.request('DELETE', messagesPath(channelId, messageId), options);
144
+ }
145
+ triggerTyping(channelId, options) {
146
+ return this.request('POST', '/channels/' + snowflake(channelId, 'Channel ID') + '/typing', options);
147
+ }
148
+ request(method, path, options) {
149
+ return this.#rest.request(method, path, options);
150
+ }
151
+ }
@@ -0,0 +1,18 @@
1
+ import { type CommandDefinition, type MicupCommand } from '../model/interaction.js';
2
+ import type { MicupRequestOptions, RestTransport } from './transport.js';
3
+ export interface CommandScope extends MicupRequestOptions {
4
+ guildId?: string;
5
+ applicationId?: string;
6
+ }
7
+ export declare class MicupCommands {
8
+ #private;
9
+ private readonly rest;
10
+ private readonly botId;
11
+ constructor(rest: RestTransport, botId: string);
12
+ list(scope?: CommandScope): Promise<MicupCommand[]>;
13
+ get(id: string, scope?: CommandScope): Promise<MicupCommand>;
14
+ create(command: CommandDefinition, scope?: CommandScope): Promise<MicupCommand>;
15
+ edit(id: string, command: Partial<CommandDefinition>, scope?: CommandScope): Promise<MicupCommand>;
16
+ delete(id: string, scope?: CommandScope): Promise<void>;
17
+ set(commands: readonly CommandDefinition[], scope?: CommandScope): Promise<MicupCommand[]>;
18
+ }
@@ -0,0 +1,94 @@
1
+ import { CommandType } from '../model/interaction.js';
2
+ import { snowflake } from './messages.js';
3
+ const chatName = /^[-_\p{Ll}\p{Lo}\p{N}]{1,32}$/u;
4
+ const lengthWithin = (value, limit) => Boolean(value && [...value].length <= limit);
5
+ function validateOptions(options, depth, group = false) {
6
+ if (options.length > 25)
7
+ throw new RangeError('A command can contain at most 25 options per level');
8
+ const names = new Set();
9
+ let optional = false;
10
+ const nested = options.some((option) => option.type === 1 || option.type === 2);
11
+ for (const option of options) {
12
+ const structural = option.type === 1 || option.type === 2;
13
+ if (!chatName.test(option.name) || names.has(option.name) || !lengthWithin(option.description, 100)) {
14
+ throw new TypeError('Invalid or duplicate Micup command option: ' + option.name);
15
+ }
16
+ names.add(option.name);
17
+ if (!Number.isInteger(option.type) || option.type < 1 || option.type > 11 ||
18
+ (nested && !structural) || (group && option.type !== 1)) {
19
+ throw new TypeError('Invalid Micup option structure');
20
+ }
21
+ if (structural) {
22
+ if (option.required || (option.type === 2 ? depth !== 0 || !option.options?.length : depth > 1) ||
23
+ (depth > 0 && !group))
24
+ throw new TypeError('Invalid nested Micup command');
25
+ validateOptions(option.options ?? [], depth + 1, option.type === 2);
26
+ continue;
27
+ }
28
+ if (option.options?.length || (option.required && optional) ||
29
+ (option.choices?.length ?? 0) > 25 || (option.autocomplete && option.choices?.length)) {
30
+ throw new TypeError('Invalid Micup command option ordering or choices');
31
+ }
32
+ if (option.autocomplete || option.choices?.length) {
33
+ if (![3, 4, 10].includes(option.type))
34
+ throw new TypeError('Invalid Micup choice or autocomplete option type');
35
+ for (const choice of option.choices ?? []) {
36
+ const validValue = option.type === 3
37
+ ? typeof choice.value === 'string' && lengthWithin(choice.value, 100)
38
+ : typeof choice.value === 'number' && Number.isFinite(choice.value) &&
39
+ (option.type !== 4 || Number.isSafeInteger(choice.value));
40
+ if (!lengthWithin(choice.name, 100) || !validValue)
41
+ throw new TypeError('Invalid Micup command choice');
42
+ }
43
+ }
44
+ if (!option.required)
45
+ optional = true;
46
+ }
47
+ }
48
+ function commandBody(command) {
49
+ const type = command.type ?? CommandType.ChatInput;
50
+ const { name, description, options, name_localizations, description_localizations, default_member_permissions, dm_permission } = command;
51
+ if (type === CommandType.ChatInput) {
52
+ if (!chatName.test(name) || !lengthWithin(description, 100))
53
+ throw new TypeError('Invalid Micup command name or description');
54
+ validateOptions(options ?? [], 0);
55
+ }
56
+ else if ((type !== CommandType.User && type !== CommandType.Message) ||
57
+ !lengthWithin(name, 32) || description || options?.length) {
58
+ throw new TypeError('Invalid Micup context menu command');
59
+ }
60
+ return { type, name, description, options, name_localizations, description_localizations, default_member_permissions, dm_permission };
61
+ }
62
+ export class MicupCommands {
63
+ rest;
64
+ botId;
65
+ constructor(rest, botId) {
66
+ this.rest = rest;
67
+ this.botId = botId;
68
+ }
69
+ #path({ guildId, applicationId = this.botId }, commandId) {
70
+ const application = '/applications/' + snowflake(applicationId, 'Application ID');
71
+ const scope = guildId === undefined ? application : application + '/guilds/' + snowflake(guildId, 'Guild ID');
72
+ return scope + '/commands' + (commandId === undefined ? '' : '/' + snowflake(commandId, 'Command ID'));
73
+ }
74
+ list(scope = {}) {
75
+ return this.rest.request('GET', this.#path(scope), scope);
76
+ }
77
+ get(id, scope = {}) {
78
+ return this.rest.request('GET', this.#path(scope, id), scope);
79
+ }
80
+ create(command, scope = {}) {
81
+ return this.rest.request('POST', this.#path(scope), { ...scope, body: commandBody(command) });
82
+ }
83
+ edit(id, command, scope = {}) {
84
+ return this.rest.request('PATCH', this.#path(scope, id), { ...scope, body: command });
85
+ }
86
+ delete(id, scope = {}) {
87
+ return this.rest.request('DELETE', this.#path(scope, id), scope);
88
+ }
89
+ set(commands, scope = {}) {
90
+ if (commands.length > 100)
91
+ throw new RangeError('Micup accepts up to 100 commands per scope');
92
+ return this.rest.request('PUT', this.#path(scope), { ...scope, body: commands.map(commandBody) });
93
+ }
94
+ }
@@ -0,0 +1,24 @@
1
+ export interface MicupFieldError {
2
+ path: string;
3
+ code: string;
4
+ message: string;
5
+ }
6
+ interface APIErrorBody {
7
+ message?: unknown;
8
+ code?: unknown;
9
+ errors?: MicupFieldError[];
10
+ retry_after?: unknown;
11
+ global?: unknown;
12
+ }
13
+ export declare function retryDelay(value: unknown): number;
14
+ export declare class MicupAPIError extends Error {
15
+ readonly status: number;
16
+ readonly code?: string;
17
+ readonly retryAfter: string | null;
18
+ readonly retryAfterMs: number;
19
+ readonly requestId: string | null;
20
+ readonly global: boolean;
21
+ readonly errors: readonly MicupFieldError[];
22
+ constructor(response: Response, body?: APIErrorBody);
23
+ }
24
+ export {};
@@ -0,0 +1,26 @@
1
+ export function retryDelay(value) {
2
+ if (typeof value !== 'number' && typeof value !== 'string')
3
+ return 0;
4
+ const seconds = Number(value);
5
+ return Number.isFinite(seconds) && seconds > 0 ? Math.min(2_147_483_647, Math.ceil(seconds * 1000)) : 0;
6
+ }
7
+ export class MicupAPIError extends Error {
8
+ status;
9
+ code;
10
+ retryAfter;
11
+ retryAfterMs;
12
+ requestId;
13
+ global;
14
+ errors;
15
+ constructor(response, body) {
16
+ super(typeof body?.message === 'string' ? body.message : 'Micup API returned HTTP ' + response.status);
17
+ this.name = 'MicupAPIError';
18
+ this.status = response.status;
19
+ this.code = typeof body?.code === 'string' ? body.code : undefined;
20
+ this.retryAfter = response.headers.get('retry-after');
21
+ this.retryAfterMs = retryDelay(body?.retry_after) || retryDelay(this.retryAfter);
22
+ this.requestId = response.headers.get('x-request-id');
23
+ this.global = body?.global === true || response.headers.get('x-ratelimit-global') === 'true';
24
+ this.errors = Array.isArray(body?.errors) ? body.errors : [];
25
+ }
26
+ }
@@ -0,0 +1,76 @@
1
+ import type { MicupChannel, MicupGuild, MicupMember, MicupRole } from '../model/guild.js';
2
+ import type { MicupUser } from './client.js';
3
+ import type { MicupRequestOptions, RestTransport } from './transport.js';
4
+ export interface AuditOptions extends MicupRequestOptions {
5
+ reason?: string;
6
+ }
7
+ export interface GuildMemberQuery extends MicupRequestOptions {
8
+ limit?: number;
9
+ after?: string;
10
+ }
11
+ export interface GuildMemberEdit {
12
+ nick?: string | null;
13
+ roles?: readonly string[];
14
+ mute?: boolean;
15
+ deaf?: boolean;
16
+ communication_disabled_until?: string | null;
17
+ channel_id?: string | null;
18
+ }
19
+ export interface GuildRoleEdit {
20
+ name?: string;
21
+ permissions?: bigint | string;
22
+ color?: number;
23
+ hoist?: boolean;
24
+ mentionable?: boolean;
25
+ icon?: string | null;
26
+ unicode_emoji?: string | null;
27
+ }
28
+ export interface GuildBanInput {
29
+ delete_message_seconds?: number;
30
+ ban_duration_seconds?: number;
31
+ reason?: string;
32
+ }
33
+ export interface GuildBan {
34
+ user: MicupUser;
35
+ reason: string | null;
36
+ moderator_id?: string;
37
+ banned_at?: string;
38
+ expires_at?: string | null;
39
+ }
40
+ export interface GuildAuditLog {
41
+ audit_log_entries: {
42
+ id: string;
43
+ action_type: number;
44
+ target_id?: string | null;
45
+ user_id?: string | null;
46
+ reason?: string;
47
+ }[];
48
+ users?: MicupUser[];
49
+ webhooks?: {
50
+ id: string;
51
+ name?: string;
52
+ }[];
53
+ }
54
+ export declare function guildPath(id: string): string;
55
+ export declare class MicupGuilds {
56
+ private readonly rest;
57
+ constructor(rest: RestTransport);
58
+ get(guildId: string, options?: MicupRequestOptions): Promise<MicupGuild>;
59
+ edit(guildId: string, body: Omit<Partial<MicupGuild>, 'id' | 'roles'>, options?: AuditOptions): Promise<MicupGuild>;
60
+ channels(guildId: string, options?: MicupRequestOptions): Promise<MicupChannel[]>;
61
+ roles(guildId: string, options?: MicupRequestOptions): Promise<MicupRole[]>;
62
+ createRole(guildId: string, role: GuildRoleEdit, options?: AuditOptions): Promise<MicupRole>;
63
+ editRole(guildId: string, roleId: string, role: GuildRoleEdit, options?: AuditOptions): Promise<MicupRole>;
64
+ deleteRole(guildId: string, roleId: string, options?: AuditOptions): Promise<void>;
65
+ member(guildId: string, userId: string, options?: MicupRequestOptions): Promise<MicupMember>;
66
+ currentMember(guildId: string, options?: MicupRequestOptions): Promise<MicupMember>;
67
+ members(guildId: string, { limit, after, signal }?: GuildMemberQuery): Promise<MicupMember[]>;
68
+ editMember(guildId: string, userId: string, body: GuildMemberEdit, options?: AuditOptions): Promise<MicupMember>;
69
+ addMemberRole(guildId: string, userId: string, roleId: string, options?: AuditOptions): Promise<void>;
70
+ removeMemberRole(guildId: string, userId: string, roleId: string, options?: AuditOptions): Promise<void>;
71
+ kick(guildId: string, userId: string, options?: AuditOptions): Promise<void>;
72
+ bans(guildId: string, options?: MicupRequestOptions): Promise<GuildBan[]>;
73
+ ban(guildId: string, userId: string, body?: GuildBanInput, options?: AuditOptions): Promise<void>;
74
+ unban(guildId: string, userId: string, options?: AuditOptions): Promise<void>;
75
+ auditLog(guildId: string, query?: URLSearchParams, options?: MicupRequestOptions): Promise<GuildAuditLog>;
76
+ }
@@ -0,0 +1,90 @@
1
+ import { snowflake } from './messages.js';
2
+ export function guildPath(id) {
3
+ return '/guilds/' + snowflake(id, 'Guild ID');
4
+ }
5
+ function memberPath(guildId, userId) {
6
+ return guildPath(guildId) + '/members/' + snowflake(userId, 'User ID');
7
+ }
8
+ function rolePayload({ permissions, ...body }) {
9
+ if (permissions === undefined)
10
+ return body;
11
+ const text = String(permissions);
12
+ if (!/^\d{1,20}$/.test(text) || BigInt(text) > (1n << 64n) - 1n)
13
+ throw new TypeError('Role permissions must be an unsigned 64-bit decimal value');
14
+ return { ...body, permissions: text };
15
+ }
16
+ export class MicupGuilds {
17
+ rest;
18
+ constructor(rest) {
19
+ this.rest = rest;
20
+ }
21
+ get(guildId, options) {
22
+ return this.rest.request('GET', guildPath(guildId), options);
23
+ }
24
+ edit(guildId, body, options) {
25
+ return this.rest.request('PATCH', guildPath(guildId), { ...options, body });
26
+ }
27
+ channels(guildId, options) {
28
+ return this.rest.request('GET', guildPath(guildId) + '/channels', options);
29
+ }
30
+ roles(guildId, options) {
31
+ return this.rest.request('GET', guildPath(guildId) + '/roles', options);
32
+ }
33
+ createRole(guildId, role, options) {
34
+ return this.rest.request('POST', guildPath(guildId) + '/roles', { ...options, body: rolePayload(role) });
35
+ }
36
+ editRole(guildId, roleId, role, options) {
37
+ const path = guildPath(guildId) + '/roles/' + snowflake(roleId, 'Role ID');
38
+ return this.rest.request('PATCH', path, { ...options, body: rolePayload(role) });
39
+ }
40
+ deleteRole(guildId, roleId, options) {
41
+ return this.rest.request('DELETE', guildPath(guildId) + '/roles/' + snowflake(roleId, 'Role ID'), options);
42
+ }
43
+ member(guildId, userId, options) {
44
+ return this.rest.request('GET', memberPath(guildId, userId), options);
45
+ }
46
+ currentMember(guildId, options) {
47
+ return this.rest.request('GET', guildPath(guildId) + '/members/@me', options);
48
+ }
49
+ members(guildId, { limit, after, signal } = {}) {
50
+ const query = new URLSearchParams();
51
+ if (limit !== undefined) {
52
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000)
53
+ throw new RangeError('Member limit must be between 1 and 1000');
54
+ query.set('limit', String(limit));
55
+ }
56
+ if (after !== undefined)
57
+ query.set('after', snowflake(after, 'Member cursor'));
58
+ return this.rest.request('GET', guildPath(guildId) + '/members', { query, signal });
59
+ }
60
+ editMember(guildId, userId, body, options) {
61
+ return this.rest.request('PATCH', memberPath(guildId, userId), { ...options, body });
62
+ }
63
+ addMemberRole(guildId, userId, roleId, options) {
64
+ return this.rest.request('PUT', memberPath(guildId, userId) + '/roles/' + snowflake(roleId, 'Role ID'), options);
65
+ }
66
+ removeMemberRole(guildId, userId, roleId, options) {
67
+ return this.rest.request('DELETE', memberPath(guildId, userId) + '/roles/' + snowflake(roleId, 'Role ID'), options);
68
+ }
69
+ kick(guildId, userId, options) {
70
+ return this.rest.request('DELETE', memberPath(guildId, userId), options);
71
+ }
72
+ bans(guildId, options) {
73
+ return this.rest.request('GET', guildPath(guildId) + '/bans', options);
74
+ }
75
+ ban(guildId, userId, body = {}, options) {
76
+ const deletion = body.delete_message_seconds ?? 0;
77
+ const duration = body.ban_duration_seconds ?? 0;
78
+ if (!Number.isInteger(deletion) || deletion < 0 || deletion > 604800 ||
79
+ !Number.isInteger(duration) || (duration !== 0 && (duration < 60 || duration > 63072000))) {
80
+ throw new RangeError('Invalid Micup ban duration or message deletion window');
81
+ }
82
+ return this.rest.request('PUT', guildPath(guildId) + '/bans/' + snowflake(userId, 'User ID'), { ...options, body });
83
+ }
84
+ unban(guildId, userId, options) {
85
+ return this.rest.request('DELETE', guildPath(guildId) + '/bans/' + snowflake(userId, 'User ID'), options);
86
+ }
87
+ auditLog(guildId, query, options) {
88
+ return this.rest.request('GET', guildPath(guildId) + '/audit-logs', { ...options, query });
89
+ }
90
+ }
@@ -0,0 +1,30 @@
1
+ import { type CommandChoice, type MicupInteraction } from '../model/interaction.js';
2
+ import type { MicupMessage } from './client.js';
3
+ import { type MessageInput } from './messages.js';
4
+ import type { MicupRequestOptions, RestTransport } from './transport.js';
5
+ export interface InteractionReplyOptions extends MicupRequestOptions {
6
+ ephemeral?: boolean;
7
+ }
8
+ export interface MicupModal {
9
+ title: string;
10
+ custom_id: string;
11
+ components: readonly Record<string, unknown>[];
12
+ }
13
+ type InteractionID = Pick<MicupInteraction, 'id' | 'token'>;
14
+ type InteractionApp = Pick<MicupInteraction, 'application_id' | 'token'>;
15
+ export declare class MicupInteractions {
16
+ #private;
17
+ private readonly rest;
18
+ constructor(rest: RestTransport);
19
+ respond(interaction: InteractionID, message: string | MessageInput, options?: InteractionReplyOptions): Promise<void>;
20
+ defer(interaction: InteractionID, options?: InteractionReplyOptions): Promise<void>;
21
+ deferUpdate(interaction: MicupInteraction, { signal }?: MicupRequestOptions): Promise<void>;
22
+ update(interaction: MicupInteraction, message: MessageInput, { signal }?: MicupRequestOptions): Promise<void>;
23
+ autocomplete(interaction: MicupInteraction, choices: readonly CommandChoice[], { signal }?: MicupRequestOptions): Promise<void>;
24
+ modal(interaction: MicupInteraction, modal: MicupModal, { signal }?: MicupRequestOptions): Promise<void>;
25
+ getResponse(interaction: InteractionApp, options?: MicupRequestOptions): Promise<MicupMessage>;
26
+ editResponse(interaction: InteractionApp, message: MessageInput, options?: MicupRequestOptions): Promise<MicupMessage>;
27
+ deleteResponse(interaction: InteractionApp, options?: MicupRequestOptions): Promise<void>;
28
+ followUp(interaction: InteractionApp, message: string | MessageInput, options?: InteractionReplyOptions): Promise<MicupMessage>;
29
+ }
30
+ export {};
@@ -0,0 +1,79 @@
1
+ import { InteractionType } from '../model/interaction.js';
2
+ import { messageBody, snowflake } from './messages.js';
3
+ const ephemeralFlag = 1 << 6;
4
+ function tokenPath(token) {
5
+ if (!token || token === '.' || token === '..')
6
+ throw new TypeError('Interaction token is required');
7
+ return encodeURIComponent(token);
8
+ }
9
+ function replyBody(message, ephemeral) {
10
+ const input = typeof message === 'string' ? { content: message } : message;
11
+ if (!input.content?.trim() && !input.embeds?.length && !input.components?.length && !input.files?.length) {
12
+ throw new TypeError('Interaction reply requires content, embeds, components or files');
13
+ }
14
+ return ephemeral ? { ...input, flags: (input.flags ?? 0) | ephemeralFlag } : input;
15
+ }
16
+ export class MicupInteractions {
17
+ rest;
18
+ constructor(rest) {
19
+ this.rest = rest;
20
+ }
21
+ #callback(interaction, type, data, signal) {
22
+ const path = '/interactions/' + snowflake(interaction.id, 'Interaction ID') + '/' + tokenPath(interaction.token) + '/callback';
23
+ return this.rest.request('POST', path, { body: { type, data }, signal });
24
+ }
25
+ #webhook(interaction) {
26
+ return '/webhooks/' + snowflake(interaction.application_id, 'Application ID') + '/' + tokenPath(interaction.token);
27
+ }
28
+ respond(interaction, message, options = {}) {
29
+ const input = replyBody(message, options.ephemeral);
30
+ if (input.files?.length)
31
+ throw new TypeError('Attach files in a follow-up after acknowledging the interaction');
32
+ return this.#callback(interaction, 4, messageBody(input), options.signal);
33
+ }
34
+ defer(interaction, options = {}) {
35
+ return this.#callback(interaction, 5, options.ephemeral ? { flags: ephemeralFlag } : undefined, options.signal);
36
+ }
37
+ deferUpdate(interaction, { signal } = {}) {
38
+ if (interaction.type !== InteractionType.Component)
39
+ throw new TypeError('Only component interactions can defer an update');
40
+ return this.#callback(interaction, 6, undefined, signal);
41
+ }
42
+ update(interaction, message, { signal } = {}) {
43
+ if (interaction.type !== InteractionType.Component)
44
+ throw new TypeError('Only component interactions can update a message');
45
+ if (message.files?.length || message.attachments?.length)
46
+ throw new TypeError('Component updates do not carry files');
47
+ return this.#callback(interaction, 7, messageBody(message), signal);
48
+ }
49
+ autocomplete(interaction, choices, { signal } = {}) {
50
+ if (interaction.type !== InteractionType.Autocomplete || choices.length > 25) {
51
+ throw new TypeError('An autocomplete interaction takes up to 25 choices');
52
+ }
53
+ return this.#callback(interaction, 8, { choices }, signal);
54
+ }
55
+ modal(interaction, modal, { signal } = {}) {
56
+ if ((interaction.type !== InteractionType.Command && interaction.type !== InteractionType.Component) ||
57
+ !modal.custom_id || modal.custom_id.length > 100 || !modal.title || modal.title.length > 45 ||
58
+ modal.components.length < 1 || modal.components.length > 5) {
59
+ throw new TypeError('Invalid Micup modal or interaction');
60
+ }
61
+ return this.#callback(interaction, 9, modal, signal);
62
+ }
63
+ getResponse(interaction, options) {
64
+ return this.rest.request('GET', this.#webhook(interaction) + '/messages/@original', options);
65
+ }
66
+ editResponse(interaction, message, options) {
67
+ return this.rest.request('PATCH', this.#webhook(interaction) + '/messages/@original', {
68
+ ...options, body: messageBody(message),
69
+ });
70
+ }
71
+ deleteResponse(interaction, options) {
72
+ return this.rest.request('DELETE', this.#webhook(interaction) + '/messages/@original', options);
73
+ }
74
+ followUp(interaction, message, options = {}) {
75
+ return this.rest.request('POST', this.#webhook(interaction), {
76
+ signal: options.signal, body: messageBody(replyBody(message, options.ephemeral)),
77
+ });
78
+ }
79
+ }
@@ -0,0 +1,65 @@
1
+ export interface MicupFile {
2
+ name: string;
3
+ data: Blob;
4
+ description?: string;
5
+ }
6
+ export interface MicupEmbed {
7
+ title?: string;
8
+ description?: string;
9
+ url?: string;
10
+ color?: number;
11
+ timestamp?: string;
12
+ fields?: readonly {
13
+ name: string;
14
+ value: string;
15
+ inline?: boolean;
16
+ }[];
17
+ image?: {
18
+ url: string;
19
+ };
20
+ thumbnail?: {
21
+ url: string;
22
+ };
23
+ footer?: {
24
+ text: string;
25
+ icon_url?: string;
26
+ };
27
+ author?: {
28
+ name: string;
29
+ url?: string;
30
+ icon_url?: string;
31
+ };
32
+ }
33
+ export interface AllowedMentions {
34
+ parse?: readonly ('users' | 'roles' | 'everyone')[];
35
+ users?: readonly string[];
36
+ roles?: readonly string[];
37
+ replied_user?: boolean;
38
+ }
39
+ export interface MessageInput {
40
+ content?: string | null;
41
+ embeds?: readonly MicupEmbed[];
42
+ components?: readonly Record<string, unknown>[];
43
+ allowed_mentions?: AllowedMentions;
44
+ flags?: number;
45
+ files?: readonly MicupFile[];
46
+ attachments?: readonly {
47
+ id: string;
48
+ filename?: string;
49
+ description?: string;
50
+ }[];
51
+ }
52
+ export interface ListMessageOptions {
53
+ before?: string;
54
+ after?: string;
55
+ around?: string;
56
+ limit?: number;
57
+ signal?: AbortSignal;
58
+ }
59
+ export declare function snowflake(id: string, label: string): string;
60
+ export declare function messagesPath(channelId: string, messageId?: string): string;
61
+ export declare function messageBody({ files, ...message }: MessageInput, reply?: {
62
+ message_id: string;
63
+ channel_id: string;
64
+ }): object;
65
+ export declare function messageQuery({ before, after, around, limit }: ListMessageOptions): URLSearchParams;