cloudstorm 0.5.8 → 0.6.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.
@@ -1,444 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- const events_1 = require("events");
6
- const BetterWs_1 = __importDefault(require("../structures/BetterWs"));
7
- const Constants_1 = require("../Constants");
8
- const Intents_1 = __importDefault(require("../Intents"));
9
- let reconnecting = false;
10
- const recoverableErrorsRegex = /EAI_AGAIN/;
11
- /**
12
- * Class used for acting based on received events.
13
- *
14
- * This class is automatically instantiated by the library and is documented for reference.
15
- */
16
- class DiscordConnector extends events_1.EventEmitter {
17
- /**
18
- * Create a new Discord Connector.
19
- * @param id id of the shard that created this class.
20
- * @param client Main client instance.
21
- */
22
- constructor(id, client) {
23
- super();
24
- this.heartbeatTimeout = null;
25
- this.heartbeatInterval = 0;
26
- this._trace = null;
27
- this.seq = 0;
28
- this.status = "disconnected";
29
- this.sessionId = null;
30
- this.lastACKAt = 0;
31
- this.lastHeartbeatSend = 0;
32
- this.latency = 0;
33
- this._closing = false;
34
- this.resumeAddress = null;
35
- this.id = id;
36
- this.client = client;
37
- this.options = client.options;
38
- this.reconnect = this.options.reconnect || true;
39
- this.identifyAddress = this.options.endpoint;
40
- this.betterWs = new BetterWs_1.default(this.identifyAddress, this.options.ws);
41
- this.betterWs.on("ws_open", () => {
42
- this.status = "connecting";
43
- this.emit("stateChange", "connecting");
44
- reconnecting = false;
45
- });
46
- this.betterWs.on("ws_message", msg => this.messageAction(msg));
47
- this.betterWs.on("ws_close", (code, reason) => this.handleWsClose(code, reason));
48
- this.betterWs.on("debug", event => this.client.emit("debug", event));
49
- this.betterWs.on("debug_send", data => this.client.emit("rawSend", data));
50
- }
51
- /**
52
- * Connect to Discord.
53
- */
54
- async connect() {
55
- this._closing = false;
56
- this.client.emit("debug", `Shard ${this.id} connecting to gateway`);
57
- // The address should already be updated if resuming/identifying
58
- return this.betterWs.connect()
59
- .catch(error => {
60
- const e = String(error);
61
- if (recoverableErrorsRegex.test(e))
62
- setTimeout(() => this.connect(), 5000);
63
- });
64
- }
65
- /**
66
- * Close the websocket connection and disconnect.
67
- */
68
- async disconnect() {
69
- this._closing = true;
70
- return this.betterWs.close(1000, "Disconnected by User");
71
- }
72
- /**
73
- * Called with a parsed Websocket message to execute further actions.
74
- * @param message Message that was received.
75
- */
76
- async messageAction(message) {
77
- this.client.emit("rawReceive", message);
78
- if (message.s) {
79
- if (message.s > this.seq + 1) {
80
- this.client.emit("debug", `Shard ${this.id}, invalid sequence: current: ${this.seq} message: ${message.s}`);
81
- this.seq = message.s;
82
- this.resume();
83
- }
84
- this.seq = message.s;
85
- }
86
- switch (message.op) {
87
- case Constants_1.GATEWAY_OP_CODES.DISPATCH:
88
- this.handleDispatch(message);
89
- break;
90
- case Constants_1.GATEWAY_OP_CODES.HEARTBEAT:
91
- this.heartbeat();
92
- break;
93
- case Constants_1.GATEWAY_OP_CODES.RECONNECT:
94
- this.client.emit("debug", `Gateway asked shard ${this.id} to reconnect`);
95
- if (this.options.reconnect && this.betterWs.status !== 2)
96
- this._reconnect(true);
97
- else
98
- this.disconnect();
99
- break;
100
- case Constants_1.GATEWAY_OP_CODES.INVALID_SESSION:
101
- if (message.d && this.sessionId)
102
- this.resume();
103
- else {
104
- this.seq = 0;
105
- this.sessionId = "";
106
- this.emit("queueIdentify", this.id);
107
- }
108
- break;
109
- case Constants_1.GATEWAY_OP_CODES.HELLO:
110
- this.client.emit("debug", `Shard ${this.id} received HELLO`);
111
- this.heartbeat();
112
- this.heartbeatInterval = message.d.heartbeat_interval;
113
- this.heartbeatTimeout = setInterval(() => {
114
- if (this.lastACKAt <= Date.now() - (this.heartbeatInterval + 5000)) {
115
- this.client.emit("debug", `Shard ${this.id} has not received a heartbeat ACK in ${this.heartbeatInterval + 5000}ms.`);
116
- if (this.options.reconnect && this.betterWs.status !== 2)
117
- this._reconnect(true);
118
- else
119
- this.disconnect();
120
- }
121
- else
122
- this.heartbeat();
123
- }, this.heartbeatInterval);
124
- this._trace = message.d._trace;
125
- this.emit("queueIdentify", this.id);
126
- break;
127
- case Constants_1.GATEWAY_OP_CODES.HEARTBEAT_ACK:
128
- this.lastACKAt = Date.now();
129
- this.latency = this.lastACKAt - this.lastHeartbeatSend;
130
- break;
131
- default:
132
- this.emit("event", message);
133
- }
134
- }
135
- /**
136
- * Reset this connector to be ready to resume or hard reconnect, then connect.
137
- * @param resume Whether or not the client intends to send an OP 6 RESUME later.
138
- */
139
- async _reconnect(resume = false) {
140
- if (resume)
141
- reconnecting = true;
142
- if (this.betterWs.status === 2)
143
- void this.client.emit("error", `Client was attempting to ${resume ? "resume" : "reconnect"} while the WebSocket was still in the connecting state. This should never happen.`);
144
- await this.betterWs.close(resume ? 4000 : 1012, "reconnecting");
145
- if (resume) {
146
- this.clearHeartBeat();
147
- if (this.resumeAddress)
148
- this.betterWs.address = this.resumeAddress;
149
- else
150
- this.betterWs.address = this.identifyAddress;
151
- }
152
- else {
153
- this.reset();
154
- this.betterWs.address = this.identifyAddress;
155
- }
156
- this.connect();
157
- }
158
- /**
159
- * Hard reset this connector.
160
- */
161
- reset() {
162
- this.sessionId = null;
163
- this.seq = 0;
164
- this.lastACKAt = 0;
165
- this._trace = null;
166
- this.clearHeartBeat();
167
- }
168
- /**
169
- * Clear the heart beat interval, set it to null and set the cached heartbeat_interval as 0.
170
- */
171
- clearHeartBeat() {
172
- if (this.heartbeatTimeout)
173
- clearInterval(this.heartbeatTimeout);
174
- this.heartbeatTimeout = null;
175
- this.heartbeatInterval = 0;
176
- }
177
- /**
178
- * Send an OP 2 IDENTIFY to the gateway or an OP 6 RESUME if forceful identify is falsy.
179
- * @param force Whether CloudStorm should send an OP 2 IDENTIFY even if there's a session that could be resumed.
180
- */
181
- async identify(force) {
182
- if (this.betterWs.status !== 1)
183
- void this.client.emit("debug", "Client was attempting to identify when the ws was not open");
184
- if (this.sessionId && !force)
185
- return this.resume();
186
- this.client.emit("debug", `Shard ${this.id} is identifying`);
187
- this.status = "identifying";
188
- this.emit("stateChange", "identifying");
189
- const data = {
190
- op: Constants_1.GATEWAY_OP_CODES.IDENTIFY,
191
- d: {
192
- token: this.options.token,
193
- properties: {
194
- os: process.platform,
195
- browser: "CloudStorm",
196
- device: "CloudStorm"
197
- },
198
- large_threshold: this.options.largeGuildThreshold,
199
- shard: [this.id, this.options.totalShards || 1],
200
- intents: this.options.intents ? Intents_1.default.resolve(this.options.intents) : 0
201
- }
202
- };
203
- if (this.options.initialPresence)
204
- Object.assign(data.d, { presence: this._checkPresenceData(this.options.initialPresence) });
205
- return this.betterWs.sendMessage(data);
206
- }
207
- /**
208
- * Send an OP 6 RESUME to the gateway.
209
- */
210
- async resume() {
211
- if (this.betterWs.status !== 1)
212
- void this.client.emit("debug", "Client was attempting to resume when the ws was not open");
213
- this.client.emit("debug", `Shard ${this.id} is resuming`);
214
- this.status = "resuming";
215
- this.emit("stateChange", "resuming");
216
- return this.betterWs.sendMessage({
217
- op: Constants_1.GATEWAY_OP_CODES.RESUME,
218
- d: { seq: this.seq, token: this.options.token, session_id: this.sessionId }
219
- });
220
- }
221
- /**
222
- * Send an OP 1 HEARTBEAT to the gateway.
223
- */
224
- heartbeat() {
225
- if (this.betterWs.status !== 1)
226
- void this.client.emit("debug", "Client was attempting to heartbeat when the ws was not open");
227
- this.betterWs.sendMessage({ op: Constants_1.GATEWAY_OP_CODES.HEARTBEAT, d: this.seq });
228
- this.lastHeartbeatSend = Date.now();
229
- }
230
- /**
231
- * Handle dispatch events.
232
- * @param message Message received from the websocket.
233
- */
234
- handleDispatch(message) {
235
- switch (message.t) {
236
- case "READY":
237
- case "RESUMED":
238
- if (message.t === "READY") {
239
- if (message.d.resume_gateway_url)
240
- this.resumeAddress = message.d.resume_gateway_url;
241
- this.sessionId = message.d.session_id;
242
- }
243
- this.status = "ready";
244
- this.emit("stateChange", "ready");
245
- this._trace = message.d._trace;
246
- this.emit("ready", message.t === "RESUMED");
247
- this.emit("event", message);
248
- break;
249
- default:
250
- this.emit("event", message);
251
- }
252
- }
253
- /**
254
- * Handle a close from the underlying websocket.
255
- * @param code Websocket close code.
256
- * @param reason Close reason if any.
257
- */
258
- handleWsClose(code, reason) {
259
- let gracefulClose = false;
260
- this.status = "disconnected";
261
- this.emit("stateChange", "disconnected");
262
- // Disallowed Intents.
263
- if (code === 4014) {
264
- this.betterWs.address = this.identifyAddress;
265
- this.client.emit("error", "Disallowed Intents, check your client options and application page.");
266
- }
267
- // Invalid Intents.
268
- if (code === 4013) {
269
- this.betterWs.address = this.identifyAddress;
270
- this.client.emit("error", "Invalid Intents data, check your client options.");
271
- }
272
- // Invalid API version.
273
- if (code === 4012) {
274
- this.betterWs.address = this.identifyAddress;
275
- this.client.emit("error", "Invalid API version.");
276
- }
277
- // Sharding required.
278
- if (code === 4011) {
279
- this.betterWs.address = this.identifyAddress;
280
- this.client.emit("error", "Shard would be on over 2500 guilds. Add more shards.");
281
- }
282
- // Invalid shard.
283
- if (code === 4010) {
284
- this.betterWs.address = this.identifyAddress;
285
- this.client.emit("error", "Invalid sharding data, check your client options.");
286
- }
287
- // Session timed out.
288
- // force identify if the session is marked as invalid.
289
- if (code === 4009) {
290
- this.client.emit("error", "Session timed out.");
291
- this.clearHeartBeat();
292
- this.betterWs.address = this.identifyAddress;
293
- this.connect();
294
- }
295
- // Rate limited.
296
- if (code === 4008) {
297
- this.client.emit("error", "You are being rate limited. Wait before sending more packets.");
298
- this.clearHeartBeat();
299
- if (this.resumeAddress)
300
- this.betterWs.address = this.resumeAddress;
301
- else
302
- this.betterWs.address = this.identifyAddress;
303
- this.connect();
304
- }
305
- // Invalid sequence.
306
- if (code === 4007) {
307
- this.client.emit("error", "Invalid sequence. Reconnecting and starting a new session.");
308
- this.reset();
309
- this.betterWs.address = this.identifyAddress;
310
- this.connect();
311
- }
312
- // Already authenticated.
313
- if (code === 4005) {
314
- this.client.emit("error", "You sent more than one OP 2 IDENTIFY payload while the websocket was open.");
315
- this.clearHeartBeat();
316
- if (this.resumeAddress)
317
- this.betterWs.address = this.resumeAddress;
318
- this.connect();
319
- }
320
- // Authentication failed.
321
- if (code === 4004) {
322
- this.betterWs.address = this.identifyAddress;
323
- this.client.emit("error", "Tried to connect with an invalid token");
324
- }
325
- // Not authenticated.
326
- if (code === 4003) {
327
- this.client.emit("error", "You tried to send a packet before sending an OP 2 IDENTIFY or OP 6 RESUME.");
328
- this.clearHeartBeat();
329
- if (this.resumeAddress)
330
- this.betterWs.address = this.resumeAddress;
331
- else
332
- this.betterWs.address = this.identifyAddress;
333
- this.connect();
334
- }
335
- // Decode error.
336
- if (code === 4002) {
337
- this.client.emit("error", "You sent an invalid payload");
338
- this.clearHeartBeat();
339
- if (this.resumeAddress)
340
- this.betterWs.address = this.resumeAddress;
341
- else
342
- this.betterWs.address = this.identifyAddress;
343
- this.connect();
344
- }
345
- // Invalid opcode.
346
- if (code === 4001) {
347
- this.client.emit("error", "You sent an invalid opcode or invalid payload for an opcode");
348
- this.clearHeartBeat();
349
- if (this.resumeAddress)
350
- this.betterWs.address = this.resumeAddress;
351
- else
352
- this.betterWs.address = this.identifyAddress;
353
- this.connect();
354
- }
355
- // Generic error / safe self closing code.
356
- if (code === 4000) {
357
- if (reconnecting)
358
- gracefulClose = true;
359
- else {
360
- this.client.emit("error", "Error code 4000 received. Attempting to resume");
361
- this.clearHeartBeat();
362
- if (this.resumeAddress)
363
- this.betterWs.address = this.resumeAddress;
364
- else
365
- this.betterWs.address = this.identifyAddress;
366
- this.connect();
367
- }
368
- }
369
- // Don't try to reconnect when true
370
- if (code === 1000 && this._closing)
371
- gracefulClose = true;
372
- this._closing = false;
373
- if (gracefulClose)
374
- this.clearHeartBeat();
375
- this.emit("disconnect", code, reason, gracefulClose);
376
- }
377
- /**
378
- * Send an OP 3 PRESENCE_UPDATE to the gateway.
379
- * @param data Presence data to send.
380
- */
381
- async presenceUpdate(data) {
382
- return this.betterWs.sendMessage({ op: Constants_1.GATEWAY_OP_CODES.PRESENCE_UPDATE, d: this._checkPresenceData(data) });
383
- }
384
- /**
385
- * Send an OP 4 VOICE_STATE_UPDATE to the gateway.
386
- * @param data Voice state update data to send.
387
- */
388
- async voiceStateUpdate(data) {
389
- if (!data)
390
- return Promise.resolve();
391
- return this.betterWs.sendMessage({ op: Constants_1.GATEWAY_OP_CODES.VOICE_STATE_UPDATE, d: this._checkVoiceStateUpdateData(data) });
392
- }
393
- /**
394
- * Send an OP 8 REQUEST_GUILD_MEMBERS to the gateway.
395
- * @param data Data to send.
396
- */
397
- async requestGuildMembers(data) {
398
- return this.betterWs.sendMessage({ op: Constants_1.GATEWAY_OP_CODES.REQUEST_GUILD_MEMBERS, d: this._checkRequestGuildMembersData(data) });
399
- }
400
- /**
401
- * Checks presence data and fills in missing elements.
402
- * @param data Data to send.
403
- * @returns Data after it's fixed/checked.
404
- */
405
- _checkPresenceData(data) {
406
- data.status = data.status || "online";
407
- data.activities = data.activities && Array.isArray(data.activities) ? data.activities : [];
408
- if (data.activities) {
409
- for (const activity of data.activities) {
410
- const index = data.activities.indexOf(activity);
411
- if (activity.type === undefined)
412
- activity.type = activity.url ? 1 : 0;
413
- if (!activity.name)
414
- data.activities.splice(index, 1);
415
- }
416
- }
417
- data.afk = data.afk || false;
418
- data.since = data.since || Date.now();
419
- return data;
420
- }
421
- /**
422
- * Checks voice state update data and fills in missing elements.
423
- * @param data Data to send.
424
- * @returns Data after it's fixed/checked.
425
- */
426
- _checkVoiceStateUpdateData(data) {
427
- data.channel_id = data.channel_id || null;
428
- data.self_mute = data.self_mute || false;
429
- data.self_deaf = data.self_deaf || false;
430
- return data;
431
- }
432
- /**
433
- * Checks request guild members data and fills in missing elements.
434
- * @param data Data to send.
435
- * @returns Data after it's fixed/checked.
436
- */
437
- _checkRequestGuildMembersData(data) {
438
- data.query = data.query || "";
439
- data.limit = data.limit || 0;
440
- return data;
441
- }
442
- }
443
- DiscordConnector.default = DiscordConnector;
444
- module.exports = DiscordConnector;
@@ -1,50 +0,0 @@
1
- /// <reference types="node" />
2
- import { EventEmitter } from "events";
3
- import RatelimitBucket from "./RatelimitBucket";
4
- interface BWSEvents {
5
- ws_open: [];
6
- ws_close: [number, string];
7
- ws_message: [import("../Types").IGatewayMessage];
8
- debug_send: [import("../Types").IWSMessage];
9
- debug: [string];
10
- }
11
- interface BetterWs {
12
- addListener<E extends keyof BWSEvents>(event: E, listener: (...args: BWSEvents[E]) => any): this;
13
- emit<E extends keyof BWSEvents>(event: E, ...args: BWSEvents[E]): boolean;
14
- eventNames(): Array<keyof BWSEvents>;
15
- listenerCount(event: keyof BWSEvents): number;
16
- listeners(event: keyof BWSEvents): Array<(...args: Array<any>) => any>;
17
- off<E extends keyof BWSEvents>(event: E, listener: (...args: BWSEvents[E]) => any): this;
18
- on<E extends keyof BWSEvents>(event: E, listener: (...args: BWSEvents[E]) => any): this;
19
- once<E extends keyof BWSEvents>(event: E, listener: (...args: BWSEvents[E]) => any): this;
20
- prependListener<E extends keyof BWSEvents>(event: E, listener: (...args: BWSEvents[E]) => any): this;
21
- prependOnceListener<E extends keyof BWSEvents>(event: E, listener: (...args: BWSEvents[E]) => any): this;
22
- rawListeners(event: keyof BWSEvents): Array<(...args: Array<any>) => any>;
23
- removeAllListeners(event?: keyof BWSEvents): this;
24
- removeListener<E extends keyof BWSEvents>(event: E, listener: (...args: BWSEvents[E]) => any): this;
25
- }
26
- /**
27
- * Helper Class for simplifying the websocket connection to Discord.
28
- */
29
- declare class BetterWs extends EventEmitter {
30
- encoding: "etf" | "json";
31
- compress: boolean;
32
- address: string;
33
- options: import("../Types").IClientWSOptions;
34
- wsBucket: RatelimitBucket;
35
- presenceBucket: RatelimitBucket;
36
- private _socket;
37
- private _internal;
38
- private _connecting;
39
- constructor(address: string, options: import("../Types").IClientWSOptions);
40
- get status(): 2 | 3 | 4 | 1;
41
- connect(): Promise<void>;
42
- close(code: number, reason?: string): Promise<void>;
43
- sendMessage(data: import("../Types").IWSMessage): Promise<void>;
44
- private _write;
45
- private _onError;
46
- private _onClose;
47
- private _onReadable;
48
- private _processFrame;
49
- }
50
- export = BetterWs;