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.
- package/LICENSE +21 -0
- package/README.md +79 -2
- package/dist/events/mux.d.ts +82 -0
- package/dist/events/mux.js +23 -0
- package/dist/events/router.d.ts +11 -0
- package/dist/events/router.js +54 -0
- package/dist/gateway/connection.d.ts +30 -0
- package/dist/gateway/connection.js +272 -0
- package/dist/gateway/protocol.d.ts +40 -0
- package/dist/gateway/protocol.js +59 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.js +12 -0
- package/dist/model/guild.d.ts +69 -0
- package/dist/model/guild.js +1 -0
- package/dist/model/interaction.d.ts +137 -0
- package/dist/model/interaction.js +18 -0
- package/dist/model/permissions.d.ts +47 -0
- package/dist/model/permissions.js +81 -0
- package/dist/model/presence.d.ts +16 -0
- package/dist/model/presence.js +30 -0
- package/dist/rest/channels.d.ts +82 -0
- package/dist/rest/channels.js +68 -0
- package/dist/rest/client.d.ts +48 -0
- package/dist/rest/client.js +151 -0
- package/dist/rest/commands.d.ts +18 -0
- package/dist/rest/commands.js +94 -0
- package/dist/rest/errors.d.ts +24 -0
- package/dist/rest/errors.js +26 -0
- package/dist/rest/guilds.d.ts +76 -0
- package/dist/rest/guilds.js +90 -0
- package/dist/rest/interactions.d.ts +30 -0
- package/dist/rest/interactions.js +79 -0
- package/dist/rest/messages.d.ts +65 -0
- package/dist/rest/messages.js +38 -0
- package/dist/rest/transport.d.ts +16 -0
- package/dist/rest/transport.js +154 -0
- package/dist/session/requests.d.ts +39 -0
- package/dist/session/requests.js +144 -0
- package/dist/session/session.d.ts +63 -0
- package/dist/session/session.js +193 -0
- package/dist/session/voice.d.ts +41 -0
- package/dist/session/voice.js +168 -0
- package/dist/shard/manager.d.ts +20 -0
- package/dist/shard/manager.js +93 -0
- package/dist/state/cache.d.ts +15 -0
- package/dist/state/cache.js +257 -0
- package/package.json +39 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mitune
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,80 @@
|
|
|
1
|
-
#
|
|
1
|
+
# micup.ts
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
TypeScript SDK for Micup bots (Fluxer API), based on [micup.go](https://github.com/yestefir/micup.go). The SDK includes API discovery, REST requests and supervised Gateway sessions.
|
|
4
|
+
|
|
5
|
+
Requires Node.js 22 or later and a Micup bot token. The build produces JavaScript and TypeScript declarations. Install it with:
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install micup.ts
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```js
|
|
12
|
+
import { MicupClient } from 'micup.ts';
|
|
13
|
+
|
|
14
|
+
const client = await MicupClient.connect({ token: process.env.MICUP_BOT_TOKEN });
|
|
15
|
+
const user = await client.getCurrentUser();
|
|
16
|
+
console.log(user.username);
|
|
17
|
+
|
|
18
|
+
await client.sendMessage(process.env.MICUP_CHANNEL_ID, 'Merhaba!');
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Supply a message ID as `{ replyTo: '123456789' }` in the third argument to send a reply. Supply an `AbortSignal` as `{ signal }` to cancel an operation. HTTP errors expose `status`, the Micup error `code` when present, and the raw `retryAfter` header when present.
|
|
22
|
+
|
|
23
|
+
## Gateway
|
|
24
|
+
|
|
25
|
+
Use a session to keep a bot connected and receive events.
|
|
26
|
+
|
|
27
|
+
```js
|
|
28
|
+
import { EventMux, MicupClient } from 'micup.ts';
|
|
29
|
+
|
|
30
|
+
const bot = await MicupClient.connect({ token: process.env.MICUP_BOT_TOKEN });
|
|
31
|
+
const events = new EventMux();
|
|
32
|
+
events.on('MESSAGE_CREATE', async (message, event, signal) => {
|
|
33
|
+
if (message.author.bot || message.content !== '!ping') return;
|
|
34
|
+
await bot.sendMessage(message.channel_id, 'pong', { replyTo: message.id, signal });
|
|
35
|
+
});
|
|
36
|
+
const stop = new AbortController();
|
|
37
|
+
process.once('SIGINT', () => stop.abort());
|
|
38
|
+
process.once('SIGTERM', () => stop.abort());
|
|
39
|
+
await bot.newSession({ handler: events.handle }).run({ signal: stop.signal });
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
The session reconnects with backoff and resumes from the last successfully processed sequence. A failed handler can receive the event again, so make externally visible effects safe to repeat. The handler's signal is aborted when the connection or session is replaced. Unknown event names can be registered with the mux and have an `unknown` payload until you provide a type.
|
|
43
|
+
|
|
44
|
+
With `bot.newShardManager({ shardCount, session: { handler: events.handle } })`, a single process can run multiple shards. The manager spaces IDENTIFY commands and `manager.forGuild(guildId)` returns the local session responsible for a guild.
|
|
45
|
+
|
|
46
|
+
## Commands and interactions
|
|
47
|
+
|
|
48
|
+
Register slash commands for a development guild using `client.commands.set`. Omit `guildId` to register globally.
|
|
49
|
+
|
|
50
|
+
```js
|
|
51
|
+
import { EventMux, InteractionRouter, MicupClient } from 'micup.ts';
|
|
52
|
+
|
|
53
|
+
const client = await MicupClient.connect({ token: process.env.MICUP_BOT_TOKEN });
|
|
54
|
+
await client.commands.set([{ name: 'ping', description: 'Check the bot' }], {
|
|
55
|
+
guildId: process.env.MICUP_GUILD_ID,
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
const router = new InteractionRouter().command('ping', (interaction, signal) =>
|
|
59
|
+
client.interactions.respond(interaction, 'pong', { signal }),
|
|
60
|
+
);
|
|
61
|
+
const events = new EventMux();
|
|
62
|
+
events.on('INTERACTION_CREATE', async (interaction, event, signal) => {
|
|
63
|
+
await router.handle(interaction, signal);
|
|
64
|
+
});
|
|
65
|
+
await client.newSession({ handler: events.handle }).run();
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
The router also handles autocomplete, buttons, select menus and modal submissions. Use `client.interactions.defer` and `editResponse` when work needs more time.
|
|
69
|
+
|
|
70
|
+
## Server administration
|
|
71
|
+
|
|
72
|
+
Use the `client.guilds` and `client.channels` APIs for members, roles, channel permissions, threads, pins, reactions and invitations. Each Gateway session exposes `session.state` for cached guilds, channels, members, voice states and permission checks.
|
|
73
|
+
|
|
74
|
+
## Voice
|
|
75
|
+
|
|
76
|
+
The optional [`@micupts/voice`](packages/voice) workspace publishes audio to LiveKit. Install it with `npm install @micupts/voice` when your bot needs audio playback.
|
|
77
|
+
|
|
78
|
+
Run `npm ci` once, then `npm test` to verify the REST client locally.
|
|
79
|
+
|
|
80
|
+
MIT license. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { GatewayDispatch } from '../gateway/protocol.js';
|
|
2
|
+
import type { MicupMessage, MicupUser } from '../rest/client.js';
|
|
3
|
+
import type { VoiceServerUpdate } from '../session/voice.js';
|
|
4
|
+
import type { MicupChannel, MicupGuildCreate, MicupMember, MicupMembersChunk, MicupRole, MicupVoiceState } from '../model/guild.js';
|
|
5
|
+
import type { MicupInteraction } from '../model/interaction.js';
|
|
6
|
+
export interface MicupEvents {
|
|
7
|
+
READY: {
|
|
8
|
+
session_id: string;
|
|
9
|
+
user: MicupUser;
|
|
10
|
+
guilds?: MicupGuildCreate[];
|
|
11
|
+
private_channels?: MicupChannel[];
|
|
12
|
+
};
|
|
13
|
+
RESUMED: Record<string, never>;
|
|
14
|
+
MESSAGE_CREATE: MicupMessage;
|
|
15
|
+
MESSAGE_UPDATE: Partial<MicupMessage> & Pick<MicupMessage, 'id' | 'channel_id'>;
|
|
16
|
+
MESSAGE_DELETE: Pick<MicupMessage, 'id' | 'channel_id'> & {
|
|
17
|
+
guild_id?: string;
|
|
18
|
+
};
|
|
19
|
+
USER_UPDATE: MicupUser;
|
|
20
|
+
INTERACTION_CREATE: MicupInteraction;
|
|
21
|
+
VOICE_STATE_UPDATE: MicupVoiceState;
|
|
22
|
+
GUILD_CREATE: MicupGuildCreate;
|
|
23
|
+
GUILD_SYNC: MicupGuildCreate;
|
|
24
|
+
GUILD_UPDATE: Partial<MicupGuildCreate> & {
|
|
25
|
+
guild_id?: string;
|
|
26
|
+
};
|
|
27
|
+
GUILD_DELETE: {
|
|
28
|
+
id: string;
|
|
29
|
+
unavailable?: boolean;
|
|
30
|
+
};
|
|
31
|
+
GUILD_ROLE_CREATE: {
|
|
32
|
+
guild_id: string;
|
|
33
|
+
role: MicupRole;
|
|
34
|
+
};
|
|
35
|
+
GUILD_ROLE_UPDATE: {
|
|
36
|
+
guild_id: string;
|
|
37
|
+
role: MicupRole;
|
|
38
|
+
};
|
|
39
|
+
GUILD_ROLE_DELETE: {
|
|
40
|
+
guild_id: string;
|
|
41
|
+
role_id: string;
|
|
42
|
+
};
|
|
43
|
+
GUILD_ROLE_UPDATE_BULK: {
|
|
44
|
+
guild_id: string;
|
|
45
|
+
roles: MicupRole[];
|
|
46
|
+
};
|
|
47
|
+
GUILD_MEMBER_ADD: MicupMember & {
|
|
48
|
+
guild_id: string;
|
|
49
|
+
};
|
|
50
|
+
GUILD_MEMBER_UPDATE: MicupMember & {
|
|
51
|
+
guild_id: string;
|
|
52
|
+
};
|
|
53
|
+
GUILD_MEMBER_REMOVE: {
|
|
54
|
+
guild_id: string;
|
|
55
|
+
user: MicupUser;
|
|
56
|
+
};
|
|
57
|
+
GUILD_MEMBERS_CHUNK: MicupMembersChunk;
|
|
58
|
+
CHANNEL_CREATE: MicupChannel;
|
|
59
|
+
CHANNEL_UPDATE: MicupChannel;
|
|
60
|
+
CHANNEL_DELETE: MicupChannel;
|
|
61
|
+
CHANNEL_UPDATE_BULK: {
|
|
62
|
+
guild_id?: string;
|
|
63
|
+
channels: MicupChannel[];
|
|
64
|
+
};
|
|
65
|
+
THREAD_CREATE: MicupChannel;
|
|
66
|
+
THREAD_UPDATE: MicupChannel;
|
|
67
|
+
THREAD_DELETE: MicupChannel;
|
|
68
|
+
THREAD_LIST_SYNC: {
|
|
69
|
+
guild_id: string;
|
|
70
|
+
channel_ids?: string[];
|
|
71
|
+
threads: MicupChannel[];
|
|
72
|
+
};
|
|
73
|
+
VOICE_SERVER_UPDATE: VoiceServerUpdate;
|
|
74
|
+
}
|
|
75
|
+
type Payload<Events, Name extends string> = Name extends keyof Events ? Events[Name] : unknown;
|
|
76
|
+
type EventHandler<Data = unknown> = (data: Data, event: GatewayDispatch, signal: AbortSignal) => void | Promise<void>;
|
|
77
|
+
export declare class EventMux<Events = MicupEvents> {
|
|
78
|
+
#private;
|
|
79
|
+
on<Name extends string>(name: Name, handler: EventHandler<Payload<Events, Name>>): () => void;
|
|
80
|
+
readonly handle: (event: GatewayDispatch, signal: AbortSignal) => Promise<void>;
|
|
81
|
+
}
|
|
82
|
+
export {};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export class EventMux {
|
|
2
|
+
#handlers = new Map();
|
|
3
|
+
on(name, handler) {
|
|
4
|
+
let handlers = this.#handlers.get(name);
|
|
5
|
+
if (!handlers) {
|
|
6
|
+
handlers = new Set();
|
|
7
|
+
this.#handlers.set(name, handlers);
|
|
8
|
+
}
|
|
9
|
+
const registered = (data, event, signal) => handler(data, event, signal);
|
|
10
|
+
handlers.add(registered);
|
|
11
|
+
return () => {
|
|
12
|
+
handlers.delete(registered);
|
|
13
|
+
if (handlers.size === 0 && this.#handlers.get(name) === handlers)
|
|
14
|
+
this.#handlers.delete(name);
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
handle = async (event, signal) => {
|
|
18
|
+
for (const handler of this.#handlers.get(event.name) ?? []) {
|
|
19
|
+
signal.throwIfAborted();
|
|
20
|
+
await handler(event.data, event, signal);
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type MicupInteraction } from '../model/interaction.js';
|
|
2
|
+
type InteractionHandler = (interaction: MicupInteraction, signal: AbortSignal) => void | Promise<void>;
|
|
3
|
+
export declare class InteractionRouter {
|
|
4
|
+
#private;
|
|
5
|
+
command(path: string, handler: InteractionHandler): this;
|
|
6
|
+
autocomplete(path: string, handler: InteractionHandler): this;
|
|
7
|
+
component(customId: string, handler: InteractionHandler): this;
|
|
8
|
+
modal(customId: string, handler: InteractionHandler): this;
|
|
9
|
+
handle(interaction: MicupInteraction, signal: AbortSignal): Promise<boolean>;
|
|
10
|
+
}
|
|
11
|
+
export {};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { InteractionType, commandPath } from '../model/interaction.js';
|
|
2
|
+
export class InteractionRouter {
|
|
3
|
+
#routes = new Map();
|
|
4
|
+
command(path, handler) {
|
|
5
|
+
return this.#set(InteractionType.Command, path, handler);
|
|
6
|
+
}
|
|
7
|
+
autocomplete(path, handler) {
|
|
8
|
+
return this.#set(InteractionType.Autocomplete, path, handler);
|
|
9
|
+
}
|
|
10
|
+
component(customId, handler) {
|
|
11
|
+
return this.#set(InteractionType.Component, customId, handler);
|
|
12
|
+
}
|
|
13
|
+
modal(customId, handler) {
|
|
14
|
+
return this.#set(InteractionType.Modal, customId, handler);
|
|
15
|
+
}
|
|
16
|
+
#set(type, key, handler) {
|
|
17
|
+
if (!key || typeof handler !== 'function')
|
|
18
|
+
throw new TypeError('Interaction route and handler are required');
|
|
19
|
+
let routes = this.#routes.get(type);
|
|
20
|
+
if (!routes) {
|
|
21
|
+
routes = new Map();
|
|
22
|
+
this.#routes.set(type, routes);
|
|
23
|
+
}
|
|
24
|
+
routes.set(key, handler);
|
|
25
|
+
return this;
|
|
26
|
+
}
|
|
27
|
+
async handle(interaction, signal) {
|
|
28
|
+
const routes = this.#routes.get(interaction.type);
|
|
29
|
+
if (!routes || !interaction.data)
|
|
30
|
+
return false;
|
|
31
|
+
let key;
|
|
32
|
+
if (interaction.type === 2 || interaction.type === 4)
|
|
33
|
+
key = commandPath(interaction.data).join(' ');
|
|
34
|
+
if (interaction.type === 3 || interaction.type === 5)
|
|
35
|
+
key = interaction.data.custom_id;
|
|
36
|
+
if (!key)
|
|
37
|
+
return false;
|
|
38
|
+
let handler = routes.get(key);
|
|
39
|
+
if (!handler) {
|
|
40
|
+
let longest = -1;
|
|
41
|
+
for (const [candidate, route] of routes) {
|
|
42
|
+
if (candidate.endsWith('*') && candidate.length > longest && key.startsWith(candidate.slice(0, -1))) {
|
|
43
|
+
longest = candidate.length;
|
|
44
|
+
handler = route;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (!handler)
|
|
49
|
+
return false;
|
|
50
|
+
signal.throwIfAborted();
|
|
51
|
+
await handler(interaction, signal);
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type GatewayDispatch } from './protocol.js';
|
|
2
|
+
export interface GatewayResume {
|
|
3
|
+
sessionId?: string;
|
|
4
|
+
sequence: number | null;
|
|
5
|
+
}
|
|
6
|
+
import type { Presence } from '../model/presence.js';
|
|
7
|
+
interface ConnectionOptions {
|
|
8
|
+
endpoint: URL;
|
|
9
|
+
token: string;
|
|
10
|
+
shard: readonly [number, number];
|
|
11
|
+
ignoredEvents: readonly string[];
|
|
12
|
+
flags: number;
|
|
13
|
+
presence: () => Presence | undefined;
|
|
14
|
+
resume: GatewayResume;
|
|
15
|
+
beforeIdentify?: (signal: AbortSignal) => Promise<void>;
|
|
16
|
+
dispatch: (event: GatewayDispatch, signal: AbortSignal) => Promise<void>;
|
|
17
|
+
receive: (event: GatewayDispatch) => void;
|
|
18
|
+
onInvalidate: () => void;
|
|
19
|
+
onReady: (resumed: boolean) => void;
|
|
20
|
+
onGatewayError?: (data: unknown) => void;
|
|
21
|
+
}
|
|
22
|
+
export declare class GatewayConnection {
|
|
23
|
+
#private;
|
|
24
|
+
private readonly options;
|
|
25
|
+
private constructor();
|
|
26
|
+
static run(options: ConnectionOptions, signal: AbortSignal, onConnect: (connection: GatewayConnection) => void): Promise<void>;
|
|
27
|
+
get latency(): number | undefined;
|
|
28
|
+
send(opcode: number, data: unknown, signal?: AbortSignal): Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
export {};
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
2
|
+
import WebSocket from 'ws';
|
|
3
|
+
import { decodePacket, GatewayCloseError, GatewayOpcode } from './protocol.js';
|
|
4
|
+
class CommandWindow {
|
|
5
|
+
capacity;
|
|
6
|
+
duration;
|
|
7
|
+
#timestamps = [];
|
|
8
|
+
constructor(capacity, duration) {
|
|
9
|
+
this.capacity = capacity;
|
|
10
|
+
this.duration = duration;
|
|
11
|
+
}
|
|
12
|
+
async acquire(signal) {
|
|
13
|
+
while (true) {
|
|
14
|
+
signal.throwIfAborted();
|
|
15
|
+
const now = performance.now();
|
|
16
|
+
while (this.#timestamps[0] <= now - this.duration) {
|
|
17
|
+
this.#timestamps.shift();
|
|
18
|
+
}
|
|
19
|
+
if (this.#timestamps.length < this.capacity) {
|
|
20
|
+
this.#timestamps.push(now);
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
await delay(Math.ceil(this.#timestamps[0] + this.duration - now), undefined, { signal });
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
export class GatewayConnection {
|
|
28
|
+
options;
|
|
29
|
+
#socket;
|
|
30
|
+
#lifetime = new AbortController();
|
|
31
|
+
#commands = new CommandWindow(540, 60_000);
|
|
32
|
+
#presence = new CommandWindow(5, 20_000);
|
|
33
|
+
#dispatches = [];
|
|
34
|
+
#helloTimer;
|
|
35
|
+
#heartbeat;
|
|
36
|
+
#pendingHeartbeat;
|
|
37
|
+
#authenticated = false;
|
|
38
|
+
#authenticating = false;
|
|
39
|
+
#draining = false;
|
|
40
|
+
#generation = new AbortController();
|
|
41
|
+
#latency;
|
|
42
|
+
constructor(options) {
|
|
43
|
+
this.options = options;
|
|
44
|
+
this.#socket = new WebSocket(options.endpoint, {
|
|
45
|
+
maxPayload: 8 * 1024 * 1024,
|
|
46
|
+
handshakeTimeout: 10_000,
|
|
47
|
+
followRedirects: false,
|
|
48
|
+
perMessageDeflate: false,
|
|
49
|
+
headers: { 'User-Agent': 'micup.ts' },
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
static async run(options, signal, onConnect) {
|
|
53
|
+
signal.throwIfAborted();
|
|
54
|
+
if (!options.resume.sessionId || options.resume.sequence === null) {
|
|
55
|
+
await options.beforeIdentify?.(signal);
|
|
56
|
+
signal.throwIfAborted();
|
|
57
|
+
}
|
|
58
|
+
const connection = new GatewayConnection(options);
|
|
59
|
+
onConnect(connection);
|
|
60
|
+
await connection.#read(signal);
|
|
61
|
+
}
|
|
62
|
+
get latency() {
|
|
63
|
+
return this.#latency;
|
|
64
|
+
}
|
|
65
|
+
async send(opcode, data, signal) {
|
|
66
|
+
const lifetime = this.#lifetime.signal;
|
|
67
|
+
const combined = signal ? AbortSignal.any([signal, lifetime]) : lifetime;
|
|
68
|
+
const payload = this.#encode(opcode, data);
|
|
69
|
+
if (opcode === GatewayOpcode.PresenceUpdate) {
|
|
70
|
+
await this.#presence.acquire(combined);
|
|
71
|
+
}
|
|
72
|
+
await this.#commands.acquire(combined);
|
|
73
|
+
combined.throwIfAborted();
|
|
74
|
+
this.#write(payload);
|
|
75
|
+
}
|
|
76
|
+
#read(signal) {
|
|
77
|
+
return new Promise((resolve, reject) => {
|
|
78
|
+
const finish = (error) => {
|
|
79
|
+
if (this.#lifetime.signal.aborted)
|
|
80
|
+
return;
|
|
81
|
+
signal.removeEventListener('abort', onAbort);
|
|
82
|
+
this.#lifetime.abort(error);
|
|
83
|
+
this.#generation.abort(error);
|
|
84
|
+
this.#dispatches.length = 0;
|
|
85
|
+
clearTimeout(this.#helloTimer);
|
|
86
|
+
clearInterval(this.#heartbeat);
|
|
87
|
+
this.#socket.terminate();
|
|
88
|
+
if (error === undefined || signal.aborted)
|
|
89
|
+
resolve();
|
|
90
|
+
else
|
|
91
|
+
reject(error);
|
|
92
|
+
};
|
|
93
|
+
const onAbort = () => finish();
|
|
94
|
+
this.#socket.on('error', () => finish(new Error('Micup Gateway connection failed')));
|
|
95
|
+
this.#socket.on('close', (code, reason) => finish(new GatewayCloseError(code, reason.toString())));
|
|
96
|
+
this.#socket.on('message', (data, binary) => {
|
|
97
|
+
if (this.#lifetime.signal.aborted)
|
|
98
|
+
return;
|
|
99
|
+
try {
|
|
100
|
+
this.#receive(data, binary, finish);
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
finish(error);
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
this.#helloTimer = setTimeout(() => finish(new Error('Micup Gateway HELLO timed out')), 10_000);
|
|
107
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
108
|
+
if (signal.aborted)
|
|
109
|
+
onAbort();
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
#receive(raw, binary, finish) {
|
|
113
|
+
if (binary)
|
|
114
|
+
throw new Error('Unexpected binary Micup Gateway packet');
|
|
115
|
+
const packet = decodePacket(raw.toString());
|
|
116
|
+
const op = GatewayOpcode;
|
|
117
|
+
switch (packet.op) {
|
|
118
|
+
case op.Hello: {
|
|
119
|
+
if (this.#heartbeat)
|
|
120
|
+
throw new Error('Duplicate Micup Gateway HELLO');
|
|
121
|
+
const interval = packet.d?.heartbeat_interval;
|
|
122
|
+
if (typeof interval !== 'number' || !Number.isFinite(interval) || interval < 100 ||
|
|
123
|
+
interval > 2_147_483_647) {
|
|
124
|
+
throw new Error('Invalid Micup Gateway heartbeat interval');
|
|
125
|
+
}
|
|
126
|
+
clearTimeout(this.#helloTimer);
|
|
127
|
+
this.#heartbeat = setInterval(() => {
|
|
128
|
+
try {
|
|
129
|
+
if (this.#pendingHeartbeat !== undefined)
|
|
130
|
+
throw new Error('Micup Gateway heartbeat timed out');
|
|
131
|
+
this.#beat();
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
finish(error);
|
|
135
|
+
}
|
|
136
|
+
}, interval);
|
|
137
|
+
this.#authenticate(false).catch(finish);
|
|
138
|
+
break;
|
|
139
|
+
}
|
|
140
|
+
case op.Heartbeat:
|
|
141
|
+
this.#beat();
|
|
142
|
+
break;
|
|
143
|
+
case op.HeartbeatAck:
|
|
144
|
+
if (this.#pendingHeartbeat !== undefined) {
|
|
145
|
+
this.#latency = performance.now() - this.#pendingHeartbeat;
|
|
146
|
+
this.#pendingHeartbeat = undefined;
|
|
147
|
+
}
|
|
148
|
+
break;
|
|
149
|
+
case op.Reconnect:
|
|
150
|
+
finish(new Error('Micup Gateway requested reconnect'));
|
|
151
|
+
break;
|
|
152
|
+
case op.InvalidSession:
|
|
153
|
+
if (!this.#authenticated)
|
|
154
|
+
throw new Error('Unexpected Micup Gateway invalid session');
|
|
155
|
+
this.#authenticated = false;
|
|
156
|
+
this.options.resume.sessionId = undefined;
|
|
157
|
+
this.options.resume.sequence = null;
|
|
158
|
+
this.#generation.abort();
|
|
159
|
+
this.#generation = new AbortController();
|
|
160
|
+
this.#dispatches.length = 0;
|
|
161
|
+
this.options.onInvalidate();
|
|
162
|
+
this.#authenticate(true).catch(finish);
|
|
163
|
+
break;
|
|
164
|
+
case op.GatewayError:
|
|
165
|
+
this.options.onGatewayError?.(packet.d);
|
|
166
|
+
break;
|
|
167
|
+
case op.Dispatch:
|
|
168
|
+
if (!this.#authenticated)
|
|
169
|
+
throw new Error('Micup Gateway dispatched before authentication');
|
|
170
|
+
if (this.#dispatches.length >= 1024)
|
|
171
|
+
throw new Error('Micup Gateway event queue is full');
|
|
172
|
+
this.options.receive(this.#dispatch(packet));
|
|
173
|
+
this.#dispatches.push(packet);
|
|
174
|
+
this.#drain(finish).catch(finish);
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
async #authenticate(waitForIdentify) {
|
|
179
|
+
if (this.#authenticating)
|
|
180
|
+
throw new Error('Micup Gateway authentication is already pending');
|
|
181
|
+
this.#authenticating = true;
|
|
182
|
+
try {
|
|
183
|
+
const { resume, token, shard, flags, ignoredEvents } = this.options;
|
|
184
|
+
if (resume.sessionId && resume.sequence !== null) {
|
|
185
|
+
this.#write(this.#encode(GatewayOpcode.Resume, {
|
|
186
|
+
token, session_id: resume.sessionId, seq: resume.sequence,
|
|
187
|
+
}));
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
if (waitForIdentify)
|
|
191
|
+
await this.options.beforeIdentify?.(this.#lifetime.signal);
|
|
192
|
+
this.#lifetime.signal.throwIfAborted();
|
|
193
|
+
const presence = this.options.presence();
|
|
194
|
+
this.#write(this.#encode(GatewayOpcode.Identify, {
|
|
195
|
+
token,
|
|
196
|
+
properties: { os: process.platform, browser: 'micup.ts', device: 'micup.ts' },
|
|
197
|
+
shard,
|
|
198
|
+
...(flags ? { flags } : {}),
|
|
199
|
+
...(presence ? { presence } : {}),
|
|
200
|
+
...(ignoredEvents.length ? { ignored_events: ignoredEvents } : {}),
|
|
201
|
+
}));
|
|
202
|
+
}
|
|
203
|
+
this.#authenticated = true;
|
|
204
|
+
}
|
|
205
|
+
finally {
|
|
206
|
+
this.#authenticating = false;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
async #drain(finish) {
|
|
210
|
+
if (this.#draining)
|
|
211
|
+
return;
|
|
212
|
+
this.#draining = true;
|
|
213
|
+
try {
|
|
214
|
+
while (!this.#lifetime.signal.aborted) {
|
|
215
|
+
const packet = this.#dispatches.shift();
|
|
216
|
+
if (!packet)
|
|
217
|
+
return;
|
|
218
|
+
const signal = this.#generation.signal;
|
|
219
|
+
const name = packet.t;
|
|
220
|
+
const sequence = packet.s ?? null;
|
|
221
|
+
try {
|
|
222
|
+
if (name === 'READY') {
|
|
223
|
+
this.options.resume.sessionId = undefined;
|
|
224
|
+
this.options.resume.sequence = null;
|
|
225
|
+
}
|
|
226
|
+
await this.options.dispatch(this.#dispatch(packet), signal);
|
|
227
|
+
if (signal.aborted)
|
|
228
|
+
continue;
|
|
229
|
+
if (name === 'READY') {
|
|
230
|
+
const id = packet.d?.session_id;
|
|
231
|
+
if (typeof id !== 'string' || !id)
|
|
232
|
+
throw new Error('Micup READY omitted the session ID');
|
|
233
|
+
this.options.resume.sessionId = id;
|
|
234
|
+
}
|
|
235
|
+
if (sequence !== null)
|
|
236
|
+
this.options.resume.sequence = sequence;
|
|
237
|
+
if (name === 'READY' || name === 'RESUMED')
|
|
238
|
+
this.options.onReady(name === 'RESUMED');
|
|
239
|
+
}
|
|
240
|
+
catch (error) {
|
|
241
|
+
if (!signal.aborted) {
|
|
242
|
+
finish(error ?? new Error('Micup Gateway handler failed'));
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
finally {
|
|
249
|
+
this.#draining = false;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
#dispatch(packet) {
|
|
253
|
+
return { name: packet.t, sequence: packet.s ?? null, data: packet.d, shardId: this.options.shard[0] };
|
|
254
|
+
}
|
|
255
|
+
#beat() {
|
|
256
|
+
this.#pendingHeartbeat ??= performance.now();
|
|
257
|
+
this.#write(this.#encode(GatewayOpcode.Heartbeat, this.options.resume.sequence));
|
|
258
|
+
}
|
|
259
|
+
#encode(op, d) {
|
|
260
|
+
if (!Number.isSafeInteger(op) || op < 0)
|
|
261
|
+
throw new TypeError('Invalid Micup Gateway opcode');
|
|
262
|
+
const payload = JSON.stringify({ op, d });
|
|
263
|
+
if (Buffer.byteLength(payload) > 16_384)
|
|
264
|
+
throw new RangeError('Micup Gateway payload exceeds 16,384 bytes');
|
|
265
|
+
return payload;
|
|
266
|
+
}
|
|
267
|
+
#write(payload) {
|
|
268
|
+
if (this.#socket.readyState !== WebSocket.OPEN)
|
|
269
|
+
throw new Error('Micup Gateway is disconnected');
|
|
270
|
+
this.#socket.send(payload);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export declare const GatewayOpcode: {
|
|
2
|
+
readonly Dispatch: 0;
|
|
3
|
+
readonly Heartbeat: 1;
|
|
4
|
+
readonly Identify: 2;
|
|
5
|
+
readonly PresenceUpdate: 3;
|
|
6
|
+
readonly VoiceStateUpdate: 4;
|
|
7
|
+
readonly Resume: 6;
|
|
8
|
+
readonly Reconnect: 7;
|
|
9
|
+
readonly RequestGuildMembers: 8;
|
|
10
|
+
readonly InvalidSession: 9;
|
|
11
|
+
readonly Hello: 10;
|
|
12
|
+
readonly HeartbeatAck: 11;
|
|
13
|
+
readonly GatewayError: 12;
|
|
14
|
+
readonly VoiceSignal: 13;
|
|
15
|
+
readonly LazyRequest: 14;
|
|
16
|
+
readonly RequestGuildCounts: 15;
|
|
17
|
+
readonly RequestChannelMemberCounts: 16;
|
|
18
|
+
readonly RequestForumUnreads: 28;
|
|
19
|
+
};
|
|
20
|
+
export declare class GatewayCloseError extends Error {
|
|
21
|
+
readonly code: number;
|
|
22
|
+
readonly reason: string;
|
|
23
|
+
constructor(code: number, reason: string);
|
|
24
|
+
get fatal(): boolean;
|
|
25
|
+
get resetsSession(): boolean;
|
|
26
|
+
}
|
|
27
|
+
export interface GatewayDispatch {
|
|
28
|
+
readonly name: string;
|
|
29
|
+
readonly data: unknown;
|
|
30
|
+
readonly sequence: number | null;
|
|
31
|
+
readonly shardId: number;
|
|
32
|
+
}
|
|
33
|
+
export interface GatewayPacket {
|
|
34
|
+
op: number;
|
|
35
|
+
d?: unknown;
|
|
36
|
+
s?: number | null;
|
|
37
|
+
t?: string;
|
|
38
|
+
}
|
|
39
|
+
export declare function decodePacket(data: string): GatewayPacket;
|
|
40
|
+
export declare function gatewayEndpoint(raw: string): URL;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
export const GatewayOpcode = {
|
|
2
|
+
Dispatch: 0,
|
|
3
|
+
Heartbeat: 1,
|
|
4
|
+
Identify: 2,
|
|
5
|
+
PresenceUpdate: 3,
|
|
6
|
+
VoiceStateUpdate: 4,
|
|
7
|
+
Resume: 6,
|
|
8
|
+
Reconnect: 7,
|
|
9
|
+
RequestGuildMembers: 8,
|
|
10
|
+
InvalidSession: 9,
|
|
11
|
+
Hello: 10,
|
|
12
|
+
HeartbeatAck: 11,
|
|
13
|
+
GatewayError: 12,
|
|
14
|
+
VoiceSignal: 13,
|
|
15
|
+
LazyRequest: 14,
|
|
16
|
+
RequestGuildCounts: 15,
|
|
17
|
+
RequestChannelMemberCounts: 16,
|
|
18
|
+
RequestForumUnreads: 28,
|
|
19
|
+
};
|
|
20
|
+
const fatalCloseCodes = new Set([4001, 4002, 4003, 4004, 4005, 4010, 4011, 4012]);
|
|
21
|
+
export class GatewayCloseError extends Error {
|
|
22
|
+
code;
|
|
23
|
+
reason;
|
|
24
|
+
constructor(code, reason) {
|
|
25
|
+
super('Micup Gateway closed with code ' + code + (reason ? ': ' + reason : ''));
|
|
26
|
+
this.code = code;
|
|
27
|
+
this.reason = reason;
|
|
28
|
+
this.name = 'GatewayCloseError';
|
|
29
|
+
}
|
|
30
|
+
get fatal() {
|
|
31
|
+
return fatalCloseCodes.has(this.code);
|
|
32
|
+
}
|
|
33
|
+
get resetsSession() {
|
|
34
|
+
return this.code === 4007 || this.code === 4009;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
export function decodePacket(data) {
|
|
38
|
+
const packet = JSON.parse(data);
|
|
39
|
+
if (!packet || !Number.isInteger(packet.op)) {
|
|
40
|
+
throw new Error('Invalid Micup Gateway packet');
|
|
41
|
+
}
|
|
42
|
+
if (packet.op === GatewayOpcode.Dispatch && (typeof packet.t !== 'string' || !packet.t ||
|
|
43
|
+
(packet.s != null && (!Number.isSafeInteger(packet.s) || packet.s < 0)))) {
|
|
44
|
+
throw new Error('Invalid Micup Gateway dispatch');
|
|
45
|
+
}
|
|
46
|
+
return packet;
|
|
47
|
+
}
|
|
48
|
+
export function gatewayEndpoint(raw) {
|
|
49
|
+
const endpoint = new URL(raw);
|
|
50
|
+
if (!['ws:', 'wss:'].includes(endpoint.protocol) || endpoint.username ||
|
|
51
|
+
endpoint.password || endpoint.hash) {
|
|
52
|
+
throw new TypeError('Invalid Micup Gateway endpoint');
|
|
53
|
+
}
|
|
54
|
+
endpoint.searchParams.set('v', '1');
|
|
55
|
+
endpoint.searchParams.set('encoding', 'json');
|
|
56
|
+
endpoint.searchParams.delete('compress');
|
|
57
|
+
endpoint.searchParams.delete('stream');
|
|
58
|
+
return endpoint;
|
|
59
|
+
}
|