micup.ts 1.0.0 → 1.1.1

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 (94) hide show
  1. package/README.md +93 -38
  2. package/README.tr.md +137 -0
  3. package/dist/bot/client.d.ts +79 -0
  4. package/dist/bot/client.js +299 -0
  5. package/dist/events/background.d.ts +7 -0
  6. package/dist/events/background.js +23 -0
  7. package/dist/events/catalog.d.ts +243 -0
  8. package/dist/events/catalog.js +1 -0
  9. package/dist/events/guild-tag.d.ts +9 -0
  10. package/dist/events/guild-tag.js +38 -0
  11. package/dist/events/mux.d.ts +20 -5
  12. package/dist/events/names.d.ts +1 -0
  13. package/dist/events/names.js +71 -0
  14. package/dist/events/safe.d.ts +9 -0
  15. package/dist/events/safe.js +27 -0
  16. package/dist/gateway/compression.d.ts +9 -0
  17. package/dist/gateway/compression.js +119 -0
  18. package/dist/gateway/connection.js +42 -17
  19. package/dist/gateway/protocol.d.ts +4 -1
  20. package/dist/gateway/protocol.js +9 -3
  21. package/dist/gateway/subscription.d.ts +10 -0
  22. package/dist/gateway/subscription.js +26 -0
  23. package/dist/index.d.ts +48 -4
  24. package/dist/index.js +19 -3
  25. package/dist/model/components.d.ts +82 -0
  26. package/dist/model/components.js +74 -0
  27. package/dist/model/constants.d.ts +330 -0
  28. package/dist/model/constants.js +330 -0
  29. package/dist/model/embed.d.ts +59 -0
  30. package/dist/model/embed.js +40 -0
  31. package/dist/model/entities.d.ts +125 -0
  32. package/dist/model/entities.js +12 -0
  33. package/dist/model/format.d.ts +32 -0
  34. package/dist/model/format.js +61 -0
  35. package/dist/model/guild.d.ts +114 -1
  36. package/dist/model/helpers.d.ts +88 -0
  37. package/dist/model/helpers.js +185 -0
  38. package/dist/model/interaction.d.ts +1 -1
  39. package/dist/model/locale.d.ts +15 -0
  40. package/dist/model/locale.js +55 -0
  41. package/dist/model/media.d.ts +23 -0
  42. package/dist/model/media.js +65 -0
  43. package/dist/model/permissions.d.ts +5 -0
  44. package/dist/model/permissions.js +31 -0
  45. package/dist/rest/attachments.d.ts +26 -0
  46. package/dist/rest/attachments.js +82 -0
  47. package/dist/rest/channels.d.ts +87 -3
  48. package/dist/rest/channels.js +181 -2
  49. package/dist/rest/commands.d.ts +1 -0
  50. package/dist/rest/commands.js +17 -0
  51. package/dist/rest/discovery.d.ts +35 -0
  52. package/dist/rest/discovery.js +33 -0
  53. package/dist/rest/errors.d.ts +38 -0
  54. package/dist/rest/errors.js +46 -0
  55. package/dist/rest/expressions.d.ts +65 -0
  56. package/dist/rest/expressions.js +89 -0
  57. package/dist/rest/guilds.d.ts +102 -1
  58. package/dist/rest/guilds.js +127 -0
  59. package/dist/rest/identity.d.ts +1 -0
  60. package/dist/rest/identity.js +15 -0
  61. package/dist/rest/interactions.d.ts +1 -1
  62. package/dist/rest/messages.d.ts +54 -30
  63. package/dist/rest/messages.js +32 -12
  64. package/dist/rest/rooms.d.ts +142 -0
  65. package/dist/rest/rooms.js +133 -0
  66. package/dist/rest/sounds.d.ts +44 -0
  67. package/dist/rest/sounds.js +89 -0
  68. package/dist/rest/transport.d.ts +8 -2
  69. package/dist/rest/transport.js +38 -5
  70. package/dist/rest/users.d.ts +65 -0
  71. package/dist/rest/users.js +63 -0
  72. package/dist/rest/webhooks.d.ts +56 -0
  73. package/dist/rest/webhooks.js +94 -0
  74. package/dist/session/inventory.d.ts +22 -0
  75. package/dist/session/inventory.js +159 -0
  76. package/dist/session/session.d.ts +21 -2
  77. package/dist/session/session.js +61 -4
  78. package/dist/session/voice.d.ts +1 -0
  79. package/dist/session/voice.js +25 -17
  80. package/dist/shard/manager.d.ts +38 -1
  81. package/dist/shard/manager.js +87 -0
  82. package/dist/state/cache.d.ts +6 -1
  83. package/dist/state/cache.js +45 -1
  84. package/docs/README.md +13 -0
  85. package/docs/commands-and-interactions.md +120 -0
  86. package/docs/errors-and-limits.md +79 -0
  87. package/docs/gateway-and-sharding.md +102 -0
  88. package/docs/getting-started.md +79 -0
  89. package/docs/migrating.md +44 -0
  90. package/docs/rest-reference.md +101 -0
  91. package/docs/voice.md +95 -0
  92. package/package.json +25 -7
  93. package/dist/rest/client.d.ts +0 -48
  94. package/dist/rest/client.js +0 -151
@@ -1,3 +1,4 @@
1
+ import { validateEmbed } from '../model/embed.js';
1
2
  export function snowflake(id, label) {
2
3
  if (typeof id !== 'string' || !/^\d+$/.test(id))
3
4
  throw new TypeError(label + ' must be a numeric string');
@@ -7,20 +8,39 @@ export function messagesPath(channelId, messageId) {
7
8
  const base = '/channels/' + snowflake(channelId, 'Channel ID') + '/messages';
8
9
  return messageId === undefined ? base : base + '/' + snowflake(messageId, 'Message ID');
9
10
  }
10
- export function messageBody({ files = [], ...message }, reply) {
11
- const body = { ...message, ...(reply && { message_reference: reply }) };
11
+ export function assertFileName(name) {
12
+ if (typeof name !== 'string' || !name || /[/\\\r\n\u0000]/.test(name)) {
13
+ throw new TypeError('Micup attachments require a valid filename');
14
+ }
15
+ }
16
+ export function messageBody({ files = [], uploads = [], ...message }, reference, extra = {}) {
17
+ if ((message.embeds?.length ?? 0) > 10)
18
+ throw new RangeError('A Micup message accepts up to 10 embeds');
19
+ for (const embed of message.embeds ?? [])
20
+ validateEmbed(embed);
21
+ if ((message.sticker_ids?.length ?? 0) > 3)
22
+ throw new RangeError('A Micup message accepts up to three stickers');
23
+ const mentions = message.allowed_mentions;
24
+ const body = {
25
+ ...message, ...extra,
26
+ ...(mentions && { allowed_mentions: { ...mentions, parse: mentions.parse ?? [] } }),
27
+ ...(reference && { message_reference: reference }),
28
+ };
29
+ const attachments = [...(message.attachments ?? [])];
30
+ if (attachments.length + files.length + uploads.length > 10)
31
+ throw new RangeError('Micup messages support up to 10 attachments');
32
+ const newFiles = files.map(({ name, data, description, title, spoiler }, index) => {
33
+ assertFileName(name);
34
+ if (!(data instanceof Blob))
35
+ throw new TypeError('Micup attachments require a Blob');
36
+ return { id: index, filename: name, description, title, flags: spoiler ? 8 : undefined };
37
+ });
38
+ const uploadedFiles = uploads.map((upload, index) => ({ ...upload, id: files.length + index }));
39
+ const payload = files.length || uploads.length ? { ...body, attachments: [...attachments, ...newFiles, ...uploadedFiles] } : body;
12
40
  if (files.length === 0)
13
- return body;
41
+ return payload;
14
42
  const form = new FormData();
15
- const attachments = [...(body.attachments ?? []), ...files.map(({ name, data, description }, index) => {
16
- if (!name || /[/\\\r\n\u0000]/.test(name) || !(data instanceof Blob)) {
17
- throw new TypeError('Micup attachments require a filename and a Blob');
18
- }
19
- return { id: index, filename: name, description };
20
- })];
21
- if (attachments.length > 10)
22
- throw new RangeError('Micup messages support up to 10 attachments');
23
- form.append('payload_json', JSON.stringify({ ...body, attachments }));
43
+ form.append('payload_json', JSON.stringify(payload));
24
44
  files.forEach(({ name, data }, index) => form.append('files[' + index + ']', data, name));
25
45
  return form;
26
46
  }
@@ -0,0 +1,142 @@
1
+ import type { MicupRequestOptions, RestTransport } from './transport.js';
2
+ export type StageBoardStyle = 'neon' | 'tahta' | 'sade';
3
+ export type StageHostCharacter = 'ithp-gunluk' | 'ithp-ceketli' | 'ithp-gozluk' | 'ithp-kulaklik' | 'ithp-rahat' | 'ithp-sapkali' | 'ithp-sehirli' | 'ithp-yazlik';
4
+ export type StageEffectType = 'confetti' | 'spotlight' | 'host_emote';
5
+ export type TournamentGame = 'slap' | 'arm_wrestle';
6
+ export type TournamentSize = 4 | 8 | 16 | 32;
7
+ export interface StageScore {
8
+ name: string;
9
+ value: number;
10
+ user_id?: string | null;
11
+ }
12
+ export interface StageBoardInput {
13
+ type: 'board';
14
+ style?: StageBoardStyle;
15
+ title?: string | null;
16
+ text?: string | null;
17
+ accent?: number;
18
+ scores?: readonly StageScore[];
19
+ message_id?: string;
20
+ }
21
+ export interface StageVideoInput {
22
+ type: 'video';
23
+ url: string;
24
+ position_ms?: number;
25
+ paused?: boolean;
26
+ }
27
+ export interface StageHostInput {
28
+ character?: StageHostCharacter;
29
+ shirt?: number;
30
+ }
31
+ export interface VoiceRoomStageInput {
32
+ tv?: StageBoardInput | StageVideoInput | null;
33
+ host?: StageHostInput | null;
34
+ ttl_seconds?: number;
35
+ }
36
+ export interface VoiceRoomStage {
37
+ v: number;
38
+ bot: {
39
+ id: string;
40
+ name: string;
41
+ avatar: string | null;
42
+ };
43
+ written_at: number;
44
+ expires_at: number;
45
+ tv: {
46
+ type: 'board';
47
+ style: StageBoardStyle;
48
+ title: string;
49
+ text: string;
50
+ accent: number | null;
51
+ scores: StageScore[];
52
+ buttons: {
53
+ message_id: string;
54
+ items: {
55
+ custom_id: string;
56
+ label: string;
57
+ style: number;
58
+ disabled: boolean;
59
+ }[];
60
+ } | null;
61
+ } | {
62
+ type: 'video';
63
+ video_id: string;
64
+ started_at: number;
65
+ paused_at: number | null;
66
+ } | null;
67
+ host: {
68
+ character: StageHostCharacter;
69
+ shirt: number;
70
+ } | null;
71
+ }
72
+ export type StageEffect = {
73
+ type: 'confetti';
74
+ } | {
75
+ type: 'spotlight';
76
+ user_id: string;
77
+ } | {
78
+ type: 'host_emote';
79
+ emote: 'wave' | 'dance' | 'jump';
80
+ } | {
81
+ type: 'host_emote';
82
+ emote: 'emoji';
83
+ emoji: string;
84
+ };
85
+ export interface TournamentTable {
86
+ slot?: string;
87
+ x?: number;
88
+ z?: number;
89
+ yaw?: number;
90
+ }
91
+ export interface TournamentInput {
92
+ game: TournamentGame;
93
+ size: TournamentSize;
94
+ table?: TournamentTable;
95
+ }
96
+ export interface TournamentMatch {
97
+ a: string;
98
+ b: string | null;
99
+ w: string | null;
100
+ }
101
+ export interface TournamentCurrentMatch {
102
+ mid: string;
103
+ r: number;
104
+ i: number;
105
+ a: string;
106
+ b: string;
107
+ phase: 'call' | 'fight' | 'paused' | 'result';
108
+ until: number;
109
+ t0?: number;
110
+ te?: number;
111
+ slot?: string;
112
+ present: number[];
113
+ }
114
+ export interface RoomTournament {
115
+ v: number;
116
+ id: string;
117
+ ver: number;
118
+ game: TournamentGame;
119
+ size: TournamentSize;
120
+ status: 'registration' | 'running' | 'ended' | 'canceled';
121
+ entrants: string[];
122
+ rounds: TournamentMatch[][];
123
+ cur: TournamentCurrentMatch | null;
124
+ champion: string | null;
125
+ t: number;
126
+ }
127
+ export interface TournamentReadOptions extends MicupRequestOptions {
128
+ connectionId?: string;
129
+ }
130
+ export declare class MicupVoiceRooms {
131
+ private readonly rest;
132
+ constructor(rest: RestTransport);
133
+ stage(channelId: string, options?: MicupRequestOptions): Promise<VoiceRoomStage | null>;
134
+ setStage(channelId: string, stage: VoiceRoomStageInput, options?: MicupRequestOptions): Promise<VoiceRoomStage>;
135
+ clearStage(channelId: string, options?: MicupRequestOptions): Promise<void>;
136
+ stageEffect(channelId: string, effect: StageEffect, options?: MicupRequestOptions): Promise<void>;
137
+ tournament(channelId: string, { connectionId, signal }?: TournamentReadOptions): Promise<RoomTournament | null>;
138
+ openTournament(channelId: string, input: TournamentInput, options?: MicupRequestOptions): Promise<RoomTournament>;
139
+ cancelTournament(channelId: string, options?: MicupRequestOptions): Promise<void>;
140
+ reorderTournament(channelId: string, version: number, userIds: readonly string[], options?: MicupRequestOptions): Promise<RoomTournament>;
141
+ startTournament(channelId: string, version: number, options?: MicupRequestOptions): Promise<RoomTournament>;
142
+ }
@@ -0,0 +1,133 @@
1
+ import { snowflake } from './messages.js';
2
+ const forbiddenRanges = [
3
+ [0x00, 0x08], [0x0b, 0x1f], [0x7f, 0x9f], [0x2028, 0x2029], [0x200e, 0x200f], [0x061c, 0x061c],
4
+ [0x202a, 0x202e], [0x2066, 0x2069], [0x200b, 0x200b], [0x2060, 0x2060], [0xfeff, 0xfeff],
5
+ ];
6
+ const hasForbiddenText = (value) => [...value].some((char) => {
7
+ const code = char.codePointAt(0);
8
+ return forbiddenRanges.some(([low, high]) => code >= low && code <= high);
9
+ });
10
+ const colour = (value, label) => {
11
+ if (!Number.isSafeInteger(value) || value < 0 || value > 0xffffff)
12
+ throw new RangeError(label + ' must be an RGB integer');
13
+ return value;
14
+ };
15
+ function plain(value, max, lines, label) {
16
+ if (value === undefined || value === null)
17
+ return;
18
+ if (typeof value !== 'string' || [...value].length > max || value.split('\n').length > lines || hasForbiddenText(value)) {
19
+ throw new RangeError(label + ' takes plain text of up to ' + max + ' characters on up to ' + lines + ' lines');
20
+ }
21
+ }
22
+ function stageBody({ tv, host, ttl_seconds }) {
23
+ if (ttl_seconds !== undefined && (!Number.isSafeInteger(ttl_seconds) || ttl_seconds < 60 || ttl_seconds > 21_600)) {
24
+ throw new RangeError('A stage lasts 60 to 21600 seconds');
25
+ }
26
+ if (tv?.type === 'board') {
27
+ plain(tv.title, 60, 1, 'Stage title');
28
+ plain(tv.text, 280, 4, 'Stage text');
29
+ if (tv.accent !== undefined)
30
+ colour(tv.accent, 'Stage accent');
31
+ if ((tv.scores?.length ?? 0) > 10)
32
+ throw new RangeError('A stage board takes up to 10 scores');
33
+ for (const score of tv.scores ?? []) {
34
+ plain(score.name, 32, 1, 'Score name');
35
+ if (!score.name || !Number.isSafeInteger(score.value) || Math.abs(score.value) > 1_000_000_000)
36
+ throw new RangeError('Invalid stage score');
37
+ if (score.user_id)
38
+ snowflake(score.user_id, 'Score user ID');
39
+ }
40
+ if (tv.message_id !== undefined)
41
+ snowflake(tv.message_id, 'Message ID');
42
+ }
43
+ else if (tv?.type === 'video') {
44
+ if (typeof tv.url !== 'string' || !tv.url || tv.url.length > 2048)
45
+ throw new TypeError('A stage video needs a URL of up to 2048 characters');
46
+ if (tv.position_ms !== undefined && (!Number.isSafeInteger(tv.position_ms) || tv.position_ms < 0 || tv.position_ms > 86_400_000)) {
47
+ throw new RangeError('A stage video position takes 0 to 86400000 milliseconds');
48
+ }
49
+ }
50
+ else if (tv) {
51
+ throw new TypeError('A stage TV shows a board or a video');
52
+ }
53
+ if (host?.shirt !== undefined)
54
+ colour(host.shirt, 'Host shirt');
55
+ return { tv: tv ?? null, host: host ?? null, ...(ttl_seconds !== undefined && { ttl_seconds }) };
56
+ }
57
+ function effectBody(effect) {
58
+ if (effect.type === 'spotlight')
59
+ snowflake(effect.user_id, 'User ID');
60
+ else if (effect.type === 'host_emote') {
61
+ if (!['wave', 'dance', 'jump', 'emoji'].includes(effect.emote))
62
+ throw new TypeError('Invalid host emote');
63
+ if (effect.emote === 'emoji' && !('emoji' in effect && effect.emoji && [...effect.emoji].length <= 16)) {
64
+ throw new TypeError('An emoji emote needs one emoji');
65
+ }
66
+ }
67
+ else if (effect.type !== 'confetti') {
68
+ throw new TypeError('Invalid stage effect');
69
+ }
70
+ return effect;
71
+ }
72
+ function tournamentBody({ game, size, table }) {
73
+ if (game !== 'slap' && game !== 'arm_wrestle')
74
+ throw new TypeError('A room tournament is slap or arm_wrestle');
75
+ if (![4, 8, 16, 32].includes(size))
76
+ throw new RangeError('A room tournament takes 4, 8, 16 or 32 entrants');
77
+ if (table) {
78
+ const point = table.x !== undefined || table.z !== undefined || table.yaw !== undefined;
79
+ if (table.slot !== undefined === point)
80
+ throw new TypeError('A tournament table is a slot or a floor point');
81
+ if (point && (![table.x, table.z].every((value) => Number.isFinite(value) && Math.abs(value) <= 100) ||
82
+ !Number.isFinite(table.yaw) || Math.abs(table.yaw) > Math.PI)) {
83
+ throw new RangeError('A floor point takes x and z within 100 metres and a yaw within pi');
84
+ }
85
+ }
86
+ return { game, size, ...(table && { table: table.slot !== undefined ? { slot: table.slot } : table }) };
87
+ }
88
+ function roomPath(channelId) {
89
+ return '/channels/' + snowflake(channelId, 'Channel ID') + '/voice-room';
90
+ }
91
+ export class MicupVoiceRooms {
92
+ rest;
93
+ constructor(rest) {
94
+ this.rest = rest;
95
+ }
96
+ async stage(channelId, options) {
97
+ const { stage } = await this.rest.request('GET', roomPath(channelId) + '/stage', options);
98
+ return stage;
99
+ }
100
+ setStage(channelId, stage, options) {
101
+ return this.rest.request('PUT', roomPath(channelId) + '/stage', { ...options, body: stageBody(stage) });
102
+ }
103
+ clearStage(channelId, options) {
104
+ return this.rest.request('DELETE', roomPath(channelId) + '/stage', options);
105
+ }
106
+ stageEffect(channelId, effect, options) {
107
+ return this.rest.request('POST', roomPath(channelId) + '/stage/effects', { ...options, body: effectBody(effect) });
108
+ }
109
+ async tournament(channelId, { connectionId, signal } = {}) {
110
+ const query = connectionId === undefined ? undefined : new URLSearchParams({ connection_id: connectionId });
111
+ const { tournament } = await this.rest.request('GET', roomPath(channelId) + '/tournament', { query, signal });
112
+ return tournament;
113
+ }
114
+ openTournament(channelId, input, options) {
115
+ return this.rest.request('POST', roomPath(channelId) + '/tournament', { ...options, body: tournamentBody(input) });
116
+ }
117
+ cancelTournament(channelId, options) {
118
+ return this.rest.request('DELETE', roomPath(channelId) + '/tournament', options);
119
+ }
120
+ reorderTournament(channelId, version, userIds, options) {
121
+ if (!Number.isSafeInteger(version) || userIds.length < 2 || userIds.length > 32 || new Set(userIds).size !== userIds.length) {
122
+ throw new RangeError('A tournament order lists 2 to 32 distinct entrants for one version');
123
+ }
124
+ return this.rest.request('PUT', roomPath(channelId) + '/tournament/order', {
125
+ ...options, body: { version, user_ids: userIds.map((id) => snowflake(id, 'User ID')) },
126
+ });
127
+ }
128
+ startTournament(channelId, version, options) {
129
+ if (!Number.isSafeInteger(version))
130
+ throw new TypeError('A tournament start needs the tournament version');
131
+ return this.rest.request('POST', roomPath(channelId) + '/tournament/start', { ...options, body: { version } });
132
+ }
133
+ }
@@ -0,0 +1,44 @@
1
+ import { type AuditOptions } from './guilds.js';
2
+ import type { MicupRequestOptions, RestTransport } from './transport.js';
3
+ export interface MicupSoundboardSound {
4
+ id: string;
5
+ guild_id: string;
6
+ creator_id: string;
7
+ name: string;
8
+ asset_hash: string;
9
+ extension: string;
10
+ size_bytes: number;
11
+ duration_ms: number;
12
+ volume: number;
13
+ created_at: string;
14
+ version: number;
15
+ url: string;
16
+ }
17
+ export type AudioInput = string | Uint8Array;
18
+ export interface SoundboardSoundInput {
19
+ name: string;
20
+ audio: AudioInput;
21
+ volume?: number;
22
+ }
23
+ export interface SoundboardSoundEdit {
24
+ name?: string;
25
+ volume?: number;
26
+ }
27
+ export interface SoundboardPlayOptions extends MicupRequestOptions {
28
+ sessionId: string;
29
+ connectionId: string;
30
+ }
31
+ export declare function encodeAudio(audio: AudioInput, label?: string): string;
32
+ export declare class MicupSounds {
33
+ private readonly rest;
34
+ constructor(rest: RestTransport);
35
+ list(guildId: string, options?: MicupRequestOptions): Promise<MicupSoundboardSound[]>;
36
+ create(guildId: string, { name, audio, volume }: SoundboardSoundInput, options?: MicupRequestOptions): Promise<MicupSoundboardSound>;
37
+ edit(guildId: string, soundId: string, { name, volume }: SoundboardSoundEdit, options?: MicupRequestOptions): Promise<MicupSoundboardSound>;
38
+ delete(guildId: string, soundId: string, options?: MicupRequestOptions): Promise<void>;
39
+ play(channelId: string, soundId: string, { sessionId, connectionId, ...options }: SoundboardPlayOptions): Promise<void>;
40
+ setGuildNotification(guildId: string, audio: AudioInput, options?: AuditOptions): Promise<void>;
41
+ clearGuildNotification(guildId: string, options?: AuditOptions): Promise<void>;
42
+ setChannelNotification(channelId: string, audio: AudioInput, options?: AuditOptions): Promise<void>;
43
+ clearChannelNotification(channelId: string, options?: AuditOptions): Promise<void>;
44
+ }
@@ -0,0 +1,89 @@
1
+ import { guildPath } from './guilds.js';
2
+ import { snowflake } from './messages.js';
3
+ const maxAudioBytes = 512_000;
4
+ export function encodeAudio(audio, label = 'Audio') {
5
+ if (typeof audio === 'string') {
6
+ if (!audio || audio.startsWith('data:') || audio.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(audio)) {
7
+ throw new TypeError(label + ' must be base64 without a data URL prefix');
8
+ }
9
+ const padding = audio.endsWith('==') ? 2 : audio.endsWith('=') ? 1 : 0;
10
+ if (audio.length / 4 * 3 - padding > maxAudioBytes)
11
+ throw new RangeError(label + ' is larger than 512000 bytes');
12
+ return audio;
13
+ }
14
+ if (!(audio instanceof Uint8Array) || !audio.byteLength)
15
+ throw new TypeError(label + ' must be a base64 string or bytes');
16
+ if (audio.byteLength > maxAudioBytes)
17
+ throw new RangeError(label + ' is larger than 512000 bytes');
18
+ return Buffer.from(audio.buffer, audio.byteOffset, audio.byteLength).toString('base64');
19
+ }
20
+ function soundName(name) {
21
+ const length = typeof name === 'string' ? [...name].length : 0;
22
+ if (length < 1 || length > 32)
23
+ throw new RangeError('A soundboard sound name takes 1 to 32 characters');
24
+ return name;
25
+ }
26
+ function soundVolume(volume) {
27
+ if (!Number.isFinite(volume) || volume < 0 || volume > 1)
28
+ throw new RangeError('Soundboard volume must be between 0 and 1');
29
+ return volume;
30
+ }
31
+ function channelPath(id) {
32
+ return '/channels/' + snowflake(id, 'Channel ID');
33
+ }
34
+ export class MicupSounds {
35
+ rest;
36
+ constructor(rest) {
37
+ this.rest = rest;
38
+ }
39
+ async list(guildId, options) {
40
+ const { sounds } = await this.rest.request('GET', guildPath(guildId) + '/soundboard-sounds', options);
41
+ return sounds;
42
+ }
43
+ create(guildId, { name, audio, volume }, options) {
44
+ return this.rest.request('POST', guildPath(guildId) + '/soundboard-sounds', {
45
+ ...options,
46
+ body: {
47
+ name: soundName(name),
48
+ audio: encodeAudio(audio),
49
+ ...(volume !== undefined && { volume: soundVolume(volume) }),
50
+ },
51
+ });
52
+ }
53
+ edit(guildId, soundId, { name, volume }, options) {
54
+ if (name === undefined && volume === undefined)
55
+ throw new TypeError('A soundboard sound edit needs a name or a volume');
56
+ return this.rest.request('PATCH', guildPath(guildId) + '/soundboard-sounds/' + snowflake(soundId, 'Sound ID'), {
57
+ ...options,
58
+ body: {
59
+ ...(name !== undefined && { name: soundName(name) }),
60
+ ...(volume !== undefined && { volume: soundVolume(volume) }),
61
+ },
62
+ });
63
+ }
64
+ delete(guildId, soundId, options) {
65
+ return this.rest.request('DELETE', guildPath(guildId) + '/soundboard-sounds/' + snowflake(soundId, 'Sound ID'), options);
66
+ }
67
+ play(channelId, soundId, { sessionId, connectionId, ...options }) {
68
+ for (const [value, label] of [[sessionId, 'Session ID'], [connectionId, 'Connection ID']]) {
69
+ if (typeof value !== 'string' || value.length < 1 || value.length > 128)
70
+ throw new TypeError(label + ' must take 1 to 128 characters');
71
+ }
72
+ return this.rest.request('POST', channelPath(channelId) + '/soundboard-sounds/' + snowflake(soundId, 'Sound ID') + '/play', {
73
+ ...options,
74
+ body: { session_id: sessionId, connection_id: connectionId },
75
+ });
76
+ }
77
+ setGuildNotification(guildId, audio, options) {
78
+ return this.rest.request('PUT', guildPath(guildId) + '/notification-sound', { ...options, body: { audio: encodeAudio(audio) } });
79
+ }
80
+ clearGuildNotification(guildId, options) {
81
+ return this.rest.request('DELETE', guildPath(guildId) + '/notification-sound', options);
82
+ }
83
+ setChannelNotification(channelId, audio, options) {
84
+ return this.rest.request('PUT', channelPath(channelId) + '/notification-sound', { ...options, body: { audio: encodeAudio(audio) } });
85
+ }
86
+ clearChannelNotification(channelId, options) {
87
+ return this.rest.request('DELETE', channelPath(channelId) + '/notification-sound', options);
88
+ }
89
+ }
@@ -1,4 +1,7 @@
1
1
  export type RestMethod = 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';
2
+ export interface MicupLogger {
3
+ warn(message: string, fields?: Record<string, unknown>): void;
4
+ }
2
5
  export interface MicupRequestOptions {
3
6
  signal?: AbortSignal;
4
7
  }
@@ -6,11 +9,14 @@ export interface RestRequestOptions extends MicupRequestOptions {
6
9
  body?: unknown;
7
10
  query?: URLSearchParams;
8
11
  reason?: string;
12
+ anonymous?: boolean;
13
+ idempotent?: boolean;
9
14
  }
10
15
  export declare class RestTransport {
11
16
  #private;
12
17
  private readonly token;
13
18
  private readonly attempts;
14
- constructor(api: string, token: string, attempts?: number);
15
- request<T>(method: RestMethod, path: string, { body, signal, query, reason }?: RestRequestOptions): Promise<T>;
19
+ private readonly logger?;
20
+ constructor(api: string, token: string, attempts?: number, logger?: MicupLogger | undefined);
21
+ request<T>(method: RestMethod, path: string, { body, signal, query, reason, anonymous, idempotent }?: RestRequestOptions): Promise<T>;
16
22
  }
@@ -1,5 +1,7 @@
1
1
  import { setTimeout as delay } from 'node:timers/promises';
2
2
  import { MicupAPIError, retryDelay } from './errors.js';
3
+ const permissionLogWindow = 60_000;
4
+ const permissionLogLimit = 512;
3
5
  const majorParameters = new Set(['channels', 'guilds', 'webhooks']);
4
6
  const maxRetryDelay = 30_000;
5
7
  const repeatable = new Set(['GET', 'HEAD', 'PUT', 'DELETE']);
@@ -76,17 +78,44 @@ async function readJson(response, limit) {
76
78
  export class RestTransport {
77
79
  token;
78
80
  attempts;
81
+ logger;
79
82
  #limits = new RateLimits();
80
83
  #api;
81
- constructor(api, token, attempts = 5) {
84
+ #denied = new Map();
85
+ constructor(api, token, attempts = 5, logger) {
82
86
  this.token = token;
83
87
  this.attempts = attempts;
88
+ this.logger = logger;
84
89
  this.#api = new URL(api + '/');
85
90
  if (!Number.isSafeInteger(attempts) || attempts < 1 || attempts > 5) {
86
91
  throw new RangeError('Micup REST attempts must be between 1 and 5');
87
92
  }
88
93
  }
89
- async request(method, path, { body, signal, query, reason } = {}) {
94
+ #notePermissionDenied(method, path, error) {
95
+ if (!this.logger || error.status !== 403 || (error.code !== 'MISSING_PERMISSIONS' && error.code !== 'MISSING_ACCESS'))
96
+ return;
97
+ const key = method + ' ' + path;
98
+ const now = performance.now();
99
+ const last = this.#denied.get(key);
100
+ if (last !== undefined && now - last < permissionLogWindow)
101
+ return;
102
+ if (this.#denied.size >= permissionLogLimit) {
103
+ for (const [stored, at] of this.#denied)
104
+ if (now - at >= permissionLogWindow)
105
+ this.#denied.delete(stored);
106
+ if (this.#denied.size >= permissionLogLimit)
107
+ this.#denied.clear();
108
+ }
109
+ this.#denied.set(key, now);
110
+ const guildId = /^\/guilds\/(\d+)/.exec(path)?.[1];
111
+ try {
112
+ this.logger.warn('bot lacks permission for this request', {
113
+ method, path, code: error.code, ...(guildId && { guild: guildId }), ...(error.message && { message: error.message }),
114
+ });
115
+ }
116
+ catch { }
117
+ }
118
+ async request(method, path, { body, signal, query, reason, anonymous, idempotent } = {}) {
90
119
  if (!path.startsWith('/') || path.startsWith('//') || /[\\?#\u0000-\u0020]/.test(path)) {
91
120
  throw new TypeError('Micup REST path must be relative to the versioned API');
92
121
  }
@@ -96,7 +125,10 @@ export class RestTransport {
96
125
  }
97
126
  if (query?.size)
98
127
  target.search = query.toString();
99
- const headers = new Headers({ Authorization: 'Bot ' + this.token, 'User-Agent': 'micup.ts' });
128
+ const headers = new Headers({ 'User-Agent': 'micup.ts' });
129
+ if (!anonymous)
130
+ headers.set('Authorization', 'Bot ' + this.token);
131
+ const canRetry = idempotent || repeatable.has(method);
100
132
  if (reason !== undefined) {
101
133
  if (typeof reason !== 'string' || !reason.trim() || reason.length > 512 || /[\r\n]/.test(reason)) {
102
134
  throw new TypeError('Invalid Micup audit log reason');
@@ -120,7 +152,7 @@ export class RestTransport {
120
152
  catch {
121
153
  signal?.throwIfAborted();
122
154
  last = new Error('Micup API connection failed');
123
- if (!remaining || !repeatable.has(method))
155
+ if (!remaining || !canRetry)
124
156
  throw last;
125
157
  await delay(backoff, undefined, { signal });
126
158
  continue;
@@ -134,6 +166,7 @@ export class RestTransport {
134
166
  signal?.throwIfAborted();
135
167
  const error = new MicupAPIError(response, errorBody);
136
168
  last = error;
169
+ this.#notePermissionDenied(method, target.pathname.slice(this.#api.pathname.length - 1), error);
137
170
  let wait = 0;
138
171
  if (response.status === 429) {
139
172
  wait = Math.max(error.retryAfterMs, 1);
@@ -142,7 +175,7 @@ export class RestTransport {
142
175
  else if (response.status === 423) {
143
176
  wait = Math.max(error.retryAfterMs, 1000);
144
177
  }
145
- else if (response.status >= 500 && repeatable.has(method)) {
178
+ else if (response.status >= 500 && canRetry) {
146
179
  wait = Math.max(error.retryAfterMs, backoff);
147
180
  }
148
181
  if (!remaining || wait === 0 || wait > maxRetryDelay)
@@ -0,0 +1,65 @@
1
+ import type { MicupUser } from '../model/entities.js';
2
+ import type { MicupChannel, MicupGuild, MicupMember } from '../model/guild.js';
3
+ import type { MicupRequestOptions, RestTransport } from './transport.js';
4
+ export interface MicupApplication {
5
+ id: string;
6
+ name: string;
7
+ icon?: string | null;
8
+ description?: string | null;
9
+ owner?: MicupUser;
10
+ flags?: number | null;
11
+ }
12
+ export interface BotProfileEdit {
13
+ username?: string;
14
+ avatar?: string | null;
15
+ banner?: string | null;
16
+ }
17
+ export interface MicupPublicApplication {
18
+ id: string;
19
+ name: string;
20
+ icon: string | null;
21
+ description: string | null;
22
+ redirect_uris: string[];
23
+ scopes: string[];
24
+ bot_public: boolean;
25
+ bot: {
26
+ id: string;
27
+ username: string;
28
+ discriminator: string;
29
+ avatar?: string | null;
30
+ banner?: string | null;
31
+ bio: string | null;
32
+ } | null;
33
+ current_user?: MicupUser | null;
34
+ }
35
+ export interface UserProfileOptions extends MicupRequestOptions {
36
+ guildId?: string;
37
+ withMutualFriends?: boolean;
38
+ withMutualGuilds?: boolean;
39
+ }
40
+ export interface MicupUserProfile {
41
+ user: MicupUser;
42
+ guild_member?: MicupMember;
43
+ mutual_guilds?: {
44
+ id: string;
45
+ nick?: string | null;
46
+ }[];
47
+ mutual_friends?: MicupUser[];
48
+ }
49
+ export declare class MicupUsers {
50
+ private readonly rest;
51
+ constructor(rest: RestTransport);
52
+ get(userId: string, options?: MicupRequestOptions): Promise<MicupUser>;
53
+ profile(userId: string, { guildId, withMutualFriends, withMutualGuilds, signal }?: UserProfileOptions): Promise<MicupUserProfile>;
54
+ createDM(userId: string, options?: MicupRequestOptions): Promise<MicupChannel>;
55
+ application(options?: MicupRequestOptions): Promise<MicupApplication>;
56
+ editCurrentUser(edit: BotProfileEdit, options?: MicupRequestOptions): Promise<MicupUser>;
57
+ publicApplication(applicationId: string, options?: MicupRequestOptions): Promise<MicupPublicApplication>;
58
+ guilds({ before, after, limit, signal }?: MicupRequestOptions & {
59
+ before?: string;
60
+ after?: string;
61
+ limit?: number;
62
+ }): Promise<MicupGuild[]>;
63
+ iterateGuilds({ signal }?: MicupRequestOptions): AsyncGenerator<MicupGuild>;
64
+ leaveGuild(guildId: string, options?: MicupRequestOptions): Promise<void>;
65
+ }