@discordeno/gateway 19.0.0-next.fc13bdf → 19.0.0-next.fdf0d53

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/dist/Shard.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { AtLeastOne, BigString, Camelize, DiscordGatewayPayload, DiscordMember, RequestGuildMembers } from '@discordeno/types';
2
- import { Collection } from '@discordeno/utils';
2
+ import { Collection, LeakyBucket } from '@discordeno/utils';
3
3
  import WebSocket from 'ws';
4
4
  import type { RequestMemberRequest } from './manager.js';
5
5
  import type { BotStatusUpdate, ShardEvents, ShardGatewayConfig, ShardHeart, ShardSocketRequest, StatusUpdate, UpdateVoiceState } from './types.js';
@@ -32,7 +32,7 @@ export declare class DiscordenoShard {
32
32
  /** Resolve internal waiting states. Mapped by SelectedEvents => ResolveFunction */
33
33
  resolves: Map<"READY" | "RESUMED" | "INVALID_SESSION", (payload: DiscordGatewayPayload) => void>;
34
34
  /** Shard bucket. Only access this if you know what you are doing. Bucket for handling shard request rate limits. */
35
- bucket: import("@discordeno/utils").LeakyBucket;
35
+ bucket: LeakyBucket;
36
36
  /** This managers cache related settings. */
37
37
  cache: {
38
38
  requestMembers: {
@@ -48,6 +48,8 @@ export declare class DiscordenoShard {
48
48
  constructor(options: ShardCreateOptions);
49
49
  /** The gateway configuration which is used to connect to Discord. */
50
50
  get gatewayConfig(): ShardGatewayConfig;
51
+ /** The url to connect to. Intially this is the discord gateway url, and then is switched to resume gateway url once a READY is received. */
52
+ get connectionUrl(): string;
51
53
  /** Calculate the amount of requests which can safely be made per rate limit interval, before the gateway gets disconnected due to an exceeded rate limit. */
52
54
  calculateSafeRequests(): number;
53
55
  checkOffline(highPriority: boolean): Promise<void>;
@@ -71,6 +73,7 @@ export declare class DiscordenoShard {
71
73
  handleClose(close: WebSocket.CloseEvent): Promise<void>;
72
74
  /** Handles a incoming gateway packet. */
73
75
  handleDiscordPacket(packet: DiscordGatewayPayload): Promise<void>;
76
+ forwardToBot(packet: DiscordGatewayPayload): void;
74
77
  /** Handle an incoming gateway message. */
75
78
  handleMessage(message: WebSocket.MessageEvent): Promise<void>;
76
79
  /**
@@ -81,6 +84,8 @@ export declare class DiscordenoShard {
81
84
  makePresence(): Promise<BotStatusUpdate | undefined>;
82
85
  /** This function communicates with the management process, in order to know whether its free to identify. When this function resolves, this means that the shard is allowed to send an identify payload to discord. */
83
86
  requestIdentify(): Promise<void>;
87
+ /** This function communicates with the management process, in order to tell it can identify the next shard. */
88
+ shardIsReady(): Promise<void>;
84
89
  /** Start sending heartbeat payloads to Discord in the provided interval. */
85
90
  startHeartbeating(interval: number): void;
86
91
  /** Stop the heartbeating process with discord. */
@@ -161,6 +166,10 @@ export interface ShardCreateOptions {
161
166
  connection: ShardGatewayConfig;
162
167
  /** The event handlers for events on the shard. */
163
168
  events: ShardEvents;
169
+ /** The handler to request a space to make an identify request. */
170
+ requestIdentify?: () => Promise<void>;
171
+ /** The handler to alert the gateway manager that this shard has received a READY event. */
172
+ shardIsReady?: () => Promise<void>;
164
173
  }
165
174
  export default DiscordenoShard;
166
175
  //# sourceMappingURL=Shard.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Shard.d.ts","sourceRoot":"","sources":["../src/Shard.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,UAAU,EACV,SAAS,EACT,QAAQ,EACR,qBAAqB,EAErB,aAAa,EAEb,mBAAmB,EACpB,MAAM,mBAAmB,CAAA;AAE1B,OAAO,EAAY,UAAU,EAAoC,MAAM,mBAAmB,CAAA;AAE1F,OAAO,SAAS,MAAM,IAAI,CAAA;AAC1B,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAA;AACxD,OAAO,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,kBAAkB,EAAE,UAAU,EAAE,kBAAkB,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAClJ,OAAO,EAAyB,U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;;;OAWG;IACG,iBAAiB,CAAC,OAAO,EAAE,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC;CAY3D;AAED,MAAM,WAAW,kBAAkB;IACjC,mBAAmB;IACnB,EAAE,EAAE,MAAM,CAAA;IACV,6BAA6B;IAC7B,UAAU,EAAE,kBAAkB,CAAA;IAC9B,kDAAkD;IAClD,MAAM,EAAE,WAAW,CAAA;IACnB,kEAAkE;IAClE,eAAe,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;IACrC,2FAA2F;IAC3F,YAAY,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;CACnC;AAED,eAAe,eAAe,CAAA"}
package/dist/Shard.js CHANGED
@@ -1,32 +1,27 @@
1
- import { GatewayCloseEventCodes, GatewayIntents, GatewayOpcodes } from '@discordeno/types';
2
- import { camelize, Collection, createLeakyBucket, delay, logger } from '@discordeno/utils';
1
+ /* eslint-disable @typescript-eslint/no-confusing-void-expression */ import { GatewayCloseEventCodes, GatewayIntents, GatewayOpcodes } from '@discordeno/types';
2
+ import { Collection, LeakyBucket, camelize, delay, logger } from '@discordeno/utils';
3
3
  import { inflateSync } from 'node:zlib';
4
4
  import WebSocket from 'ws';
5
5
  import { ShardSocketCloseCodes, ShardState } from './types.js';
6
6
  export class DiscordenoShard {
7
- /** The maximum of requests which can be send to discord per rate limit tick. Typically this value should not be changed. */ maxRequestsPerRateLimitTick = 120;
8
- /** The previous payload sequence number. */ previousSequenceNumber = null;
9
- /** In which interval (in milliseconds) the gateway resets it's rate limit. */ rateLimitResetInterval = 60000;
10
- /** Current internal state of the this. */ state = ShardState.Offline;
11
- /** The url provided by discord to use when resuming a connection for this this. */ resumeGatewayUrl = '';
12
- /** The shard related event handlers. */ events = {};
13
- /** Cache for pending gateway requests which should have been send while the gateway went offline. */ offlineSendQueue = [];
14
- /** Resolve internal waiting states. Mapped by SelectedEvents => ResolveFunction */ resolves = new Map();
15
- /** Shard bucket. Only access this if you know what you are doing. Bucket for handling shard request rate limits. */ bucket = createLeakyBucket({
16
- max: 120,
17
- refillInterval: 60000,
18
- refillAmount: 120
19
- });
20
- /** This managers cache related settings. */ cache = {
21
- requestMembers: {
22
- /**
7
+ constructor(options){
8
+ /** The maximum of requests which can be send to discord per rate limit tick. Typically this value should not be changed. */ this.maxRequestsPerRateLimitTick = 120;
9
+ /** The previous payload sequence number. */ this.previousSequenceNumber = null;
10
+ /** In which interval (in milliseconds) the gateway resets it's rate limit. */ this.rateLimitResetInterval = 60000;
11
+ /** Current internal state of the this. */ this.state = ShardState.Offline;
12
+ /** The url provided by discord to use when resuming a connection for this this. */ this.resumeGatewayUrl = '';
13
+ /** The shard related event handlers. */ this.events = {};
14
+ /** Cache for pending gateway requests which should have been send while the gateway went offline. */ this.offlineSendQueue = [];
15
+ /** Resolve internal waiting states. Mapped by SelectedEvents => ResolveFunction */ this.resolves = new Map();
16
+ /** This managers cache related settings. */ this.cache = {
17
+ requestMembers: {
18
+ /**
23
19
  * Whether or not request member requests should be cached.
24
20
  * @default false
25
21
  */ enabled: false,
26
- /** The pending requests. */ pending: new Collection()
27
- }
28
- };
29
- constructor(options){
22
+ /** The pending requests. */ pending: new Collection()
23
+ }
24
+ };
30
25
  this.id = options.id;
31
26
  this.connection = options.connection;
32
27
  this.events = options.events;
@@ -34,10 +29,21 @@ export class DiscordenoShard {
34
29
  acknowledged: false,
35
30
  interval: 45000
36
31
  };
32
+ if (options.requestIdentify) this.requestIdentify = options.requestIdentify;
33
+ if (options.shardIsReady) this.shardIsReady = options.shardIsReady;
34
+ this.bucket = new LeakyBucket({
35
+ max: this.calculateSafeRequests(),
36
+ refillAmount: this.calculateSafeRequests(),
37
+ refillInterval: 60000
38
+ });
37
39
  }
38
40
  /** The gateway configuration which is used to connect to Discord. */ get gatewayConfig() {
39
41
  return this.connection;
40
42
  }
43
+ /** The url to connect to. Intially this is the discord gateway url, and then is switched to resume gateway url once a READY is received. */ get connectionUrl() {
44
+ // Use || and not ?? here. ?? will cause a bug.
45
+ return this.resumeGatewayUrl || this.gatewayConfig.url;
46
+ }
41
47
  /** Calculate the amount of requests which can safely be made per rate limit interval, before the gateway gets disconnected due to an exceeded rate limit. */ calculateSafeRequests() {
42
48
  // * 2 adds extra safety layer for discords OP 1 requests that we need to respond to
43
49
  const safeRequests = this.maxRequestsPerRateLimitTick - Math.ceil(this.rateLimitResetInterval / this.heart.interval) * 2;
@@ -54,7 +60,7 @@ export class DiscordenoShard {
54
60
  }
55
61
  /** Close the socket connection to discord if present. */ close(code, reason) {
56
62
  if (this.socket?.readyState !== WebSocket.OPEN) return;
57
- return this.socket?.close(code, reason);
63
+ this.socket?.close(code, reason);
58
64
  }
59
65
  /** Connect the shard with the gateway and start heartbeating. This will not identify the shard to the gateway. */ async connect() {
60
66
  // Only set the shard to `Connecting` state,
@@ -66,20 +72,15 @@ export class DiscordenoShard {
66
72
  this.state = ShardState.Connecting;
67
73
  }
68
74
  this.events.connecting?.(this);
69
- let url = new URL(this.gatewayConfig.url);
70
- // If not connecting to a proxy but directly to discord need to handle resuming
71
- if (url.origin === 'wss://gateway.discord.gg') {
72
- if (this.state === ShardState.Resuming) {
73
- url = new URL(this.resumeGatewayUrl);
74
- }
75
- url.searchParams.set('v', this.gatewayConfig.version.toString());
76
- url.searchParams.set('encoding', 'json');
77
- }
75
+ const url = new URL(this.connectionUrl);
76
+ url.searchParams.set('v', this.gatewayConfig.version.toString());
77
+ url.searchParams.set('encoding', 'json');
78
78
  const socket = new WebSocket(url.toString());
79
79
  this.socket = socket;
80
80
  // TODO: proper event handling
81
81
  socket.onerror = (event)=>console.log({
82
- error: event
82
+ error: event,
83
+ shardId: this.id
83
84
  });
84
85
  socket.onclose = async (event)=>await this.handleClose(event);
85
86
  socket.onmessage = async (message)=>await this.handleMessage(message);
@@ -102,7 +103,7 @@ export class DiscordenoShard {
102
103
  // A new identify has been requested even though there is already a connection open.
103
104
  // Therefore we need to close the old connection and heartbeating before creating a new one.
104
105
  if (this.isOpen()) {
105
- console.log(`CLOSING EXISTING SHARD: #${this.id}`);
106
+ logger.debug(`CLOSING EXISTING SHARD: #${this.id}`);
106
107
  this.close(ShardSocketCloseCodes.ReIdentifying, 'Re-identifying closure of old connection.');
107
108
  }
108
109
  this.state = ShardState.Identifying;
@@ -113,8 +114,6 @@ export class DiscordenoShard {
113
114
  if (!this.isOpen()) {
114
115
  await this.connect();
115
116
  }
116
- // Wait until an identify is free for this this.
117
- await this.requestIdentify();
118
117
  this.send({
119
118
  op: GatewayOpcodes.Identify,
120
119
  d: {
@@ -132,6 +131,8 @@ export class DiscordenoShard {
132
131
  return await new Promise((resolve)=>{
133
132
  this.resolves.set('READY', ()=>{
134
133
  this.events.identified?.(this);
134
+ // Tells the manager that this shard is ready
135
+ this.shardIsReady();
135
136
  resolve();
136
137
  });
137
138
  // When identifying too fast,
@@ -147,7 +148,7 @@ export class DiscordenoShard {
147
148
  return this.socket?.readyState === WebSocket.OPEN;
148
149
  }
149
150
  /** Attempt to resume the previous shards session with the gateway. */ async resume() {
150
- // gateway.debug("GW RESUMING", { shardId });
151
+ logger.debug(`[Gateway] Resuming Shard #${this.id}`);
151
152
  // It has been requested to resume the Shards session.
152
153
  // It's possible that the shard is still connected with Discord's gateway therefore we need to forcefully close it.
153
154
  if (this.isOpen()) {
@@ -155,12 +156,8 @@ export class DiscordenoShard {
155
156
  }
156
157
  // Shard has never identified, so we cannot resume.
157
158
  if (!this.sessionId) {
158
- // gateway.debug(
159
- // "GW DEBUG",
160
- // `[Error] Trying to resume a shard (id: ${shardId}) that was not first identified.`,
161
- // );
159
+ logger.debug(`[Shard] Trying to resume a shard #${this.id} that was NOT first identified. (No session id found)`);
162
160
  return await this.identify();
163
- // throw new Error(`[SHARD] Trying to resume a shard (id: ${this.id}) which was never identified`);
164
161
  }
165
162
  this.state = ShardState.Resuming;
166
163
  // Before we can resume, we need to create a new connection with Discord's gateway.
@@ -190,7 +187,7 @@ export class DiscordenoShard {
190
187
  // Before acquiring a token from the bucket, check whether the shard is currently offline or not.
191
188
  // Else bucket and token wait time just get wasted.
192
189
  await this.checkOffline(highPriority);
193
- await this.bucket.acquire(1, highPriority);
190
+ await this.bucket.acquire(highPriority);
194
191
  // It's possible, that the shard went offline after a token has been acquired from the bucket.
195
192
  await this.checkOffline(highPriority);
196
193
  this.socket?.send(JSON.stringify(message));
@@ -228,6 +225,7 @@ export class DiscordenoShard {
228
225
  case GatewayCloseEventCodes.RateLimited:
229
226
  case GatewayCloseEventCodes.SessionTimedOut:
230
227
  {
228
+ logger.debug(`[Shard] Gateway connection closing requiring re-identify. Code: ${close.code}`);
231
229
  this.state = ShardState.Identifying;
232
230
  this.events.disconnected?.(this);
233
231
  return await this.identify();
@@ -286,16 +284,19 @@ export class DiscordenoShard {
286
284
  const interval = packet.d.heartbeat_interval;
287
285
  this.startHeartbeating(interval);
288
286
  if (this.state !== ShardState.Resuming) {
287
+ const currentQueue = [
288
+ ...this.bucket.queue
289
+ ];
289
290
  // HELLO has been send on a non resume action.
290
291
  // This means that the shard starts a new session,
291
292
  // therefore the rate limit interval has been reset too.
292
- this.bucket = createLeakyBucket({
293
+ this.bucket = new LeakyBucket({
293
294
  max: this.calculateSafeRequests(),
294
295
  refillInterval: 60000,
295
- refillAmount: this.calculateSafeRequests(),
296
- // Waiting acquires should not be lost on a re-identify.
297
- waiting: this.bucket.waiting
296
+ refillAmount: this.calculateSafeRequests()
298
297
  });
298
+ // Queue should not be lost on a re-identify.
299
+ this.bucket.queue.unshift(...currentQueue);
299
300
  }
300
301
  this.events.hello?.(this);
301
302
  break;
@@ -314,8 +315,8 @@ export class DiscordenoShard {
314
315
  }
315
316
  case GatewayOpcodes.InvalidSession:
316
317
  {
317
- // gateway.debug("GW INVALID_SESSION", { shardId, payload: packet });
318
318
  const resumable = packet.d;
319
+ logger.debug(`[Shard] Received Invalid Session for Shard #${this.id} with resumeable as ${resumable.toString()}`);
319
320
  this.events.invalidSession?.(this, resumable);
320
321
  // We need to wait for a random amount of time between 1 and 5
321
322
  // Reference: https://discord.com/developers/docs/topics/gateway#resuming
@@ -324,7 +325,7 @@ export class DiscordenoShard {
324
325
  this.resolves.delete('INVALID_SESSION');
325
326
  // When resumable is false we need to re-identify
326
327
  if (!resumable) {
327
- await this.identify();
328
+ await this.requestIdentify();
328
329
  break;
329
330
  }
330
331
  // The session is invalid but apparently it is resumable
@@ -358,6 +359,9 @@ export class DiscordenoShard {
358
359
  if (packet.s !== null) {
359
360
  this.previousSequenceNumber = packet.s;
360
361
  }
362
+ this.forwardToBot(packet);
363
+ }
364
+ forwardToBot(packet) {
361
365
  // The necessary handling required for the Shards connection has been finished.
362
366
  // Now the event can be safely forwarded.
363
367
  this.events.message?.(this, camelize(packet));
@@ -381,12 +385,12 @@ export class DiscordenoShard {
381
385
  // eslint-disable-next-line no-useless-return
382
386
  return;
383
387
  }
384
- /** This function communicates with the management process, in order to know whether its free to identify. When this function resolves, this means that the shard is allowed to send an identify payload to discord. */ async requestIdentify() {
385
- // TODO: how to handle this
386
- // return await options.requestIdentify(this.id)
387
- }
388
+ /** This function communicates with the management process, in order to know whether its free to identify. When this function resolves, this means that the shard is allowed to send an identify payload to discord. */ async requestIdentify() {}
389
+ /** This function communicates with the management process, in order to tell it can identify the next shard. */ async shardIsReady() {}
388
390
  /** Start sending heartbeat payloads to Discord in the provided interval. */ startHeartbeating(interval) {
389
- // gateway.debug("GW HEARTBEATING_STARTED", { shardId, interval });
391
+ // If old heartbeast exist like after resume, clear the old ones.
392
+ if (this.heart.intervalId) clearInterval(this.heart.intervalId);
393
+ if (this.heart.timeoutId) clearTimeout(this.heart.timeoutId);
390
394
  this.heart.interval = interval;
391
395
  // Only set the shard's state to `Unidentified`
392
396
  // if heartbeating has not been started due to an identify or resume action.
@@ -420,6 +424,7 @@ export class DiscordenoShard {
420
424
  // The Shard needs to start a re-identify action accordingly.
421
425
  // Reference: https://discord.com/developers/docs/topics/gateway#heartbeating-example-gateway-heartbeat-ack
422
426
  if (!this.heart.acknowledged) {
427
+ logger.debug(`[Shard] Heartbeat not acknowledged for shard #${this.id}.`);
423
428
  this.close(ShardSocketCloseCodes.ZombiedConnection, 'Zombied connection, did not receive an heartbeat ACK in time.');
424
429
  return await this.identify();
425
430
  }
@@ -457,7 +462,7 @@ export class DiscordenoShard {
457
462
  * @see {@link https://discord.com/developers/docs/topics/gateway#update-voice-state}
458
463
  */ async joinVoiceChannel(guildId, channelId, options) {
459
464
  logger.debug(`[Shard] joinVoiceChannel guildId: ${guildId} channelId: ${channelId}`);
460
- return await this.send({
465
+ await this.send({
461
466
  op: GatewayOpcodes.VoiceStateUpdate,
462
467
  d: {
463
468
  guild_id: guildId.toString(),
@@ -474,7 +479,7 @@ export class DiscordenoShard {
474
479
  * @returns Promise<void>
475
480
  */ async editBotStatus(data) {
476
481
  logger.debug(`[Shard] editBotStatus data: ${JSON.stringify(data)}`);
477
- return await this.editShardStatus(data);
482
+ await this.editShardStatus(data);
478
483
  }
479
484
  /**
480
485
  * Edits the bot's status on one shard.
@@ -484,7 +489,7 @@ export class DiscordenoShard {
484
489
  * @returns Promise<void>
485
490
  */ async editShardStatus(data) {
486
491
  logger.debug(`[Shard] editShardStatus shardId: ${this.id} -> data: ${JSON.stringify(data)}`);
487
- return await this.send({
492
+ await this.send({
488
493
  op: GatewayOpcodes.PresenceUpdate,
489
494
  d: {
490
495
  since: null,
@@ -578,7 +583,7 @@ export class DiscordenoShard {
578
583
  * @see {@link https://discord.com/developers/docs/topics/gateway#update-voice-state}
579
584
  */ async leaveVoiceChannel(guildId) {
580
585
  logger.debug(`[Shard] leaveVoiceChannel guildId: ${guildId} Shard ${this.id}`);
581
- return await this.send({
586
+ await this.send({
582
587
  op: GatewayOpcodes.VoiceStateUpdate,
583
588
  d: {
584
589
  guild_id: guildId.toString(),
package/dist/Shard.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/Shard.ts"],"sourcesContent":["import type {\n AtLeastOne,\n BigString,\n Camelize,\n DiscordGatewayPayload,\n DiscordHello,\n DiscordMember,\n DiscordReady,\n RequestGuildMembers,\n} from '@discordeno/types'\nimport { GatewayCloseEventCodes, GatewayIntents, GatewayOpcodes } from '@discordeno/types'\nimport { camelize, Collection, createLeakyBucket, delay, logger } from '@discordeno/utils'\nimport { inflateSync } from 'node:zlib'\nimport WebSocket from 'ws'\nimport type { RequestMemberRequest } from './manager.js'\nimport type { BotStatusUpdate, ShardEvents, ShardGatewayConfig, ShardHeart, ShardSocketRequest, StatusUpdate, UpdateVoiceState } from './types.js'\nimport { ShardSocketCloseCodes, ShardState } from './types.js'\n\nexport class DiscordenoShard {\n /** The id of the shard */\n id: number\n /** The connection config details that this shard will used to connect to discord. */\n connection: ShardGatewayConfig\n /** This contains all the heartbeat information */\n heart: ShardHeart\n /** The maximum of requests which can be send to discord per rate limit tick. Typically this value should not be changed. */\n maxRequestsPerRateLimitTick: number = 120\n /** The previous payload sequence number. */\n previousSequenceNumber: number | null = null\n /** In which interval (in milliseconds) the gateway resets it's rate limit. */\n rateLimitResetInterval: number = 60000\n /** Current session id of the shard if present. */\n sessionId?: string\n /** This contains the WebSocket connection to Discord, if currently connected. */\n socket?: WebSocket\n /** Current internal state of the this. */\n state = ShardState.Offline\n /** The url provided by discord to use when resuming a connection for this this. */\n resumeGatewayUrl: string = ''\n /** The shard related event handlers. */\n events: ShardEvents = {}\n /** Cache for pending gateway requests which should have been send while the gateway went offline. */\n offlineSendQueue: Array<(_?: unknown) => void> = []\n /** Resolve internal waiting states. Mapped by SelectedEvents => ResolveFunction */\n resolves = new Map<'READY' | 'RESUMED' | 'INVALID_SESSION', (payload: DiscordGatewayPayload) => void>()\n /** Shard bucket. Only access this if you know what you are doing. Bucket for handling shard request rate limits. */\n bucket = createLeakyBucket({\n max: 120,\n refillInterval: 60000,\n refillAmount: 120,\n })\n\n /** This managers cache related settings. */\n cache = {\n requestMembers: {\n /**\n * Whether or not request member requests should be cached.\n * @default false\n */\n enabled: false,\n /** The pending requests. */\n pending: new Collection<string, RequestMemberRequest>(),\n },\n }\n\n constructor(options: ShardCreateOptions) {\n this.id = options.id\n this.connection = options.connection\n this.events = options.events\n\n this.heart = {\n acknowledged: false,\n interval: 45000,\n }\n }\n\n /** The gateway configuration which is used to connect to Discord. */\n get gatewayConfig(): ShardGatewayConfig {\n return this.connection\n }\n\n /** Calculate the amount of requests which can safely be made per rate limit interval, before the gateway gets disconnected due to an exceeded rate limit. */\n calculateSafeRequests(): number {\n // * 2 adds extra safety layer for discords OP 1 requests that we need to respond to\n const safeRequests = this.maxRequestsPerRateLimitTick - Math.ceil(this.rateLimitResetInterval / this.heart.interval) * 2\n\n return safeRequests < 0 ? 0 : safeRequests\n }\n\n async checkOffline(highPriority: boolean): Promise<void> {\n if (!this.isOpen()) {\n await new Promise((resolve) => {\n // Higher priority requests get added at the beginning of the array.\n if (highPriority) this.offlineSendQueue.unshift(resolve)\n else this.offlineSendQueue.push(resolve)\n })\n }\n }\n\n /** Close the socket connection to discord if present. */\n close(code: number, reason: string): void {\n if (this.socket?.readyState !== WebSocket.OPEN) return\n\n return this.socket?.close(code, reason)\n }\n\n /** Connect the shard with the gateway and start heartbeating. This will not identify the shard to the gateway. */\n async connect(): Promise<DiscordenoShard> {\n // Only set the shard to `Connecting` state,\n // if the connection request does not come from an identify or resume action.\n if (![ShardState.Identifying, ShardState.Resuming].includes(this.state)) {\n this.state = ShardState.Connecting\n }\n this.events.connecting?.(this)\n\n let url = new URL(this.gatewayConfig.url)\n // If not connecting to a proxy but directly to discord need to handle resuming\n if (url.origin === 'wss://gateway.discord.gg') {\n if (this.state === ShardState.Resuming) {\n url = new URL(this.resumeGatewayUrl)\n }\n url.searchParams.set('v', this.gatewayConfig.version.toString())\n url.searchParams.set('encoding', 'json')\n }\n\n const socket = new WebSocket(url.toString())\n\n this.socket = socket\n\n // TODO: proper event handling\n socket.onerror = (event) => console.log({ error: event })\n\n socket.onclose = async (event) => await this.handleClose(event)\n\n socket.onmessage = async (message) => await this.handleMessage(message)\n\n return await new Promise((resolve) => {\n socket.onopen = () => {\n // Only set the shard to `Unidentified` state,\n // if the connection request does not come from an identify or resume action.\n if (![ShardState.Identifying, ShardState.Resuming].includes(this.state)) {\n this.state = ShardState.Unidentified\n }\n this.events.connected?.(this)\n\n resolve(this)\n }\n })\n }\n\n /** Identify the shard to the gateway. If not connected, this will also connect the shard to the gateway. */\n async identify(): Promise<void> {\n // A new identify has been requested even though there is already a connection open.\n // Therefore we need to close the old connection and heartbeating before creating a new one.\n if (this.isOpen()) {\n console.log(`CLOSING EXISTING SHARD: #${this.id}`)\n this.close(ShardSocketCloseCodes.ReIdentifying, 'Re-identifying closure of old connection.')\n }\n\n this.state = ShardState.Identifying\n this.events.identifying?.(this)\n\n // It is possible that the shard is in Heartbeating state but not identified,\n // so check whether there is already a gateway connection existing.\n // If not we need to create one before we identify.\n if (!this.isOpen()) {\n await this.connect()\n }\n\n // Wait until an identify is free for this this.\n await this.requestIdentify()\n\n this.send(\n {\n op: GatewayOpcodes.Identify,\n d: {\n token: `Bot ${this.gatewayConfig.token}`,\n compress: this.gatewayConfig.compress,\n properties: this.gatewayConfig.properties,\n intents: this.gatewayConfig.intents,\n shard: [this.id, this.gatewayConfig.totalShards],\n presence: await this.makePresence?.(),\n },\n },\n true,\n )\n\n return await new Promise((resolve) => {\n this.resolves.set('READY', () => {\n this.events.identified?.(this)\n resolve()\n })\n // When identifying too fast,\n // Discord sends an invalid session payload.\n // This can safely be ignored though and the shard starts a new identify action.\n this.resolves.set('INVALID_SESSION', () => {\n this.resolves.delete('READY')\n resolve()\n })\n })\n }\n\n /** Check whether the connection to Discord is currently open. */\n isOpen(): boolean {\n return this.socket?.readyState === WebSocket.OPEN\n }\n\n /** Attempt to resume the previous shards session with the gateway. */\n async resume(): Promise<void> {\n // gateway.debug(\"GW RESUMING\", { shardId });\n // It has been requested to resume the Shards session.\n // It's possible that the shard is still connected with Discord's gateway therefore we need to forcefully close it.\n if (this.isOpen()) {\n this.close(ShardSocketCloseCodes.ResumeClosingOldConnection, 'Reconnecting the shard, closing old connection.')\n }\n\n // Shard has never identified, so we cannot resume.\n if (!this.sessionId) {\n // gateway.debug(\n // \"GW DEBUG\",\n // `[Error] Trying to resume a shard (id: ${shardId}) that was not first identified.`,\n // );\n\n return await this.identify()\n\n // throw new Error(`[SHARD] Trying to resume a shard (id: ${this.id}) which was never identified`);\n }\n\n this.state = ShardState.Resuming\n\n // Before we can resume, we need to create a new connection with Discord's gateway.\n await this.connect()\n\n this.send(\n {\n op: GatewayOpcodes.Resume,\n d: {\n token: `Bot ${this.gatewayConfig.token}`,\n session_id: this.sessionId,\n seq: this.previousSequenceNumber ?? 0,\n },\n },\n true,\n )\n\n return await new Promise((resolve) => {\n this.resolves.set('RESUMED', () => resolve())\n // If it is attempted to resume with an invalid session id,\n // Discord sends an invalid session payload\n // Not erroring here since it is easy that this happens, also it would be not catchable\n this.resolves.set('INVALID_SESSION', () => {\n this.resolves.delete('RESUMED')\n resolve()\n })\n })\n }\n\n /** Send a message to Discord.\n * @param {boolean} [highPriority=false] - Whether this message should be send asap.\n */\n async send(message: ShardSocketRequest, highPriority = false): Promise<void> {\n // Before acquiring a token from the bucket, check whether the shard is currently offline or not.\n // Else bucket and token wait time just get wasted.\n await this.checkOffline(highPriority)\n\n await this.bucket.acquire(1, highPriority)\n\n // It's possible, that the shard went offline after a token has been acquired from the bucket.\n await this.checkOffline(highPriority)\n\n this.socket?.send(JSON.stringify(message))\n }\n\n /** Shutdown the this. Forcefully disconnect the shard from Discord. The shard may not attempt to reconnect with Discord. */\n async shutdown(): Promise<void> {\n this.close(ShardSocketCloseCodes.Shutdown, 'Shard shutting down.')\n this.state = ShardState.Offline\n }\n\n /** Handle a gateway connection close. */\n async handleClose(close: WebSocket.CloseEvent): Promise<void> {\n // gateway.debug(\"GW CLOSED\", { shardId, payload: event });\n\n this.stopHeartbeating()\n\n switch (close.code) {\n case ShardSocketCloseCodes.TestingFinished: {\n this.state = ShardState.Offline\n this.events.disconnected?.(this)\n\n return\n }\n // On these codes a manual start will be done.\n case ShardSocketCloseCodes.Shutdown:\n case ShardSocketCloseCodes.ReIdentifying:\n case ShardSocketCloseCodes.Resharded:\n case ShardSocketCloseCodes.ResumeClosingOldConnection:\n case ShardSocketCloseCodes.ZombiedConnection: {\n this.state = ShardState.Disconnected\n this.events.disconnected?.(this)\n\n // gateway.debug(\"GW CLOSED_RECONNECT\", { shardId, payload: event });\n return\n }\n // Gateway connection closes which require a new identify.\n case GatewayCloseEventCodes.UnknownOpcode:\n case GatewayCloseEventCodes.NotAuthenticated:\n case GatewayCloseEventCodes.InvalidSeq:\n case GatewayCloseEventCodes.RateLimited:\n case GatewayCloseEventCodes.SessionTimedOut: {\n this.state = ShardState.Identifying\n this.events.disconnected?.(this)\n\n return await this.identify()\n }\n // When these codes are received something went really wrong.\n // On those we cannot start a reconnect attempt.\n case GatewayCloseEventCodes.AuthenticationFailed:\n case GatewayCloseEventCodes.InvalidShard:\n case GatewayCloseEventCodes.ShardingRequired:\n case GatewayCloseEventCodes.InvalidApiVersion:\n case GatewayCloseEventCodes.InvalidIntents:\n case GatewayCloseEventCodes.DisallowedIntents: {\n this.state = ShardState.Offline\n this.events.disconnected?.(this)\n\n throw new Error(close.reason || 'Discord gave no reason! GG! You broke Discord!')\n }\n // Gateway connection closes on which a resume is allowed.\n case GatewayCloseEventCodes.UnknownError:\n case GatewayCloseEventCodes.DecodeError:\n case GatewayCloseEventCodes.AlreadyAuthenticated:\n default: {\n this.state = ShardState.Resuming\n this.events.disconnected?.(this)\n\n return await this.resume()\n }\n }\n }\n\n /** Handles a incoming gateway packet. */\n async handleDiscordPacket(packet: DiscordGatewayPayload): Promise<void> {\n // Edge case start: https://github.com/discordeno/discordeno/issues/2311\n this.heart.lastAck = Date.now()\n // Manually calculating the round trip time for users who need it.\n if (this.heart.lastBeat && !this.heart.acknowledged) {\n this.heart.rtt = this.heart.lastAck - this.heart.lastBeat\n }\n this.heart.acknowledged = true\n // Edge case end!\n\n switch (packet.op) {\n case GatewayOpcodes.Heartbeat: {\n // TODO: can this actually happen\n if (!this.isOpen()) return\n\n this.heart.lastBeat = Date.now()\n // Discord randomly sends this requiring an immediate heartbeat back.\n // Using a direct socket.send call here because heartbeat requests are reserved by us.\n this.socket?.send(\n JSON.stringify({\n op: GatewayOpcodes.Heartbeat,\n d: this.previousSequenceNumber,\n }),\n )\n this.events.heartbeat?.(this)\n\n break\n }\n case GatewayOpcodes.Hello: {\n const interval = (packet.d as DiscordHello).heartbeat_interval\n\n this.startHeartbeating(interval)\n\n if (this.state !== ShardState.Resuming) {\n // HELLO has been send on a non resume action.\n // This means that the shard starts a new session,\n // therefore the rate limit interval has been reset too.\n this.bucket = createLeakyBucket({\n max: this.calculateSafeRequests(),\n refillInterval: 60000,\n refillAmount: this.calculateSafeRequests(),\n // Waiting acquires should not be lost on a re-identify.\n waiting: this.bucket.waiting,\n })\n }\n\n this.events.hello?.(this)\n\n break\n }\n case GatewayOpcodes.HeartbeatACK: {\n this.events.heartbeatAck?.(this)\n\n break\n }\n case GatewayOpcodes.Reconnect: {\n // gateway.debug(\"GW RECONNECT\", { shardId });\n\n this.events.requestedReconnect?.(this)\n\n await this.resume()\n\n break\n }\n case GatewayOpcodes.InvalidSession: {\n // gateway.debug(\"GW INVALID_SESSION\", { shardId, payload: packet });\n const resumable = packet.d as boolean\n\n this.events.invalidSession?.(this, resumable)\n\n // We need to wait for a random amount of time between 1 and 5\n // Reference: https://discord.com/developers/docs/topics/gateway#resuming\n await delay(Math.floor((Math.random() * 4 + 1) * 1000))\n\n this.resolves.get('INVALID_SESSION')?.(packet)\n this.resolves.delete('INVALID_SESSION')\n\n // When resumable is false we need to re-identify\n if (!resumable) {\n await this.identify()\n\n break\n }\n\n // The session is invalid but apparently it is resumable\n await this.resume()\n\n break\n }\n }\n\n if (packet.t === 'RESUMED') {\n // gateway.debug(\"GW RESUMED\", { shardId });\n\n this.state = ShardState.Connected\n this.events.resumed?.(this)\n\n // Continue the requests which have been queued since the shard went offline.\n this.offlineSendQueue.map((resolve) => resolve())\n\n this.resolves.get('RESUMED')?.(packet)\n this.resolves.delete('RESUMED')\n } else if (packet.t === 'READY') {\n // Important for future resumes.\n\n const payload = packet.d as DiscordReady\n\n this.resumeGatewayUrl = payload.resume_gateway_url\n\n this.sessionId = payload.session_id\n this.state = ShardState.Connected\n\n // Continue the requests which have been queued since the shard went offline.\n // Important when this is a re-identify\n this.offlineSendQueue.map((resolve) => resolve())\n\n this.resolves.get('READY')?.(packet)\n this.resolves.delete('READY')\n }\n\n // Update the sequence number if it is present\n // `s` can be either `null` or a `number`.\n // In order to prevent update misses when `s` is `0` we check against null.\n if (packet.s !== null) {\n this.previousSequenceNumber = packet.s\n }\n\n // The necessary handling required for the Shards connection has been finished.\n // Now the event can be safely forwarded.\n this.events.message?.(this, camelize(packet))\n }\n\n /** Handle an incoming gateway message. */\n async handleMessage(message: WebSocket.MessageEvent): Promise<void> {\n let preProcessMessage = message.data\n\n // If message compression is enabled,\n // Discord might send zlib compressed payloads.\n if (this.gatewayConfig.compress && preProcessMessage instanceof Blob) {\n preProcessMessage = inflateSync(await preProcessMessage.arrayBuffer()).toString()\n }\n\n // Safeguard incase decompression failed to make a string.\n if (typeof preProcessMessage !== 'string') return\n\n return await this.handleDiscordPacket(JSON.parse(preProcessMessage) as DiscordGatewayPayload)\n }\n\n /**\n * Override in order to make the shards presence.\n * async in case devs create the presence based on eg. database values.\n * Passing the shard's id there to make it easier for the dev to use this function.\n */\n async makePresence(): Promise<BotStatusUpdate | undefined> {\n // eslint-disable-next-line no-useless-return\n return\n }\n\n /** This function communicates with the management process, in order to know whether its free to identify. When this function resolves, this means that the shard is allowed to send an identify payload to discord. */\n async requestIdentify(): Promise<void> {\n // TODO: how to handle this\n // return await options.requestIdentify(this.id)\n }\n\n /** Start sending heartbeat payloads to Discord in the provided interval. */\n startHeartbeating(interval: number): void {\n // gateway.debug(\"GW HEARTBEATING_STARTED\", { shardId, interval });\n\n this.heart.interval = interval\n\n // Only set the shard's state to `Unidentified`\n // if heartbeating has not been started due to an identify or resume action.\n if ([ShardState.Disconnected, ShardState.Offline].includes(this.state)) {\n this.state = ShardState.Unidentified\n }\n\n // The first heartbeat needs to be send with a random delay between `0` and `interval`\n // Using a `setTimeout(_, jitter)` here to accomplish that.\n // `Math.random()` can be `0` so we use `0.5` if this happens\n // Reference: https://discord.com/developers/docs/topics/gateway#heartbeating\n const jitter = Math.ceil(this.heart.interval * (Math.random() || 0.5))\n this.heart.timeoutId = setTimeout(() => {\n if (!this.isOpen()) return\n\n // Using a direct socket.send call here because heartbeat requests are reserved by us.\n this.socket?.send(\n JSON.stringify({\n op: GatewayOpcodes.Heartbeat,\n d: this.previousSequenceNumber,\n }),\n )\n\n this.heart.lastBeat = Date.now()\n this.heart.acknowledged = false\n\n // After the random heartbeat jitter we can start a normal interval.\n this.heart.intervalId = setInterval(async () => {\n if (!this.isOpen()) return\n // gateway.debug(\"GW DEBUG\", `Running setInterval in heartbeat file. Shard: ${shardId}`);\n\n // gateway.debug(\"GW HEARTBEATING\", { shardId, shard: currentShard });\n\n // The Shard did not receive a heartbeat ACK from Discord in time,\n // therefore we have to assume that the connection has failed or got \"zombied\".\n // The Shard needs to start a re-identify action accordingly.\n // Reference: https://discord.com/developers/docs/topics/gateway#heartbeating-example-gateway-heartbeat-ack\n if (!this.heart.acknowledged) {\n this.close(ShardSocketCloseCodes.ZombiedConnection, 'Zombied connection, did not receive an heartbeat ACK in time.')\n\n return await this.identify()\n }\n\n this.heart.acknowledged = false\n\n // Using a direct socket.send call here because heartbeat requests are reserved by us.\n this.socket?.send(\n JSON.stringify({\n op: GatewayOpcodes.Heartbeat,\n d: this.previousSequenceNumber,\n }),\n )\n\n this.heart.lastBeat = Date.now()\n\n this.events.heartbeat?.(this)\n }, this.heart.interval)\n }, jitter)\n }\n\n /** Stop the heartbeating process with discord. */\n stopHeartbeating(): void {\n // Clear the regular heartbeat interval.\n clearInterval(this.heart.intervalId)\n // It's possible that the Shard got closed before the first jittered heartbeat.\n // To go safe we should clear the related timeout too.\n clearTimeout(this.heart.timeoutId)\n }\n\n /**\n * Connects the bot user to a voice or stage channel.\n *\n * This function sends the _Update Voice State_ gateway command over the gateway behind the scenes.\n *\n * @param guildId - The ID of the guild the voice channel to leave is in.\n * @param channelId - The ID of the channel you want to join.\n *\n * @remarks\n * Requires the `CONNECT` permission.\n *\n * Fires a _Voice State Update_ gateway event.\n *\n * @see {@link https://discord.com/developers/docs/topics/gateway#update-voice-state}\n */\n async joinVoiceChannel(\n guildId: BigString,\n channelId: BigString,\n options?: AtLeastOne<Omit<UpdateVoiceState, 'guildId' | 'channelId'>>,\n ): Promise<void> {\n logger.debug(`[Shard] joinVoiceChannel guildId: ${guildId} channelId: ${channelId}`)\n return await this.send({\n op: GatewayOpcodes.VoiceStateUpdate,\n d: {\n guild_id: guildId.toString(),\n channel_id: channelId.toString(),\n self_mute: Boolean(options?.selfMute),\n self_deaf: options?.selfDeaf ?? true,\n },\n })\n }\n\n /**\n * Edits the bot status in all shards that this gateway manages.\n *\n * @param data The status data to set the bots status to.\n * @returns Promise<void>\n */\n async editBotStatus(data: StatusUpdate): Promise<void> {\n logger.debug(`[Shard] editBotStatus data: ${JSON.stringify(data)}`)\n return await this.editShardStatus(data)\n }\n\n /**\n * Edits the bot's status on one shard.\n *\n * @param shardId The shard id to edit the status for.\n * @param data The status data to set the bots status to.\n * @returns Promise<void>\n */\n async editShardStatus(data: StatusUpdate): Promise<void> {\n logger.debug(`[Shard] editShardStatus shardId: ${this.id} -> data: ${JSON.stringify(data)}`)\n return await this.send({\n op: GatewayOpcodes.PresenceUpdate,\n d: {\n since: null,\n afk: false,\n activities: data.activities,\n status: data.status,\n },\n })\n }\n\n /**\n * Fetches the list of members for a guild over the gateway.\n *\n * @param guildId - The ID of the guild to get the list of members for.\n * @param options - The parameters for the fetching of the members.\n *\n * @remarks\n * If requesting the entire member list:\n * - Requires the `GUILD_MEMBERS` intent.\n *\n * If requesting presences ({@link RequestGuildMembers.presences | presences} set to `true`):\n * - Requires the `GUILD_PRESENCES` intent.\n *\n * If requesting a prefix ({@link RequestGuildMembers.query | query} non-`undefined`):\n * - Returns a maximum of 100 members.\n *\n * If requesting a users by ID ({@link RequestGuildMembers.userIds | userIds} non-`undefined`):\n * - Returns a maximum of 100 members.\n *\n * Fires a _Guild Members Chunk_ gateway event for every 1000 members fetched.\n *\n * @see {@link https://discord.com/developers/docs/topics/gateway#request-guild-members}\n */\n async requestMembers(guildId: BigString, options?: Omit<RequestGuildMembers, 'guildId'>): Promise<Camelize<DiscordMember[]>> {\n // You can request 1 member without the intent\n // Check if intents is not 0 as proxy ws won't set intents in other instances\n if (this.connection.intents && (!options?.limit || options.limit > 1) && !(this.connection.intents & GatewayIntents.GuildMembers)) {\n throw new Error('MISSING_INTENT_GUILD_MEMBERS')\n }\n\n if (options?.userIds?.length) {\n logger.debug(`[Shard] requestMembers guildId: ${guildId} -> setting user limit based on userIds length: ${options.userIds.length}`)\n options.limit = options.userIds.length\n }\n\n const nonce = `${guildId}-${Date.now()}`\n\n // Gateway does not require caching these requests so directly send and return\n if (!this.cache.requestMembers?.enabled) {\n logger.debug(`[Shard] requestMembers guildId: ${guildId} -> skipping cache -> options ${JSON.stringify(options)}`)\n await this.send({\n op: GatewayOpcodes.RequestGuildMembers,\n d: {\n guild_id: guildId.toString(),\n // If a query is provided use it, OR if a limit is NOT provided use \"\"\n query: options?.query ?? (options?.limit ? undefined : ''),\n limit: options?.limit ?? 0,\n presences: options?.presences ?? false,\n user_ids: options?.userIds?.map((id) => id.toString()),\n nonce,\n },\n })\n return []\n }\n\n return await new Promise((resolve) => {\n this.cache.requestMembers?.pending.set(nonce, { nonce, resolve, members: [] })\n\n logger.debug(`[Shard] requestMembers guildId: ${guildId} -> requesting members -> data: ${JSON.stringify(options)}`)\n this.send({\n op: GatewayOpcodes.RequestGuildMembers,\n d: {\n guild_id: guildId.toString(),\n // If a query is provided use it, OR if a limit is NOT provided use \"\"\n query: options?.query ?? (options?.limit ? undefined : ''),\n limit: options?.limit ?? 0,\n presences: options?.presences ?? false,\n user_ids: options?.userIds?.map((id) => id.toString()),\n nonce,\n },\n })\n })\n }\n\n /**\n * Leaves the voice channel the bot user is currently in.\n *\n * This function sends the _Update Voice State_ gateway command over the gateway behind the scenes.\n *\n * @param guildId - The ID of the guild the voice channel to leave is in.\n *\n * @remarks\n * Fires a _Voice State Update_ gateway event.\n *\n * @see {@link https://discord.com/developers/docs/topics/gateway#update-voice-state}\n */\n async leaveVoiceChannel(guildId: BigString): Promise<void> {\n logger.debug(`[Shard] leaveVoiceChannel guildId: ${guildId} Shard ${this.id}`)\n return await this.send({\n op: GatewayOpcodes.VoiceStateUpdate,\n d: {\n guild_id: guildId.toString(),\n channel_id: null,\n self_mute: false,\n self_deaf: false,\n },\n })\n }\n}\n\nexport interface ShardCreateOptions {\n /** The shard id */\n id: number\n /** The connection details */\n connection: ShardGatewayConfig\n /** The event handlers for events on the shard. */\n events: ShardEvents\n}\n\nexport default DiscordenoShard\n"],"names":["GatewayCloseEventCodes","GatewayIntents","GatewayOpcodes","camelize","Collection","createLeakyBucket","delay","logger","inflateSync","WebSocket","ShardSocketCloseCodes","ShardState","DiscordenoShard","maxRequestsPerRateLimitTick","previousSequenceNumber","rateLimitResetInterval","state","Offline","resumeGatewayUrl","events","offlineSendQueue","resolves","Map","bucket","max","refillInterval","refillAmount","cache","requestMembers","enabled","pending","constructor","options","id","connection","heart","acknowledged","interval","gatewayConfig","calculateSafeRequests","safeRequests","Math","ceil","checkOffline","highPriority","isOpen","Promise","resolve","unshift","push","close","code","reason","socket","readyState","OPEN","connect","Identifying","Resuming","includes","Connecting","connecting","url","URL","origin","searchParams","set","version","toString","onerror","event","console","log","error","onclose","handleClose","onmessage","message","handleMessage","onopen","Unidentified","connected","identify","ReIdentifying","identifying","requestIdentify","send","op","Identify","d","token","compress","properties","intents","shard","totalShards","presence","makePresence","identified","delete","resume","ResumeClosingOldConnection","sessionId","Resume","session_id","seq","acquire","JSON","stringify","shutdown","Shutdown","stopHeartbeating","TestingFinished","disconnected","Resharded","ZombiedConnection","Disconnected","UnknownOpcode","NotAuthenticated","InvalidSeq","RateLimited","SessionTimedOut","AuthenticationFailed","InvalidShard","ShardingRequired","InvalidApiVersion","InvalidIntents","DisallowedIntents","Error","UnknownError","DecodeError","AlreadyAuthenticated","handleDiscordPacket","packet","lastAck","Date","now","lastBeat","rtt","Heartbeat","heartbeat","Hello","heartbeat_interval","startHeartbeating","waiting","hello","HeartbeatACK","heartbeatAck","Reconnect","requestedReconnect","InvalidSession","resumable","invalidSession","floor","random","get","t","Connected","resumed","map","payload","resume_gateway_url","s","preProcessMessage","data","Blob","arrayBuffer","parse","jitter","timeoutId","setTimeout","intervalId","setInterval","clearInterval","clearTimeout","joinVoiceChannel","guildId","channelId","debug","VoiceStateUpdate","guild_id","channel_id","self_mute","Boolean","selfMute","self_deaf","selfDeaf","editBotStatus","editShardStatus","PresenceUpdate","since","afk","activities","status","limit","GuildMembers","userIds","length","nonce","RequestGuildMembers","query","undefined","presences","user_ids","members","leaveVoiceChannel"],"mappings":"AAUA,SAASA,sBAAsB,EAAEC,cAAc,EAAEC,cAAc,QAAQ,oBAAmB;AAC1F,SAASC,QAAQ,EAAEC,UAAU,EAAEC,iBAAiB,EAAEC,KAAK,EAAEC,MAAM,QAAQ,oBAAmB;AAC1F,SAASC,WAAW,QAAQ,YAAW;AACvC,OAAOC,eAAe,KAAI;AAG1B,SAASC,qBAAqB,EAAEC,UAAU,QAAQ,aAAY;AAE9D,OAAO,MAAMC;IAOX,0HAA0H,GAC1HC,8BAAsC,IAAG;IACzC,0CAA0C,GAC1CC,yBAAwC,IAAI,CAAA;IAC5C,4EAA4E,GAC5EC,yBAAiC,MAAK;IAKtC,wCAAwC,GACxCC,QAAQL,WAAWM,OAAO,CAAA;IAC1B,iFAAiF,GACjFC,mBAA2B,GAAE;IAC7B,sCAAsC,GACtCC,SAAsB,CAAC,EAAC;IACxB,mGAAmG,GACnGC,mBAAiD,EAAE,CAA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ACF;AACF,CAAC;AAWD,eAAe7K,gBAAe"}
1
+ {"version":3,"sources":["../src/Shard.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-confusing-void-expression */\nimport type {\n AtLeastOne,\n BigString,\n Camelize,\n DiscordGatewayPayload,\n DiscordHello,\n DiscordMember,\n DiscordReady,\n RequestGuildMembers,\n} from '@discordeno/types'\nimport { GatewayCloseEventCodes, GatewayIntents, GatewayOpcodes } from '@discordeno/types'\nimport { Collection, LeakyBucket, camelize, delay, logger } from '@discordeno/utils'\nimport { inflateSync } from 'node:zlib'\nimport WebSocket from 'ws'\nimport type { RequestMemberRequest } from './manager.js'\nimport type { BotStatusUpdate, ShardEvents, ShardGatewayConfig, ShardHeart, ShardSocketRequest, StatusUpdate, UpdateVoiceState } from './types.js'\nimport { ShardSocketCloseCodes, ShardState } from './types.js'\n\nexport class DiscordenoShard {\n /** The id of the shard */\n id: number\n /** The connection config details that this shard will used to connect to discord. */\n connection: ShardGatewayConfig\n /** This contains all the heartbeat information */\n heart: ShardHeart\n /** The maximum of requests which can be send to discord per rate limit tick. Typically this value should not be changed. */\n maxRequestsPerRateLimitTick: number = 120\n /** The previous payload sequence number. */\n previousSequenceNumber: number | null = null\n /** In which interval (in milliseconds) the gateway resets it's rate limit. */\n rateLimitResetInterval: number = 60000\n /** Current session id of the shard if present. */\n sessionId?: string\n /** This contains the WebSocket connection to Discord, if currently connected. */\n socket?: WebSocket\n /** Current internal state of the this. */\n state = ShardState.Offline\n /** The url provided by discord to use when resuming a connection for this this. */\n resumeGatewayUrl: string = ''\n /** The shard related event handlers. */\n events: ShardEvents = {}\n /** Cache for pending gateway requests which should have been send while the gateway went offline. */\n offlineSendQueue: Array<(_?: unknown) => void> = []\n /** Resolve internal waiting states. Mapped by SelectedEvents => ResolveFunction */\n resolves = new Map<'READY' | 'RESUMED' | 'INVALID_SESSION', (payload: DiscordGatewayPayload) => void>()\n /** Shard bucket. Only access this if you know what you are doing. Bucket for handling shard request rate limits. */\n bucket: LeakyBucket\n\n /** This managers cache related settings. */\n cache = {\n requestMembers: {\n /**\n * Whether or not request member requests should be cached.\n * @default false\n */\n enabled: false,\n /** The pending requests. */\n pending: new Collection<string, RequestMemberRequest>(),\n },\n }\n\n constructor(options: ShardCreateOptions) {\n this.id = options.id\n this.connection = options.connection\n this.events = options.events\n\n this.heart = {\n acknowledged: false,\n interval: 45000,\n }\n\n if (options.requestIdentify) this.requestIdentify = options.requestIdentify\n if (options.shardIsReady) this.shardIsReady = options.shardIsReady\n\n this.bucket = new LeakyBucket({\n max: this.calculateSafeRequests(),\n refillAmount: this.calculateSafeRequests(),\n refillInterval: 60000,\n })\n }\n\n /** The gateway configuration which is used to connect to Discord. */\n get gatewayConfig(): ShardGatewayConfig {\n return this.connection\n }\n\n /** The url to connect to. Intially this is the discord gateway url, and then is switched to resume gateway url once a READY is received. */\n get connectionUrl(): string {\n // Use || and not ?? here. ?? will cause a bug.\n return this.resumeGatewayUrl || this.gatewayConfig.url\n }\n\n /** Calculate the amount of requests which can safely be made per rate limit interval, before the gateway gets disconnected due to an exceeded rate limit. */\n calculateSafeRequests(): number {\n // * 2 adds extra safety layer for discords OP 1 requests that we need to respond to\n const safeRequests = this.maxRequestsPerRateLimitTick - Math.ceil(this.rateLimitResetInterval / this.heart.interval) * 2\n\n return safeRequests < 0 ? 0 : safeRequests\n }\n\n async checkOffline(highPriority: boolean): Promise<void> {\n if (!this.isOpen()) {\n await new Promise((resolve) => {\n // Higher priority requests get added at the beginning of the array.\n if (highPriority) this.offlineSendQueue.unshift(resolve)\n else this.offlineSendQueue.push(resolve)\n })\n }\n }\n\n /** Close the socket connection to discord if present. */\n close(code: number, reason: string): void {\n if (this.socket?.readyState !== WebSocket.OPEN) return\n\n this.socket?.close(code, reason)\n }\n\n /** Connect the shard with the gateway and start heartbeating. This will not identify the shard to the gateway. */\n async connect(): Promise<DiscordenoShard> {\n // Only set the shard to `Connecting` state,\n // if the connection request does not come from an identify or resume action.\n if (![ShardState.Identifying, ShardState.Resuming].includes(this.state)) {\n this.state = ShardState.Connecting\n }\n this.events.connecting?.(this)\n\n const url = new URL(this.connectionUrl)\n url.searchParams.set('v', this.gatewayConfig.version.toString())\n url.searchParams.set('encoding', 'json')\n\n const socket = new WebSocket(url.toString())\n this.socket = socket\n\n // TODO: proper event handling\n socket.onerror = (event) => console.log({ error: event, shardId: this.id })\n socket.onclose = async (event) => await this.handleClose(event)\n socket.onmessage = async (message) => await this.handleMessage(message)\n\n return await new Promise((resolve) => {\n socket.onopen = () => {\n // Only set the shard to `Unidentified` state,\n // if the connection request does not come from an identify or resume action.\n if (![ShardState.Identifying, ShardState.Resuming].includes(this.state)) {\n this.state = ShardState.Unidentified\n }\n this.events.connected?.(this)\n\n resolve(this)\n }\n })\n }\n\n /** Identify the shard to the gateway. If not connected, this will also connect the shard to the gateway. */\n async identify(): Promise<void> {\n // A new identify has been requested even though there is already a connection open.\n // Therefore we need to close the old connection and heartbeating before creating a new one.\n if (this.isOpen()) {\n logger.debug(`CLOSING EXISTING SHARD: #${this.id}`)\n this.close(ShardSocketCloseCodes.ReIdentifying, 'Re-identifying closure of old connection.')\n }\n\n this.state = ShardState.Identifying\n this.events.identifying?.(this)\n\n // It is possible that the shard is in Heartbeating state but not identified,\n // so check whether there is already a gateway connection existing.\n // If not we need to create one before we identify.\n if (!this.isOpen()) {\n await this.connect()\n }\n\n this.send(\n {\n op: GatewayOpcodes.Identify,\n d: {\n token: `Bot ${this.gatewayConfig.token}`,\n compress: this.gatewayConfig.compress,\n properties: this.gatewayConfig.properties,\n intents: this.gatewayConfig.intents,\n shard: [this.id, this.gatewayConfig.totalShards],\n presence: await this.makePresence?.(),\n },\n },\n true,\n )\n\n return await new Promise((resolve) => {\n this.resolves.set('READY', () => {\n this.events.identified?.(this)\n // Tells the manager that this shard is ready\n this.shardIsReady()\n resolve()\n })\n // When identifying too fast,\n // Discord sends an invalid session payload.\n // This can safely be ignored though and the shard starts a new identify action.\n this.resolves.set('INVALID_SESSION', () => {\n this.resolves.delete('READY')\n resolve()\n })\n })\n }\n\n /** Check whether the connection to Discord is currently open. */\n isOpen(): boolean {\n return this.socket?.readyState === WebSocket.OPEN\n }\n\n /** Attempt to resume the previous shards session with the gateway. */\n async resume(): Promise<void> {\n logger.debug(`[Gateway] Resuming Shard #${this.id}`)\n // It has been requested to resume the Shards session.\n // It's possible that the shard is still connected with Discord's gateway therefore we need to forcefully close it.\n if (this.isOpen()) {\n this.close(ShardSocketCloseCodes.ResumeClosingOldConnection, 'Reconnecting the shard, closing old connection.')\n }\n\n // Shard has never identified, so we cannot resume.\n if (!this.sessionId) {\n logger.debug(`[Shard] Trying to resume a shard #${this.id} that was NOT first identified. (No session id found)`)\n\n return await this.identify()\n }\n\n this.state = ShardState.Resuming\n\n // Before we can resume, we need to create a new connection with Discord's gateway.\n await this.connect()\n\n this.send(\n {\n op: GatewayOpcodes.Resume,\n d: {\n token: `Bot ${this.gatewayConfig.token}`,\n session_id: this.sessionId,\n seq: this.previousSequenceNumber ?? 0,\n },\n },\n true,\n )\n\n return await new Promise((resolve) => {\n this.resolves.set('RESUMED', () => resolve())\n // If it is attempted to resume with an invalid session id,\n // Discord sends an invalid session payload\n // Not erroring here since it is easy that this happens, also it would be not catchable\n this.resolves.set('INVALID_SESSION', () => {\n this.resolves.delete('RESUMED')\n resolve()\n })\n })\n }\n\n /** Send a message to Discord.\n * @param {boolean} [highPriority=false] - Whether this message should be send asap.\n */\n async send(message: ShardSocketRequest, highPriority = false): Promise<void> {\n // Before acquiring a token from the bucket, check whether the shard is currently offline or not.\n // Else bucket and token wait time just get wasted.\n await this.checkOffline(highPriority)\n\n await this.bucket.acquire(highPriority)\n\n // It's possible, that the shard went offline after a token has been acquired from the bucket.\n await this.checkOffline(highPriority)\n\n this.socket?.send(JSON.stringify(message))\n }\n\n /** Shutdown the this. Forcefully disconnect the shard from Discord. The shard may not attempt to reconnect with Discord. */\n async shutdown(): Promise<void> {\n this.close(ShardSocketCloseCodes.Shutdown, 'Shard shutting down.')\n this.state = ShardState.Offline\n }\n\n /** Handle a gateway connection close. */\n async handleClose(close: WebSocket.CloseEvent): Promise<void> {\n // gateway.debug(\"GW CLOSED\", { shardId, payload: event });\n\n this.stopHeartbeating()\n\n switch (close.code) {\n case ShardSocketCloseCodes.TestingFinished: {\n this.state = ShardState.Offline\n this.events.disconnected?.(this)\n\n return\n }\n // On these codes a manual start will be done.\n case ShardSocketCloseCodes.Shutdown:\n case ShardSocketCloseCodes.ReIdentifying:\n case ShardSocketCloseCodes.Resharded:\n case ShardSocketCloseCodes.ResumeClosingOldConnection:\n case ShardSocketCloseCodes.ZombiedConnection: {\n this.state = ShardState.Disconnected\n this.events.disconnected?.(this)\n\n // gateway.debug(\"GW CLOSED_RECONNECT\", { shardId, payload: event });\n return\n }\n // Gateway connection closes which require a new identify.\n case GatewayCloseEventCodes.UnknownOpcode:\n case GatewayCloseEventCodes.NotAuthenticated:\n case GatewayCloseEventCodes.InvalidSeq:\n case GatewayCloseEventCodes.RateLimited:\n case GatewayCloseEventCodes.SessionTimedOut: {\n logger.debug(`[Shard] Gateway connection closing requiring re-identify. Code: ${close.code}`)\n this.state = ShardState.Identifying\n this.events.disconnected?.(this)\n\n return await this.identify()\n }\n // When these codes are received something went really wrong.\n // On those we cannot start a reconnect attempt.\n case GatewayCloseEventCodes.AuthenticationFailed:\n case GatewayCloseEventCodes.InvalidShard:\n case GatewayCloseEventCodes.ShardingRequired:\n case GatewayCloseEventCodes.InvalidApiVersion:\n case GatewayCloseEventCodes.InvalidIntents:\n case GatewayCloseEventCodes.DisallowedIntents: {\n this.state = ShardState.Offline\n this.events.disconnected?.(this)\n\n throw new Error(close.reason || 'Discord gave no reason! GG! You broke Discord!')\n }\n // Gateway connection closes on which a resume is allowed.\n case GatewayCloseEventCodes.UnknownError:\n case GatewayCloseEventCodes.DecodeError:\n case GatewayCloseEventCodes.AlreadyAuthenticated:\n default: {\n this.state = ShardState.Resuming\n this.events.disconnected?.(this)\n\n return await this.resume()\n }\n }\n }\n\n /** Handles a incoming gateway packet. */\n async handleDiscordPacket(packet: DiscordGatewayPayload): Promise<void> {\n // Edge case start: https://github.com/discordeno/discordeno/issues/2311\n this.heart.lastAck = Date.now()\n // Manually calculating the round trip time for users who need it.\n if (this.heart.lastBeat && !this.heart.acknowledged) {\n this.heart.rtt = this.heart.lastAck - this.heart.lastBeat\n }\n this.heart.acknowledged = true\n // Edge case end!\n\n switch (packet.op) {\n case GatewayOpcodes.Heartbeat: {\n // TODO: can this actually happen\n if (!this.isOpen()) return\n\n this.heart.lastBeat = Date.now()\n // Discord randomly sends this requiring an immediate heartbeat back.\n // Using a direct socket.send call here because heartbeat requests are reserved by us.\n this.socket?.send(\n JSON.stringify({\n op: GatewayOpcodes.Heartbeat,\n d: this.previousSequenceNumber,\n }),\n )\n this.events.heartbeat?.(this)\n\n break\n }\n case GatewayOpcodes.Hello: {\n const interval = (packet.d as DiscordHello).heartbeat_interval\n\n this.startHeartbeating(interval)\n\n if (this.state !== ShardState.Resuming) {\n const currentQueue = [...this.bucket.queue]\n // HELLO has been send on a non resume action.\n // This means that the shard starts a new session,\n // therefore the rate limit interval has been reset too.\n this.bucket = new LeakyBucket({\n max: this.calculateSafeRequests(),\n refillInterval: 60000,\n refillAmount: this.calculateSafeRequests(),\n })\n\n // Queue should not be lost on a re-identify.\n this.bucket.queue.unshift(...currentQueue)\n }\n\n this.events.hello?.(this)\n\n break\n }\n case GatewayOpcodes.HeartbeatACK: {\n this.events.heartbeatAck?.(this)\n\n break\n }\n case GatewayOpcodes.Reconnect: {\n // gateway.debug(\"GW RECONNECT\", { shardId });\n\n this.events.requestedReconnect?.(this)\n\n await this.resume()\n\n break\n }\n case GatewayOpcodes.InvalidSession: {\n const resumable = packet.d as boolean\n logger.debug(`[Shard] Received Invalid Session for Shard #${this.id} with resumeable as ${resumable.toString()}`)\n\n this.events.invalidSession?.(this, resumable)\n\n // We need to wait for a random amount of time between 1 and 5\n // Reference: https://discord.com/developers/docs/topics/gateway#resuming\n await delay(Math.floor((Math.random() * 4 + 1) * 1000))\n\n this.resolves.get('INVALID_SESSION')?.(packet)\n this.resolves.delete('INVALID_SESSION')\n\n // When resumable is false we need to re-identify\n if (!resumable) {\n await this.requestIdentify()\n\n break\n }\n\n // The session is invalid but apparently it is resumable\n await this.resume()\n\n break\n }\n }\n\n if (packet.t === 'RESUMED') {\n // gateway.debug(\"GW RESUMED\", { shardId });\n\n this.state = ShardState.Connected\n this.events.resumed?.(this)\n\n // Continue the requests which have been queued since the shard went offline.\n this.offlineSendQueue.map((resolve) => resolve())\n\n this.resolves.get('RESUMED')?.(packet)\n this.resolves.delete('RESUMED')\n } else if (packet.t === 'READY') {\n // Important for future resumes.\n\n const payload = packet.d as DiscordReady\n\n this.resumeGatewayUrl = payload.resume_gateway_url\n\n this.sessionId = payload.session_id\n this.state = ShardState.Connected\n\n // Continue the requests which have been queued since the shard went offline.\n // Important when this is a re-identify\n this.offlineSendQueue.map((resolve) => resolve())\n\n this.resolves.get('READY')?.(packet)\n this.resolves.delete('READY')\n }\n\n // Update the sequence number if it is present\n // `s` can be either `null` or a `number`.\n // In order to prevent update misses when `s` is `0` we check against null.\n if (packet.s !== null) {\n this.previousSequenceNumber = packet.s\n }\n\n this.forwardToBot(packet);\n }\n\n forwardToBot(packet: DiscordGatewayPayload): void {\n // The necessary handling required for the Shards connection has been finished.\n // Now the event can be safely forwarded.\n this.events.message?.(this, camelize(packet))\n }\n\n /** Handle an incoming gateway message. */\n async handleMessage(message: WebSocket.MessageEvent): Promise<void> {\n let preProcessMessage = message.data\n\n // If message compression is enabled,\n // Discord might send zlib compressed payloads.\n if (this.gatewayConfig.compress && preProcessMessage instanceof Blob) {\n preProcessMessage = inflateSync(await preProcessMessage.arrayBuffer()).toString()\n }\n\n // Safeguard incase decompression failed to make a string.\n if (typeof preProcessMessage !== 'string') return\n\n return await this.handleDiscordPacket(JSON.parse(preProcessMessage) as DiscordGatewayPayload)\n }\n\n /**\n * Override in order to make the shards presence.\n * async in case devs create the presence based on eg. database values.\n * Passing the shard's id there to make it easier for the dev to use this function.\n */\n async makePresence(): Promise<BotStatusUpdate | undefined> {\n // eslint-disable-next-line no-useless-return\n return\n }\n\n /** This function communicates with the management process, in order to know whether its free to identify. When this function resolves, this means that the shard is allowed to send an identify payload to discord. */\n async requestIdentify(): Promise<void> {}\n\n /** This function communicates with the management process, in order to tell it can identify the next shard. */\n async shardIsReady(): Promise<void> {}\n\n /** Start sending heartbeat payloads to Discord in the provided interval. */\n startHeartbeating(interval: number): void {\n // If old heartbeast exist like after resume, clear the old ones.\n if (this.heart.intervalId) clearInterval(this.heart.intervalId)\n if (this.heart.timeoutId) clearTimeout(this.heart.timeoutId)\n\n this.heart.interval = interval\n\n // Only set the shard's state to `Unidentified`\n // if heartbeating has not been started due to an identify or resume action.\n if ([ShardState.Disconnected, ShardState.Offline].includes(this.state)) {\n this.state = ShardState.Unidentified\n }\n\n // The first heartbeat needs to be send with a random delay between `0` and `interval`\n // Using a `setTimeout(_, jitter)` here to accomplish that.\n // `Math.random()` can be `0` so we use `0.5` if this happens\n // Reference: https://discord.com/developers/docs/topics/gateway#heartbeating\n const jitter = Math.ceil(this.heart.interval * (Math.random() || 0.5))\n this.heart.timeoutId = setTimeout(() => {\n if (!this.isOpen()) return\n\n // Using a direct socket.send call here because heartbeat requests are reserved by us.\n this.socket?.send(\n JSON.stringify({\n op: GatewayOpcodes.Heartbeat,\n d: this.previousSequenceNumber,\n }),\n )\n\n this.heart.lastBeat = Date.now()\n this.heart.acknowledged = false\n\n // After the random heartbeat jitter we can start a normal interval.\n this.heart.intervalId = setInterval(async () => {\n if (!this.isOpen()) return\n // gateway.debug(\"GW DEBUG\", `Running setInterval in heartbeat file. Shard: ${shardId}`);\n\n // gateway.debug(\"GW HEARTBEATING\", { shardId, shard: currentShard });\n\n // The Shard did not receive a heartbeat ACK from Discord in time,\n // therefore we have to assume that the connection has failed or got \"zombied\".\n // The Shard needs to start a re-identify action accordingly.\n // Reference: https://discord.com/developers/docs/topics/gateway#heartbeating-example-gateway-heartbeat-ack\n if (!this.heart.acknowledged) {\n logger.debug(`[Shard] Heartbeat not acknowledged for shard #${this.id}.`)\n this.close(ShardSocketCloseCodes.ZombiedConnection, 'Zombied connection, did not receive an heartbeat ACK in time.')\n\n return await this.identify()\n }\n\n this.heart.acknowledged = false\n\n // Using a direct socket.send call here because heartbeat requests are reserved by us.\n this.socket?.send(\n JSON.stringify({\n op: GatewayOpcodes.Heartbeat,\n d: this.previousSequenceNumber,\n }),\n )\n\n this.heart.lastBeat = Date.now()\n\n this.events.heartbeat?.(this)\n }, this.heart.interval)\n }, jitter)\n }\n\n /** Stop the heartbeating process with discord. */\n stopHeartbeating(): void {\n // Clear the regular heartbeat interval.\n clearInterval(this.heart.intervalId)\n // It's possible that the Shard got closed before the first jittered heartbeat.\n // To go safe we should clear the related timeout too.\n clearTimeout(this.heart.timeoutId)\n }\n\n /**\n * Connects the bot user to a voice or stage channel.\n *\n * This function sends the _Update Voice State_ gateway command over the gateway behind the scenes.\n *\n * @param guildId - The ID of the guild the voice channel to leave is in.\n * @param channelId - The ID of the channel you want to join.\n *\n * @remarks\n * Requires the `CONNECT` permission.\n *\n * Fires a _Voice State Update_ gateway event.\n *\n * @see {@link https://discord.com/developers/docs/topics/gateway#update-voice-state}\n */\n async joinVoiceChannel(\n guildId: BigString,\n channelId: BigString,\n options?: AtLeastOne<Omit<UpdateVoiceState, 'guildId' | 'channelId'>>,\n ): Promise<void> {\n logger.debug(`[Shard] joinVoiceChannel guildId: ${guildId} channelId: ${channelId}`)\n await this.send({\n op: GatewayOpcodes.VoiceStateUpdate,\n d: {\n guild_id: guildId.toString(),\n channel_id: channelId.toString(),\n self_mute: Boolean(options?.selfMute),\n self_deaf: options?.selfDeaf ?? true,\n },\n })\n }\n\n /**\n * Edits the bot status in all shards that this gateway manages.\n *\n * @param data The status data to set the bots status to.\n * @returns Promise<void>\n */\n async editBotStatus(data: StatusUpdate): Promise<void> {\n logger.debug(`[Shard] editBotStatus data: ${JSON.stringify(data)}`)\n await this.editShardStatus(data)\n }\n\n /**\n * Edits the bot's status on one shard.\n *\n * @param shardId The shard id to edit the status for.\n * @param data The status data to set the bots status to.\n * @returns Promise<void>\n */\n async editShardStatus(data: StatusUpdate): Promise<void> {\n logger.debug(`[Shard] editShardStatus shardId: ${this.id} -> data: ${JSON.stringify(data)}`)\n await this.send({\n op: GatewayOpcodes.PresenceUpdate,\n d: {\n since: null,\n afk: false,\n activities: data.activities,\n status: data.status,\n },\n })\n }\n\n /**\n * Fetches the list of members for a guild over the gateway.\n *\n * @param guildId - The ID of the guild to get the list of members for.\n * @param options - The parameters for the fetching of the members.\n *\n * @remarks\n * If requesting the entire member list:\n * - Requires the `GUILD_MEMBERS` intent.\n *\n * If requesting presences ({@link RequestGuildMembers.presences | presences} set to `true`):\n * - Requires the `GUILD_PRESENCES` intent.\n *\n * If requesting a prefix ({@link RequestGuildMembers.query | query} non-`undefined`):\n * - Returns a maximum of 100 members.\n *\n * If requesting a users by ID ({@link RequestGuildMembers.userIds | userIds} non-`undefined`):\n * - Returns a maximum of 100 members.\n *\n * Fires a _Guild Members Chunk_ gateway event for every 1000 members fetched.\n *\n * @see {@link https://discord.com/developers/docs/topics/gateway#request-guild-members}\n */\n async requestMembers(guildId: BigString, options?: Omit<RequestGuildMembers, 'guildId'>): Promise<Camelize<DiscordMember[]>> {\n // You can request 1 member without the intent\n // Check if intents is not 0 as proxy ws won't set intents in other instances\n if (this.connection.intents && (!options?.limit || options.limit > 1) && !(this.connection.intents & GatewayIntents.GuildMembers)) {\n throw new Error('MISSING_INTENT_GUILD_MEMBERS')\n }\n\n if (options?.userIds?.length) {\n logger.debug(`[Shard] requestMembers guildId: ${guildId} -> setting user limit based on userIds length: ${options.userIds.length}`)\n options.limit = options.userIds.length\n }\n\n const nonce = `${guildId}-${Date.now()}`\n\n // Gateway does not require caching these requests so directly send and return\n if (!this.cache.requestMembers?.enabled) {\n logger.debug(`[Shard] requestMembers guildId: ${guildId} -> skipping cache -> options ${JSON.stringify(options)}`)\n await this.send({\n op: GatewayOpcodes.RequestGuildMembers,\n d: {\n guild_id: guildId.toString(),\n // If a query is provided use it, OR if a limit is NOT provided use \"\"\n query: options?.query ?? (options?.limit ? undefined : ''),\n limit: options?.limit ?? 0,\n presences: options?.presences ?? false,\n user_ids: options?.userIds?.map((id) => id.toString()),\n nonce,\n },\n })\n return []\n }\n\n return await new Promise((resolve) => {\n this.cache.requestMembers?.pending.set(nonce, { nonce, resolve, members: [] })\n\n logger.debug(`[Shard] requestMembers guildId: ${guildId} -> requesting members -> data: ${JSON.stringify(options)}`)\n this.send({\n op: GatewayOpcodes.RequestGuildMembers,\n d: {\n guild_id: guildId.toString(),\n // If a query is provided use it, OR if a limit is NOT provided use \"\"\n query: options?.query ?? (options?.limit ? undefined : ''),\n limit: options?.limit ?? 0,\n presences: options?.presences ?? false,\n user_ids: options?.userIds?.map((id) => id.toString()),\n nonce,\n },\n })\n })\n }\n\n /**\n * Leaves the voice channel the bot user is currently in.\n *\n * This function sends the _Update Voice State_ gateway command over the gateway behind the scenes.\n *\n * @param guildId - The ID of the guild the voice channel to leave is in.\n *\n * @remarks\n * Fires a _Voice State Update_ gateway event.\n *\n * @see {@link https://discord.com/developers/docs/topics/gateway#update-voice-state}\n */\n async leaveVoiceChannel(guildId: BigString): Promise<void> {\n logger.debug(`[Shard] leaveVoiceChannel guildId: ${guildId} Shard ${this.id}`)\n await this.send({\n op: GatewayOpcodes.VoiceStateUpdate,\n d: {\n guild_id: guildId.toString(),\n channel_id: null,\n self_mute: false,\n self_deaf: false,\n },\n })\n }\n}\n\nexport interface ShardCreateOptions {\n /** The shard id */\n id: number\n /** The connection details */\n connection: ShardGatewayConfig\n /** The event handlers for events on the shard. */\n events: ShardEvents\n /** The handler to request a space to make an identify request. */\n requestIdentify?: () => Promise<void>\n /** The handler to alert the gateway manager that this shard has received a READY event. */\n shardIsReady?: () => Promise<void>\n}\n\nexport default DiscordenoShard\n"],"names":["GatewayCloseEventCodes","GatewayIntents","GatewayOpcodes","Collection","LeakyBucket","camelize","delay","logger","inflateSync","WebSocket","ShardSocketCloseCodes","ShardState","DiscordenoShard","constructor","options","maxRequestsPerRateLimitTick","previousSequenceNumber","rateLimitResetInterval","state","Offline","resumeGatewayUrl","events","offlineSendQueue","resolves","Map","cache","requestMembers","enabled","pending","id","connection","heart","acknowledged","interval","requestIdentify","shardIsReady","bucket","max","calculateSafeRequests","refillAmount","refillInterval","gatewayConfig","connectionUrl","url","safeRequests","Math","ceil","checkOffline","highPriority","isOpen","Promise","resolve","unshift","push","close","code","reason","socket","readyState","OPEN","connect","Identifying","Resuming","includes","Connecting","connecting","URL","searchParams","set","version","toString","onerror","event","console","log","error","shardId","onclose","handleClose","onmessage","message","handleMessage","onopen","Unidentified","connected","identify","debug","ReIdentifying","identifying","send","op","Identify","d","token","compress","properties","intents","shard","totalShards","presence","makePresence","identified","delete","resume","ResumeClosingOldConnection","sessionId","Resume","session_id","seq","acquire","JSON","stringify","shutdown","Shutdown","stopHeartbeating","TestingFinished","disconnected","Resharded","ZombiedConnection","Disconnected","UnknownOpcode","NotAuthenticated","InvalidSeq","RateLimited","SessionTimedOut","AuthenticationFailed","InvalidShard","ShardingRequired","InvalidApiVersion","InvalidIntents","DisallowedIntents","Error","UnknownError","DecodeError","AlreadyAuthenticated","handleDiscordPacket","packet","lastAck","Date","now","lastBeat","rtt","Heartbeat","heartbeat","Hello","heartbeat_interval","startHeartbeating","currentQueue","queue","hello","HeartbeatACK","heartbeatAck","Reconnect","requestedReconnect","InvalidSession","resumable","invalidSession","floor","random","get","t","Connected","resumed","map","payload","resume_gateway_url","s","forwardToBot","preProcessMessage","data","Blob","arrayBuffer","parse","intervalId","clearInterval","timeoutId","clearTimeout","jitter","setTimeout","setInterval","joinVoiceChannel","guildId","channelId","VoiceStateUpdate","guild_id","channel_id","self_mute","Boolean","selfMute","self_deaf","selfDeaf","editBotStatus","editShardStatus","PresenceUpdate","since","afk","activities","status","limit","GuildMembers","userIds","length","nonce","RequestGuildMembers","query","undefined","presences","user_ids","members","leaveVoiceChannel"],"mappings":"AAAA,kEAAkE,GAWlE,SAASA,sBAAsB,EAAEC,cAAc,EAAEC,cAAc,QAAQ,oBAAmB;AAC1F,SAASC,UAAU,EAAEC,WAAW,EAAEC,QAAQ,EAAEC,KAAK,EAAEC,MAAM,QAAQ,oBAAmB;AACpF,SAASC,WAAW,QAAQ,YAAW;AACvC,OAAOC,eAAe,KAAI;AAG1B,SAASC,qBAAqB,EAAEC,UAAU,QAAQ,aAAY;AAE9D,OAAO,MAAMC;IA2CXC,YAAYC,OAA2B,CAAE;QApCzC,0HAA0H,QAC1HC,8BAAsC;QACtC,0CAA0C,QAC1CC,yBAAwC,IAAI;QAC5C,4EAA4E,QAC5EC,yBAAiC;QAKjC,wCAAwC,QACxCC,QAAQP,WAAWQ,OAAO;QAC1B,iFAAiF,QACjFC,mBAA2B;QAC3B,sCAAsC,QACtCC,SAAsB,CAAC;QACvB,mGAAmG,QACnGC,mBAAiD,EAAE;QACnD,iFAAiF,QACjFC,WAAW,IAAIC;QAIf,0CAA0C,QAC1CC,QAAQ;YACNC,gBAAgB;gBACd;;;OAGC,GACDC,SAAS,KAAK;gBACd,0BAA0B,GAC1BC,SAAS,IAAIzB;YACf;QACF;QAGE,IAAI,CAAC0B,EAAE,GAAGf,QAAQe,EAAE;QACpB,IAAI,CAACC,UAAU,GAAGhB,QAAQgB,UAAU;QACpC,IAAI,CAACT,MAAM,GAAGP,QAAQO,MAAM;QAE5B,IAAI,CAACU,KAAK,GAAG;YACXC,cAAc,KAAK;YACnBC,UAAU;QACZ;QAEA,IAAInB,QAAQoB,eAAe,EAAE,IAAI,CAACA,eAAe,GAAGpB,QAAQoB,eAAe;QAC3E,IAAIpB,QAAQqB,YAAY,EAAE,IAAI,CAACA,YAAY,GAAGrB,QAAQqB,YAAY;QAElE,IAAI,CAACC,MAAM,GAAG,IAAIhC,YAAY;YAC5BiC,KAAK,IAAI,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OAAO,EAAE,IAAI,CAACxJ,EAAE,CAAC,CAAC;QAC7E,MAAM,IAAI,CAAC4D,IAAI,CAAC;YACdC,IAAIxF,eAAeqL,gBAAgB;YACnC3F,GAAG;gBACD4F,UAAUH,QAAQ/G,QAAQ;gBAC1BmH,YAAY,IAAI;gBAChBC,WAAW,KAAK;gBAChBG,WAAW,KAAK;YAClB;QACF;IACF;AACF,CAAC;AAeD,eAAejL,gBAAe"}
package/dist/manager.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import type { AtLeastOne, BigString, Camelize, DiscordGetGatewayBot, DiscordMember, RequestGuildMembers } from '@discordeno/types';
2
- import type { LeakyBucket } from '@discordeno/utils';
3
2
  import { Collection } from '@discordeno/utils';
4
3
  import Shard from './Shard.js';
5
4
  import type { ShardEvents, StatusUpdate, UpdateVoiceState } from './types.js';
@@ -20,6 +19,11 @@ export interface CreateGatewayManagerOptions {
20
19
  * @default 5300
21
20
  */
22
21
  spawnShardDelay?: number;
22
+ /**
23
+ * Whether to send the discord packets in snake case form.
24
+ * @default false
25
+ */
26
+ preferSnakeCase?: boolean;
23
27
  /**
24
28
  * Total amount of shards your bot uses. Useful for zero-downtime updates or resharding.
25
29
  * @default 1
@@ -99,7 +103,8 @@ export interface GatewayManager extends Required<CreateGatewayManagerOptions> {
99
103
  id: number;
100
104
  queue: number[];
101
105
  }>;
102
- leak: LeakyBucket;
106
+ /** Requests to identify shards are made based on whether it is available to be made. */
107
+ identifyRequests: Array<(value: void | PromiseLike<void>) => void>;
103
108
  }>;
104
109
  /** The shards that are created. */
105
110
  shards: Map<number, Shard>;
@@ -119,8 +124,8 @@ export interface GatewayManager extends Required<CreateGatewayManagerOptions> {
119
124
  identify: (shardId: number) => Promise<void>;
120
125
  /** Kill a shard. Close a shards connection to Discord's gateway (if any) and remove it from the manager. */
121
126
  kill: (shardId: number) => Promise<void>;
122
- /** This function communicates with the parent manager, in order to know whether this manager is allowed to identify a new shard. */
123
- requestIdentify: () => Promise<void>;
127
+ /** This function makes sure that the bucket is allowed to make the next identify request. */
128
+ requestIdentify: (shardId: number) => Promise<void>;
124
129
  /** Calculates the number of shards based on the guild id and total shards. */
125
130
  calculateShardId: (guildId: BigString, totalShards?: number) => number;
126
131
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"manager.d.ts","sourceRoot":"","sources":["../src/manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,QAAQ,EAAE,oBAAoB,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAA;AAClI,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAA;AACpD,OAAO,EAAE,UAAU,EAAoC,MAAM,mBAAmB,CAAA;AAChF,OAAO,KAAK,MAAM,YAAY,CAAA;AAC9B,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAE7E,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,2BAA2B,GAAG,cAAc,CAyPzF;AAED,MAAM,WAAW,2BAA2B;IAC1C;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,oFAAoF;IACpF,UAAU,CAAC,EAAE,QAAQ,CAAC,oBAAoB,CAAC,CAAA;IAC3C;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,iCAAiC;IACjC,UAAU,CAAC,EAAE;QACX;;;WAGG;QACH,EAAE,EAAE,MAAM,CAAA;QAC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;;;;;;;;;;;OAsBG;IACH,cAAc,EAAE,CAAC,OAAO,EAAE,SAAS,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,mBAAmB,EAAE,SAAS,CAAC,KAAK,OAAO,CAAC,QAAQ,CAAC,aAAa,EAAE,CAAC,CAAC,CAAA;IAC1H;;;;;;;;;;;OAWG;IACH,iBAAiB,EAAE,CAAC,OAAO,EAAE,SAAS,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;CACzD;AAED,MAAM,WAAW,oBAAoB;IACnC,yCAAyC;IACzC,KAAK,EAAE,MAAM,CAAA;IACb,2DAA2D;IAC3D,OAAO,EAAE,CAAC,KAAK,EAAE,QAAQ,CAAC,aAAa,EAAE,CAAC,GAAG,WAAW,CAAC,QAAQ,CAAC,aAAa,EAAE,CAAC,CAAC,KAAK,IAAI,CAAA;IAC5F,8DAA8D;IAC9D,OAAO,EAAE,QAAQ,CAAC,aAAa,EAAE,CAAC,CAAA;CACnC"}
package/dist/manager.js CHANGED
@@ -1,4 +1,4 @@
1
- import { Collection, createLeakyBucket, delay, logger } from '@discordeno/utils';
1
+ /* eslint-disable @typescript-eslint/no-confusing-void-expression */ import { Collection, delay, logger } from '@discordeno/utils';
2
2
  import Shard from './Shard.js';
3
3
  export function createGatewayManager(options) {
4
4
  if (!options.connection) {
@@ -32,6 +32,7 @@ export function createGatewayManager(options) {
32
32
  totalWorkers: options.totalWorkers ?? 4,
33
33
  shardsPerWorker: options.shardsPerWorker ?? 25,
34
34
  spawnShardDelay: options.spawnShardDelay ?? 5300,
35
+ preferSnakeCase: false,
35
36
  shards: new Map(),
36
37
  buckets: new Map(),
37
38
  cache: {
@@ -52,13 +53,7 @@ export function createGatewayManager(options) {
52
53
  (gateway.connection.sessionStartLimit.maxConcurrency === 1 ? 16 : gateway.connection.sessionStartLimit.maxConcurrency)) * gateway.connection.sessionStartLimit.maxConcurrency;
53
54
  },
54
55
  calculateWorkerId (shardId) {
55
- // Ignore decimal numbers.
56
- let workerId = Math.floor(shardId / gateway.shardsPerWorker);
57
- // If the workerId overflows the maximal allowed workers we by default just use to last worker.
58
- if (workerId >= gateway.totalWorkers) {
59
- // The Id of the last available worker is total -1
60
- workerId = gateway.totalWorkers - 1;
61
- }
56
+ const workerId = shardId % gateway.shardsPerWorker;
62
57
  logger.debug(`[Gateway] Calculating workerId: Shard: ${shardId} -> Worker: ${workerId} -> Per Worker: ${gateway.shardsPerWorker} -> Total: ${gateway.totalWorkers}`);
63
58
  return workerId;
64
59
  },
@@ -67,12 +62,7 @@ export function createGatewayManager(options) {
67
62
  logger.debug(`[Gateway] Preparing buckets for concurrency: ${i}`);
68
63
  gateway.buckets.set(i, {
69
64
  workers: [],
70
- leak: createLeakyBucket({
71
- max: 1,
72
- refillAmount: 1,
73
- // special number which is proven to be working dont change
74
- refillInterval: gateway.spawnShardDelay
75
- })
65
+ identifyRequests: []
76
66
  });
77
67
  }
78
68
  // ORGANIZE ALL SHARDS INTO THEIR OWN BUCKETS
@@ -102,6 +92,12 @@ export function createGatewayManager(options) {
102
92
  });
103
93
  }
104
94
  }
95
+ for (const bucket of gateway.buckets.values()){
96
+ for (const worker of bucket.workers.values()){
97
+ // eslint-disable-next-line @typescript-eslint/require-array-sort-compare
98
+ worker.queue = worker.queue.sort((a, b)=>a - b);
99
+ }
100
+ }
105
101
  },
106
102
  async spawnShards () {
107
103
  // PREPARES ALL SHARDS IN SPECIFIC BUCKETS
@@ -123,7 +119,7 @@ export function createGatewayManager(options) {
123
119
  },
124
120
  async tellWorkerToIdentify (workerId, shardId, bucketId) {
125
121
  logger.debug(`[Gateway] tell worker to identify (${workerId}, ${shardId}, ${bucketId})`);
126
- return await gateway.identify(shardId);
122
+ await gateway.identify(shardId);
127
123
  },
128
124
  async identify (shardId) {
129
125
  let shard = this.shards.get(shardId);
@@ -140,11 +136,33 @@ export function createGatewayManager(options) {
140
136
  url: this.url,
141
137
  version: this.version
142
138
  },
143
- events: options.events
139
+ events: options.events,
140
+ requestIdentify: async ()=>{
141
+ await gateway.identify(shardId);
142
+ },
143
+ shardIsReady: async ()=>{
144
+ logger.debug(`[Shard] Shard #${shardId} is ready`);
145
+ await delay(gateway.spawnShardDelay);
146
+ logger.debug(`[Shard] Resolving shard identify request`);
147
+ gateway.buckets.get(shardId % gateway.connection.sessionStartLimit.maxConcurrency).identifyRequests.shift()?.();
148
+ }
144
149
  });
150
+ if (this.preferSnakeCase) {
151
+ shard.forwardToBot = async (payload)=>{
152
+ options.events.message?.(shard, payload);
153
+ };
154
+ }
145
155
  this.shards.set(shardId, shard);
146
156
  }
147
- return await shard.identify();
157
+ const bucket = gateway.buckets.get(shardId % gateway.connection.sessionStartLimit.maxConcurrency);
158
+ if (!bucket) return;
159
+ return await new Promise((resolve)=>{
160
+ // Mark that we are making an identify request so another is not made.
161
+ bucket.identifyRequests.push(resolve);
162
+ logger.debug(`[Gateway] identifying shard #(${shardId}).`);
163
+ // This will trigger identify and when READY is received it will resolve the above request.
164
+ shard?.identify();
165
+ });
148
166
  },
149
167
  async kill (shardId) {
150
168
  const shard = this.shards.get(shardId);
@@ -153,10 +171,15 @@ export function createGatewayManager(options) {
153
171
  }
154
172
  logger.debug(`[Gateway] kill shard (${shardId})`);
155
173
  this.shards.delete(shardId);
156
- return await shard.shutdown();
174
+ await shard.shutdown();
157
175
  },
158
- async requestIdentify () {
176
+ async requestIdentify (shardId) {
159
177
  logger.debug(`[Gateway] requesting identify`);
178
+ // const bucket = gateway.buckets.get(shardId % gateway.connection.sessionStartLimit.maxConcurrency)
179
+ // if (!bucket) return
180
+ // return await new Promise((resolve) => {
181
+ // bucket.identifyRequests.push(resolve)
182
+ // })
160
183
  },
161
184
  // Helpers methods below this
162
185
  calculateShardId (guildId, totalShards) {
@@ -193,7 +216,7 @@ export function createGatewayManager(options) {
193
216
  throw new Error(`Shard (id: ${shardId}) not found.`);
194
217
  }
195
218
  logger.debug(`[Gateway] editShardStatus shardId: ${shardId} -> data: ${JSON.stringify(data)}`);
196
- return await shard.editShardStatus(data);
219
+ await shard.editShardStatus(data);
197
220
  },
198
221
  async requestMembers (guildId, options) {
199
222
  const shardId = gateway.calculateShardId(guildId);
@@ -211,7 +234,7 @@ export function createGatewayManager(options) {
211
234
  throw new Error(`Shard (id: ${shardId} not found`);
212
235
  }
213
236
  logger.debug(`[Gateway] leaveVoiceChannel guildId: ${guildId} Shard ${shardId}`);
214
- return await shard.leaveVoiceChannel(guildId);
237
+ await shard.leaveVoiceChannel(guildId);
215
238
  }
216
239
  };
217
240
  return gateway;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/manager.ts"],"sourcesContent":["import type { AtLeastOne, BigString, Camelize, DiscordGetGatewayBot, DiscordMember, RequestGuildMembers } from '@discordeno/types'\nimport type { LeakyBucket } from '@discordeno/utils'\nimport { Collection, createLeakyBucket, delay, logger } from '@discordeno/utils'\nimport Shard from './Shard.js'\nimport type { ShardEvents, StatusUpdate, UpdateVoiceState } from './types.js'\n\nexport function createGatewayManager(options: CreateGatewayManagerOptions): GatewayManager {\n if (!options.connection) {\n options.connection = {\n url: 'wss://gateway.discord.gg',\n shards: 1,\n sessionStartLimit: {\n maxConcurrency: 1,\n remaining: 1000,\n total: 1000,\n resetAfter: 1000 * 60 * 60 * 24,\n },\n }\n }\n\n const gateway: GatewayManager = {\n events: options.events,\n compress: options.compress ?? false,\n intents: options.intents ?? 0,\n properties: {\n os: options.properties?.os ?? process.platform,\n browser: options.properties?.browser ?? 'Discordeno',\n device: options.properties?.device ?? 'Discordeno',\n },\n token: options.token,\n url: options.url ?? options.connection.url ?? 'wss://gateway.discord.gg',\n version: options.version ?? 10,\n connection: options.connection,\n totalShards: options.totalShards ?? options.connection.shards ?? 1,\n lastShardId: options.lastShardId ?? 0,\n firstShardId: options.firstShardId ?? 0,\n totalWorkers: options.totalWorkers ?? 4,\n shardsPerWorker: options.shardsPerWorker ?? 25,\n spawnShardDelay: options.spawnShardDelay ?? 5300,\n shards: new Map(),\n buckets: new Map(),\n cache: {\n requestMembers: {\n enabled: options.cache?.requestMembers?.enabled ?? false,\n pending: new Collection(),\n },\n },\n\n calculateTotalShards() {\n // Bots under 100k servers do not have access to total shards.\n if (gateway.totalShards < 100) {\n logger.debug(`[Gateway] Calculating total shards: ${gateway.totalShards}`)\n return gateway.totalShards\n }\n\n logger.debug(`[Gateway] Calculating total shards`, gateway.totalShards, gateway.connection.sessionStartLimit.maxConcurrency)\n // Calculate a multiple of `maxConcurrency` which can be used to connect to the gateway.\n return (\n Math.ceil(\n gateway.totalShards /\n // If `maxConcurrency` is 1 we can safely use 16.\n (gateway.connection.sessionStartLimit.maxConcurrency === 1 ? 16 : gateway.connection.sessionStartLimit.maxConcurrency),\n ) * gateway.connection.sessionStartLimit.maxConcurrency\n )\n },\n calculateWorkerId(shardId) {\n // Ignore decimal numbers.\n let workerId = Math.floor(shardId / gateway.shardsPerWorker)\n // If the workerId overflows the maximal allowed workers we by default just use to last worker.\n if (workerId >= gateway.totalWorkers) {\n // The Id of the last available worker is total -1\n workerId = gateway.totalWorkers - 1\n }\n\n logger.debug(\n `[Gateway] Calculating workerId: Shard: ${shardId} -> Worker: ${workerId} -> Per Worker: ${gateway.shardsPerWorker} -> Total: ${gateway.totalWorkers}`,\n )\n\n return workerId\n },\n prepareBuckets() {\n for (let i = 0; i < gateway.connection.sessionStartLimit.maxConcurrency; ++i) {\n logger.debug(`[Gateway] Preparing buckets for concurrency: ${i}`)\n gateway.buckets.set(i, {\n workers: [],\n leak: createLeakyBucket({\n max: 1,\n refillAmount: 1,\n // special number which is proven to be working dont change\n refillInterval: gateway.spawnShardDelay,\n }),\n })\n }\n\n // ORGANIZE ALL SHARDS INTO THEIR OWN BUCKETS\n for (let shardId = gateway.firstShardId; shardId <= gateway.lastShardId; ++shardId) {\n logger.debug(`[Gateway] Preparing buckets for shard: ${shardId}`)\n if (shardId >= gateway.totalShards) {\n throw new Error(`Shard (id: ${shardId}) is bigger or equal to the used amount of used shards which is ${gateway.totalShards}`)\n }\n\n const bucketId = shardId % gateway.connection.sessionStartLimit.maxConcurrency\n const bucket = gateway.buckets.get(bucketId)\n if (!bucket) {\n throw new Error(\n `Shard (id: ${shardId}) got assigned to an illegal bucket id: ${bucketId}, expected a bucket id between 0 and ${\n gateway.connection.sessionStartLimit.maxConcurrency - 1\n }`,\n )\n }\n\n // FIND A QUEUE IN THIS BUCKET THAT HAS SPACE\n // const worker = bucket.workers.find((w) => w.queue.length < gateway.shardsPerWorker);\n const workerId = gateway.calculateWorkerId(shardId)\n const worker = bucket.workers.find((w) => w.id === workerId)\n if (worker) {\n // IF THE QUEUE HAS SPACE JUST ADD IT TO THIS QUEUE\n worker.queue.push(shardId)\n } else {\n bucket.workers.push({ id: workerId, queue: [shardId] })\n }\n }\n },\n async spawnShards() {\n // PREPARES ALL SHARDS IN SPECIFIC BUCKETS\n gateway.prepareBuckets()\n\n // Prefer concurrency of forEach instead of forof\n await Promise.all(\n [...gateway.buckets.entries()].map(async ([bucketId, bucket]) => {\n for (const worker of bucket.workers) {\n for (const shardId of worker.queue) {\n await gateway.tellWorkerToIdentify(worker.id, shardId, bucketId)\n }\n }\n }),\n )\n },\n async shutdown(code, reason) {\n gateway.shards.forEach((shard) => shard.close(code, reason))\n\n await delay(5000)\n },\n async tellWorkerToIdentify(workerId, shardId, bucketId) {\n logger.debug(`[Gateway] tell worker to identify (${workerId}, ${shardId}, ${bucketId})`)\n return await gateway.identify(shardId)\n },\n async identify(shardId: number) {\n let shard = this.shards.get(shardId)\n logger.debug(`[Gateway] identifying ${shard ? 'existing' : 'new'} shard (${shardId})`)\n\n if (!shard) {\n shard = new Shard({\n id: shardId,\n connection: {\n compress: this.compress,\n intents: this.intents,\n properties: this.properties,\n token: this.token,\n totalShards: this.totalShards,\n url: this.url,\n version: this.version,\n },\n events: options.events,\n })\n\n this.shards.set(shardId, shard)\n }\n\n return await shard.identify()\n },\n async kill(shardId: number) {\n const shard = this.shards.get(shardId)\n if (!shard) {\n return logger.debug(`[Gateway] kill shard but not found (${shardId})`)\n }\n\n logger.debug(`[Gateway] kill shard (${shardId})`)\n this.shards.delete(shardId)\n return await shard.shutdown()\n },\n\n async requestIdentify() {\n logger.debug(`[Gateway] requesting identify`)\n },\n\n // Helpers methods below this\n\n calculateShardId(guildId, totalShards) {\n // If none is provided, use the total shards number from gateway object.\n if (!totalShards) totalShards = gateway.totalShards\n // If it is only 1 shard, it will always be shard id 0\n if (totalShards === 1) {\n logger.debug(`[Gateway] calculateShardId (1 shard)`)\n return 0\n }\n\n logger.debug(`[Gateway] calculateShardId (guildId: ${guildId}, totalShards: ${totalShards})`)\n return Number((BigInt(guildId) >> 22n) % BigInt(totalShards))\n },\n\n async joinVoiceChannel(guildId, channelId, options) {\n const shardId = gateway.calculateShardId(guildId)\n const shard = gateway.shards.get(shardId)\n if (!shard) {\n throw new Error(`Shard (id: ${shardId} not found`)\n }\n\n logger.debug(`[Gateway] joinVoiceChannel guildId: ${guildId} channelId: ${channelId}`)\n shard.joinVoiceChannel(guildId, channelId, options)\n },\n\n async editBotStatus(data) {\n logger.debug(`[Gateway] editBotStatus data: ${JSON.stringify(data)}`)\n await Promise.all(\n [...gateway.shards.values()].map(async (shard) => {\n gateway.editShardStatus(shard.id, data)\n }),\n )\n },\n\n async editShardStatus(shardId, data) {\n const shard = gateway.shards.get(shardId)\n if (!shard) {\n throw new Error(`Shard (id: ${shardId}) not found.`)\n }\n\n logger.debug(`[Gateway] editShardStatus shardId: ${shardId} -> data: ${JSON.stringify(data)}`)\n return await shard.editShardStatus(data)\n },\n\n async requestMembers(guildId, options) {\n const shardId = gateway.calculateShardId(guildId)\n const shard = gateway.shards.get(shardId)\n if (!shard) {\n throw new Error(`Shard (id: ${shardId}) not found.`)\n }\n\n logger.debug(`[Gateway] requestMembers guildId: ${guildId} -> options ${JSON.stringify(options)}`)\n return await shard.requestMembers(guildId, options)\n },\n\n async leaveVoiceChannel(guildId) {\n const shardId = gateway.calculateShardId(guildId)\n const shard = gateway.shards.get(shardId)\n if (!shard) {\n throw new Error(`Shard (id: ${shardId} not found`)\n }\n\n logger.debug(`[Gateway] leaveVoiceChannel guildId: ${guildId} Shard ${shardId}`)\n return await shard.leaveVoiceChannel(guildId)\n },\n }\n\n return gateway\n}\n\nexport interface CreateGatewayManagerOptions {\n /**\n * Id of the first Shard which should get controlled by this manager.\n * @default 0\n */\n firstShardId?: number\n /**\n * Id of the last Shard which should get controlled by this manager.\n * @default 0\n */\n lastShardId?: number\n /**\n * Delay in milliseconds to wait before spawning next shard. OPTIMAL IS ABOVE 5100. YOU DON'T WANT TO HIT THE RATE LIMIT!!!\n * @default 5300\n */\n spawnShardDelay?: number\n /**\n * Total amount of shards your bot uses. Useful for zero-downtime updates or resharding.\n * @default 1\n */\n totalShards?: number\n /**\n * The amount of shards to load per worker.\n * @default 25\n */\n shardsPerWorker?: number\n /**\n * The total amount of workers to use for your bot.\n * @default 4\n */\n totalWorkers?: number\n /** Important data which is used by the manager to connect shards to the gateway. */\n connection?: Camelize<DiscordGetGatewayBot>\n /** Whether incoming payloads are compressed using zlib.\n *\n * @default false\n */\n compress?: boolean\n /** The calculated intent value of the events which the shard should receive.\n *\n * @default 0\n */\n intents?: number\n /** Identify properties to use */\n properties?: {\n /** Operating system the shard runs on.\n *\n * @default \"darwin\" | \"linux\" | \"windows\"\n */\n os: string\n /** The \"browser\" where this shard is running on.\n *\n * @default \"Discordeno\"\n */\n browser: string\n /** The device on which the shard is running.\n *\n * @default \"Discordeno\"\n */\n device: string\n }\n /** Bot token which is used to connect to Discord */\n token: string\n /** The URL of the gateway which should be connected to.\n *\n * @default \"wss://gateway.discord.gg\"\n */\n url?: string\n /** The gateway version which should be used.\n *\n * @default 10\n */\n version?: number\n /** The events handlers */\n events: ShardEvents\n /** This managers cache related settings. */\n cache?: {\n requestMembers?: {\n /**\n * Whether or not request member requests should be cached.\n * @default false\n */\n enabled?: boolean\n /** The pending requests. */\n pending: Collection<string, RequestMemberRequest>\n }\n }\n}\n\nexport interface GatewayManager extends Required<CreateGatewayManagerOptions> {\n /** The max concurrency buckets. Those will be created when the `spawnShards` (which calls `prepareBuckets` under the hood) function gets called. */\n buckets: Map<\n number,\n {\n workers: Array<{ id: number; queue: number[] }>\n leak: LeakyBucket\n }\n >\n /** The shards that are created. */\n shards: Map<number, Shard>\n /** Determine max number of shards to use based upon the max concurrency. */\n calculateTotalShards: () => number\n /** Determine the id of the worker which is handling a shard. */\n calculateWorkerId: (shardId: number) => number\n /** Prepares all the buckets that are available for identifying the shards. */\n prepareBuckets: () => void\n /** Start identifying all the shards. */\n spawnShards: () => Promise<void>\n /** Shutdown all shards. */\n shutdown: (code: number, reason: string) => Promise<void>\n /** Allows users to hook in and change to communicate to different workers across different servers or anything they like. For example using redis pubsub to talk to other servers. */\n tellWorkerToIdentify: (workerId: number, shardId: number, bucketId: number) => Promise<void>\n /** Tell the manager to identify a Shard. If this Shard is not already managed this will also add the Shard to the manager. */\n identify: (shardId: number) => Promise<void>\n /** Kill a shard. Close a shards connection to Discord's gateway (if any) and remove it from the manager. */\n kill: (shardId: number) => Promise<void>\n /** This function communicates with the parent manager, in order to know whether this manager is allowed to identify a new shard. */\n requestIdentify: () => Promise<void>\n /** Calculates the number of shards based on the guild id and total shards. */\n calculateShardId: (guildId: BigString, totalShards?: number) => number\n /**\n * Connects the bot user to a voice or stage channel.\n *\n * This function sends the _Update Voice State_ gateway command over the gateway behind the scenes.\n *\n * @param guildId - The ID of the guild the voice channel to leave is in.\n * @param channelId - The ID of the channel you want to join.\n *\n * @remarks\n * Requires the `CONNECT` permission.\n *\n * Fires a _Voice State Update_ gateway event.\n *\n * @see {@link https://discord.com/developers/docs/topics/gateway#update-voice-state}\n */\n joinVoiceChannel: (guildId: BigString, channelId: BigString, options?: AtLeastOne<Omit<UpdateVoiceState, 'guildId' | 'channelId'>>) => Promise<void>\n /**\n * Edits the bot status in all shards that this gateway manages.\n *\n * @param data The status data to set the bots status to.\n * @returns Promise<void>\n */\n editBotStatus: (data: StatusUpdate) => Promise<void>\n /**\n * Edits the bot's status on one shard.\n *\n * @param shardId The shard id to edit the status for.\n * @param data The status data to set the bots status to.\n * @returns Promise<void>\n */\n editShardStatus: (shardId: number, data: StatusUpdate) => Promise<void>\n /**\n * Fetches the list of members for a guild over the gateway.\n *\n * @param guildId - The ID of the guild to get the list of members for.\n * @param options - The parameters for the fetching of the members.\n *\n * @remarks\n * If requesting the entire member list:\n * - Requires the `GUILD_MEMBERS` intent.\n *\n * If requesting presences ({@link RequestGuildMembers.presences | presences} set to `true`):\n * - Requires the `GUILD_PRESENCES` intent.\n *\n * If requesting a prefix ({@link RequestGuildMembers.query | query} non-`undefined`):\n * - Returns a maximum of 100 members.\n *\n * If requesting a users by ID ({@link RequestGuildMembers.userIds | userIds} non-`undefined`):\n * - Returns a maximum of 100 members.\n *\n * Fires a _Guild Members Chunk_ gateway event for every 1000 members fetched.\n *\n * @see {@link https://discord.com/developers/docs/topics/gateway#request-guild-members}\n */\n requestMembers: (guildId: BigString, options?: Omit<RequestGuildMembers, 'guildId'>) => Promise<Camelize<DiscordMember[]>>\n /**\n * Leaves the voice channel the bot user is currently in.\n *\n * This function sends the _Update Voice State_ gateway command over the gateway behind the scenes.\n *\n * @param guildId - The ID of the guild the voice channel to leave is in.\n *\n * @remarks\n * Fires a _Voice State Update_ gateway event.\n *\n * @see {@link https://discord.com/developers/docs/topics/gateway#update-voice-state}\n */\n leaveVoiceChannel: (guildId: BigString) => Promise<void>\n}\n\nexport interface RequestMemberRequest {\n /** The unique nonce for this request. */\n nonce: string\n /** The resolver handler to run when all members arrive. */\n resolve: (value: Camelize<DiscordMember[]> | PromiseLike<Camelize<DiscordMember[]>>) => void\n /** The members that have already arrived for this request. */\n members: Camelize<DiscordMember[]>\n}\n"],"names":["Collection","createLeakyBucket","delay","logger","Shard","createGatewayManager","options","connection","url","shards","sessionStartLimit","maxConcurrency","remaining","total","resetAfter","gateway","events","compress","intents","properties","os","process","platform","browser","device","token","version","totalShards","lastShardId","firstShardId","totalWorkers","shardsPerWorker","spawnShardDelay","Map","buckets","cache","requestMembers","enabled","pending","calculateTotalShards","debug","Math","ceil","calculateWorkerId","shardId","workerId","floor","prepareBuckets","i","set","workers","leak","max","refillAmount","refillInterval","Error","bucketId","bucket","get","worker","find","w","id","queue","push","spawnShards","Promise","all","entries","map","tellWorkerToIdentify","shutdown","code","reason","forEach","shard","close","identify","kill","delete","requestIdentify","calculateShardId","guildId","Number","BigInt","joinVoiceChannel","channelId","editBotStatus","data","JSON","stringify","values","editShardStatus","leaveVoiceChannel"],"mappings":"AAEA,SAASA,UAAU,EAAEC,iBAAiB,EAAEC,KAAK,EAAEC,MAAM,QAAQ,oBAAmB;AAChF,OAAOC,WAAW,aAAY;AAG9B,OAAO,SAASC,qBAAqBC,OAAoC,EAAkB;IACzF,IAAI,CAACA,QAAQC,UAAU,EAAE;QACvBD,QAAQC,UAAU,GAAG;YACnBC,KAAK;YACLC,QAAQ;YACRC,mBAAmB;gBACjBC,gBAAgB;gBAChBC,WAAW;gBACXC,OAAO;gBACPC,YAAY,OAAO,KAAK,KAAK;YAC/B;QACF;IACF,CAAC;IAED,MAAMC,UAA0B;QAC9BC,QAAQV,QAAQU,MAAM;QACtBC,UAAUX,QAAQW,QAAQ,IAAI,KAAK;QACnCC,SAASZ,QAAQY,OAAO,IAAI;QAC5BC,YAAY;YACVC,IAAId,QAAQa,UAAU,EAAEC,MAAMC,QAAQC,QAAQ;YAC9CC,SAASjB,QAAQa,UAAU,EAAEI,WAAW;YACxCC,QAAQlB,QAAQa,UAAU,EAAEK,UAAU;QACxC;QACAC,OAAOnB,QAAQmB,KAAK;QACpBjB,KAAKF,QAAQE,GAAG,IAAIF,QAAQC,UAAU,CAACC,GAAG,IAAI;QAC9CkB,SAASpB,QAAQoB,OAAO,IAAI;QAC5BnB,YAAYD,QAAQC,UAAU;QAC9BoB,aAAarB,QAAQqB,WAAW,IAAIrB,QAAQC,UAAU,CAACE,MAAM,IAAI;QACjEmB,aAAatB,QAAQsB,WAAW,IAAI;QACpCC,cAAcvB,QAAQu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jC,IAAI,CAAC+B,OAAO;gBACV,MAAM,IAAIpB,MAAM,CAAC,WAAW,EAAEX,QAAQ,YAAY,CAAC,EAAC;YACtD,CAAC;YAEDzC,OAAOqC,KAAK,CAAC,CAAC,kCAAkC,EAAE0C,QAAQ,YAAY,EAAEO,KAAKC,SAAS,CAACpF,SAAS,CAAC;YACjG,OAAO,MAAMqE,MAAMvC,cAAc,CAAC8C,SAAS5E;QAC7C;QAEA,MAAMuF,mBAAkBX,OAAO,EAAE;YAC/B,MAAMtC,UAAU7B,QAAQkE,gBAAgB,CAACC;YACzC,MAAMP,QAAQ5D,QAAQN,MAAM,CAACiD,GAAG,CAACd;YACjC,IAAI,CAAC+B,OAAO;gBACV,MAAM,IAAIpB,MAAM,CAAC,WAAW,EAAEX,QAAQ,UAAU,CAAC,EAAC;YACpD,CAAC;YAEDzC,OAAOqC,KAAK,CAAC,CAAC,qCAAqC,EAAE0C,QAAQ,OAAO,EAAEtC,QAAQ,CAAC;YAC/E,OAAO,MAAM+B,MAAMkB,iBAAiB,CAACX;QACvC;IACF;IAEA,OAAOnE;AACT,CAAC"}
1
+ {"version":3,"sources":["../src/manager.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-confusing-void-expression */\nimport type { AtLeastOne, BigString, Camelize, DiscordGetGatewayBot, DiscordMember, RequestGuildMembers } from '@discordeno/types'\nimport { Collection, delay, logger } from '@discordeno/utils'\nimport Shard from './Shard.js'\nimport type { ShardEvents, StatusUpdate, UpdateVoiceState } from './types.js'\n\nexport function createGatewayManager(options: CreateGatewayManagerOptions): GatewayManager {\n if (!options.connection) {\n options.connection = {\n url: 'wss://gateway.discord.gg',\n shards: 1,\n sessionStartLimit: {\n maxConcurrency: 1,\n remaining: 1000,\n total: 1000,\n resetAfter: 1000 * 60 * 60 * 24,\n },\n }\n }\n\n const gateway: GatewayManager = {\n events: options.events,\n compress: options.compress ?? false,\n intents: options.intents ?? 0,\n properties: {\n os: options.properties?.os ?? process.platform,\n browser: options.properties?.browser ?? 'Discordeno',\n device: options.properties?.device ?? 'Discordeno',\n },\n token: options.token,\n url: options.url ?? options.connection.url ?? 'wss://gateway.discord.gg',\n version: options.version ?? 10,\n connection: options.connection,\n totalShards: options.totalShards ?? options.connection.shards ?? 1,\n lastShardId: options.lastShardId ?? 0,\n firstShardId: options.firstShardId ?? 0,\n totalWorkers: options.totalWorkers ?? 4,\n shardsPerWorker: options.shardsPerWorker ?? 25,\n spawnShardDelay: options.spawnShardDelay ?? 5300,\n preferSnakeCase: false,\n shards: new Map(),\n buckets: new Map(),\n cache: {\n requestMembers: {\n enabled: options.cache?.requestMembers?.enabled ?? false,\n pending: new Collection(),\n },\n },\n\n calculateTotalShards() {\n // Bots under 100k servers do not have access to total shards.\n if (gateway.totalShards < 100) {\n logger.debug(`[Gateway] Calculating total shards: ${gateway.totalShards}`)\n return gateway.totalShards\n }\n\n logger.debug(`[Gateway] Calculating total shards`, gateway.totalShards, gateway.connection.sessionStartLimit.maxConcurrency)\n // Calculate a multiple of `maxConcurrency` which can be used to connect to the gateway.\n return (\n Math.ceil(\n gateway.totalShards /\n // If `maxConcurrency` is 1 we can safely use 16.\n (gateway.connection.sessionStartLimit.maxConcurrency === 1 ? 16 : gateway.connection.sessionStartLimit.maxConcurrency),\n ) * gateway.connection.sessionStartLimit.maxConcurrency\n )\n },\n calculateWorkerId(shardId) {\n const workerId = shardId % gateway.shardsPerWorker\n logger.debug(\n `[Gateway] Calculating workerId: Shard: ${shardId} -> Worker: ${workerId} -> Per Worker: ${gateway.shardsPerWorker} -> Total: ${gateway.totalWorkers}`,\n )\n return workerId\n },\n prepareBuckets() {\n for (let i = 0; i < gateway.connection.sessionStartLimit.maxConcurrency; ++i) {\n logger.debug(`[Gateway] Preparing buckets for concurrency: ${i}`)\n gateway.buckets.set(i, {\n workers: [],\n identifyRequests: [],\n })\n }\n\n // ORGANIZE ALL SHARDS INTO THEIR OWN BUCKETS\n for (let shardId = gateway.firstShardId; shardId <= gateway.lastShardId; ++shardId) {\n logger.debug(`[Gateway] Preparing buckets for shard: ${shardId}`)\n if (shardId >= gateway.totalShards) {\n throw new Error(`Shard (id: ${shardId}) is bigger or equal to the used amount of used shards which is ${gateway.totalShards}`)\n }\n\n const bucketId = shardId % gateway.connection.sessionStartLimit.maxConcurrency\n const bucket = gateway.buckets.get(bucketId)\n if (!bucket) {\n throw new Error(\n `Shard (id: ${shardId}) got assigned to an illegal bucket id: ${bucketId}, expected a bucket id between 0 and ${\n gateway.connection.sessionStartLimit.maxConcurrency - 1\n }`,\n )\n }\n\n // FIND A QUEUE IN THIS BUCKET THAT HAS SPACE\n // const worker = bucket.workers.find((w) => w.queue.length < gateway.shardsPerWorker);\n const workerId = gateway.calculateWorkerId(shardId)\n const worker = bucket.workers.find((w) => w.id === workerId)\n if (worker) {\n // IF THE QUEUE HAS SPACE JUST ADD IT TO THIS QUEUE\n worker.queue.push(shardId)\n } else {\n bucket.workers.push({ id: workerId, queue: [shardId] })\n }\n }\n\n for (const bucket of gateway.buckets.values()) {\n for (const worker of bucket.workers.values()) {\n // eslint-disable-next-line @typescript-eslint/require-array-sort-compare\n worker.queue = worker.queue.sort((a, b) => a - b)\n }\n }\n },\n async spawnShards() {\n // PREPARES ALL SHARDS IN SPECIFIC BUCKETS\n gateway.prepareBuckets()\n\n // Prefer concurrency of forEach instead of forof\n await Promise.all(\n [...gateway.buckets.entries()].map(async ([bucketId, bucket]) => {\n for (const worker of bucket.workers) {\n for (const shardId of worker.queue) {\n await gateway.tellWorkerToIdentify(worker.id, shardId, bucketId)\n }\n }\n }),\n )\n },\n async shutdown(code, reason) {\n gateway.shards.forEach((shard) => shard.close(code, reason))\n\n await delay(5000)\n },\n async tellWorkerToIdentify(workerId, shardId, bucketId) {\n logger.debug(`[Gateway] tell worker to identify (${workerId}, ${shardId}, ${bucketId})`)\n await gateway.identify(shardId)\n },\n async identify(shardId: number) {\n let shard = this.shards.get(shardId)\n logger.debug(`[Gateway] identifying ${shard ? 'existing' : 'new'} shard (${shardId})`)\n\n if (!shard) {\n shard = new Shard({\n id: shardId,\n connection: {\n compress: this.compress,\n intents: this.intents,\n properties: this.properties,\n token: this.token,\n totalShards: this.totalShards,\n url: this.url,\n version: this.version,\n },\n events: options.events,\n requestIdentify: async () => {\n await gateway.identify(shardId)\n },\n shardIsReady: async () => {\n logger.debug(`[Shard] Shard #${shardId} is ready`)\n await delay(gateway.spawnShardDelay)\n logger.debug(`[Shard] Resolving shard identify request`)\n gateway.buckets.get(shardId % gateway.connection.sessionStartLimit.maxConcurrency)!.identifyRequests.shift()?.()\n },\n })\n\n if (this.preferSnakeCase) {\n shard.forwardToBot = async (payload) => {\n options.events.message?.(shard!, payload)\n }\n }\n\n this.shards.set(shardId, shard)\n }\n\n const bucket = gateway.buckets.get(shardId % gateway.connection.sessionStartLimit.maxConcurrency)\n if (!bucket) return\n\n return await new Promise((resolve) => {\n // Mark that we are making an identify request so another is not made.\n bucket.identifyRequests.push(resolve)\n logger.debug(`[Gateway] identifying shard #(${shardId}).`)\n // This will trigger identify and when READY is received it will resolve the above request.\n shard?.identify()\n })\n },\n async kill(shardId: number) {\n const shard = this.shards.get(shardId)\n if (!shard) {\n return logger.debug(`[Gateway] kill shard but not found (${shardId})`)\n }\n\n logger.debug(`[Gateway] kill shard (${shardId})`)\n this.shards.delete(shardId)\n await shard.shutdown()\n },\n\n async requestIdentify(shardId: number) {\n logger.debug(`[Gateway] requesting identify`)\n // const bucket = gateway.buckets.get(shardId % gateway.connection.sessionStartLimit.maxConcurrency)\n // if (!bucket) return\n\n // return await new Promise((resolve) => {\n // bucket.identifyRequests.push(resolve)\n // })\n },\n\n // Helpers methods below this\n\n calculateShardId(guildId, totalShards) {\n // If none is provided, use the total shards number from gateway object.\n if (!totalShards) totalShards = gateway.totalShards\n // If it is only 1 shard, it will always be shard id 0\n if (totalShards === 1) {\n logger.debug(`[Gateway] calculateShardId (1 shard)`)\n return 0\n }\n\n logger.debug(`[Gateway] calculateShardId (guildId: ${guildId}, totalShards: ${totalShards})`)\n return Number((BigInt(guildId) >> 22n) % BigInt(totalShards))\n },\n\n async joinVoiceChannel(guildId, channelId, options) {\n const shardId = gateway.calculateShardId(guildId)\n const shard = gateway.shards.get(shardId)\n if (!shard) {\n throw new Error(`Shard (id: ${shardId} not found`)\n }\n\n logger.debug(`[Gateway] joinVoiceChannel guildId: ${guildId} channelId: ${channelId}`)\n shard.joinVoiceChannel(guildId, channelId, options)\n },\n\n async editBotStatus(data) {\n logger.debug(`[Gateway] editBotStatus data: ${JSON.stringify(data)}`)\n await Promise.all(\n [...gateway.shards.values()].map(async (shard) => {\n gateway.editShardStatus(shard.id, data)\n }),\n )\n },\n\n async editShardStatus(shardId, data) {\n const shard = gateway.shards.get(shardId)\n if (!shard) {\n throw new Error(`Shard (id: ${shardId}) not found.`)\n }\n\n logger.debug(`[Gateway] editShardStatus shardId: ${shardId} -> data: ${JSON.stringify(data)}`)\n await shard.editShardStatus(data)\n },\n\n async requestMembers(guildId, options) {\n const shardId = gateway.calculateShardId(guildId)\n const shard = gateway.shards.get(shardId)\n if (!shard) {\n throw new Error(`Shard (id: ${shardId}) not found.`)\n }\n\n logger.debug(`[Gateway] requestMembers guildId: ${guildId} -> options ${JSON.stringify(options)}`)\n return await shard.requestMembers(guildId, options)\n },\n\n async leaveVoiceChannel(guildId) {\n const shardId = gateway.calculateShardId(guildId)\n const shard = gateway.shards.get(shardId)\n if (!shard) {\n throw new Error(`Shard (id: ${shardId} not found`)\n }\n\n logger.debug(`[Gateway] leaveVoiceChannel guildId: ${guildId} Shard ${shardId}`)\n await shard.leaveVoiceChannel(guildId)\n },\n }\n\n return gateway\n}\n\nexport interface CreateGatewayManagerOptions {\n /**\n * Id of the first Shard which should get controlled by this manager.\n * @default 0\n */\n firstShardId?: number\n /**\n * Id of the last Shard which should get controlled by this manager.\n * @default 0\n */\n lastShardId?: number\n /**\n * Delay in milliseconds to wait before spawning next shard. OPTIMAL IS ABOVE 5100. YOU DON'T WANT TO HIT THE RATE LIMIT!!!\n * @default 5300\n */\n spawnShardDelay?: number\n /**\n * Whether to send the discord packets in snake case form.\n * @default false\n */\n preferSnakeCase?: boolean\n /**\n * Total amount of shards your bot uses. Useful for zero-downtime updates or resharding.\n * @default 1\n */\n totalShards?: number\n /**\n * The amount of shards to load per worker.\n * @default 25\n */\n shardsPerWorker?: number\n /**\n * The total amount of workers to use for your bot.\n * @default 4\n */\n totalWorkers?: number\n /** Important data which is used by the manager to connect shards to the gateway. */\n connection?: Camelize<DiscordGetGatewayBot>\n /** Whether incoming payloads are compressed using zlib.\n *\n * @default false\n */\n compress?: boolean\n /** The calculated intent value of the events which the shard should receive.\n *\n * @default 0\n */\n intents?: number\n /** Identify properties to use */\n properties?: {\n /** Operating system the shard runs on.\n *\n * @default \"darwin\" | \"linux\" | \"windows\"\n */\n os: string\n /** The \"browser\" where this shard is running on.\n *\n * @default \"Discordeno\"\n */\n browser: string\n /** The device on which the shard is running.\n *\n * @default \"Discordeno\"\n */\n device: string\n }\n /** Bot token which is used to connect to Discord */\n token: string\n /** The URL of the gateway which should be connected to.\n *\n * @default \"wss://gateway.discord.gg\"\n */\n url?: string\n /** The gateway version which should be used.\n *\n * @default 10\n */\n version?: number\n /** The events handlers */\n events: ShardEvents\n /** This managers cache related settings. */\n cache?: {\n requestMembers?: {\n /**\n * Whether or not request member requests should be cached.\n * @default false\n */\n enabled?: boolean\n /** The pending requests. */\n pending: Collection<string, RequestMemberRequest>\n }\n }\n}\n\nexport interface GatewayManager extends Required<CreateGatewayManagerOptions> {\n /** The max concurrency buckets. Those will be created when the `spawnShards` (which calls `prepareBuckets` under the hood) function gets called. */\n buckets: Map<\n number,\n {\n workers: Array<{ id: number; queue: number[] }>\n /** Requests to identify shards are made based on whether it is available to be made. */\n identifyRequests: Array<(value: void | PromiseLike<void>) => void>\n }\n >\n /** The shards that are created. */\n shards: Map<number, Shard>\n /** Determine max number of shards to use based upon the max concurrency. */\n calculateTotalShards: () => number\n /** Determine the id of the worker which is handling a shard. */\n calculateWorkerId: (shardId: number) => number\n /** Prepares all the buckets that are available for identifying the shards. */\n prepareBuckets: () => void\n /** Start identifying all the shards. */\n spawnShards: () => Promise<void>\n /** Shutdown all shards. */\n shutdown: (code: number, reason: string) => Promise<void>\n /** Allows users to hook in and change to communicate to different workers across different servers or anything they like. For example using redis pubsub to talk to other servers. */\n tellWorkerToIdentify: (workerId: number, shardId: number, bucketId: number) => Promise<void>\n /** Tell the manager to identify a Shard. If this Shard is not already managed this will also add the Shard to the manager. */\n identify: (shardId: number) => Promise<void>\n /** Kill a shard. Close a shards connection to Discord's gateway (if any) and remove it from the manager. */\n kill: (shardId: number) => Promise<void>\n /** This function makes sure that the bucket is allowed to make the next identify request. */\n requestIdentify: (shardId: number) => Promise<void>\n /** Calculates the number of shards based on the guild id and total shards. */\n calculateShardId: (guildId: BigString, totalShards?: number) => number\n /**\n * Connects the bot user to a voice or stage channel.\n *\n * This function sends the _Update Voice State_ gateway command over the gateway behind the scenes.\n *\n * @param guildId - The ID of the guild the voice channel to leave is in.\n * @param channelId - The ID of the channel you want to join.\n *\n * @remarks\n * Requires the `CONNECT` permission.\n *\n * Fires a _Voice State Update_ gateway event.\n *\n * @see {@link https://discord.com/developers/docs/topics/gateway#update-voice-state}\n */\n joinVoiceChannel: (guildId: BigString, channelId: BigString, options?: AtLeastOne<Omit<UpdateVoiceState, 'guildId' | 'channelId'>>) => Promise<void>\n /**\n * Edits the bot status in all shards that this gateway manages.\n *\n * @param data The status data to set the bots status to.\n * @returns Promise<void>\n */\n editBotStatus: (data: StatusUpdate) => Promise<void>\n /**\n * Edits the bot's status on one shard.\n *\n * @param shardId The shard id to edit the status for.\n * @param data The status data to set the bots status to.\n * @returns Promise<void>\n */\n editShardStatus: (shardId: number, data: StatusUpdate) => Promise<void>\n /**\n * Fetches the list of members for a guild over the gateway.\n *\n * @param guildId - The ID of the guild to get the list of members for.\n * @param options - The parameters for the fetching of the members.\n *\n * @remarks\n * If requesting the entire member list:\n * - Requires the `GUILD_MEMBERS` intent.\n *\n * If requesting presences ({@link RequestGuildMembers.presences | presences} set to `true`):\n * - Requires the `GUILD_PRESENCES` intent.\n *\n * If requesting a prefix ({@link RequestGuildMembers.query | query} non-`undefined`):\n * - Returns a maximum of 100 members.\n *\n * If requesting a users by ID ({@link RequestGuildMembers.userIds | userIds} non-`undefined`):\n * - Returns a maximum of 100 members.\n *\n * Fires a _Guild Members Chunk_ gateway event for every 1000 members fetched.\n *\n * @see {@link https://discord.com/developers/docs/topics/gateway#request-guild-members}\n */\n requestMembers: (guildId: BigString, options?: Omit<RequestGuildMembers, 'guildId'>) => Promise<Camelize<DiscordMember[]>>\n /**\n * Leaves the voice channel the bot user is currently in.\n *\n * This function sends the _Update Voice State_ gateway command over the gateway behind the scenes.\n *\n * @param guildId - The ID of the guild the voice channel to leave is in.\n *\n * @remarks\n * Fires a _Voice State Update_ gateway event.\n *\n * @see {@link https://discord.com/developers/docs/topics/gateway#update-voice-state}\n */\n leaveVoiceChannel: (guildId: BigString) => Promise<void>\n}\n\nexport interface RequestMemberRequest {\n /** The unique nonce for this request. */\n nonce: string\n /** The resolver handler to run when all members arrive. */\n resolve: (value: Camelize<DiscordMember[]> | PromiseLike<Camelize<DiscordMember[]>>) => void\n /** The members that have already arrived for this request. */\n members: Camelize<DiscordMember[]>\n}\n"],"names":["Collection","delay","logger","Shard","createGatewayManager","options","connection","url","shards","sessionStartLimit","maxConcurrency","remaining","total","resetAfter","gateway","events","compress","intents","properties","os","process","platform","browser","device","token","version","totalShards","lastShardId","firstShardId","totalWorkers","shardsPerWorker","spawnShardDelay","preferSnakeCase","Map","buckets","cache","requestMembers","enabled","pending","calculateTotalShards","debug","Math","ceil","calculateWorkerId","shardId","workerId","prepareBuckets","i","set","workers","identifyRequests","Error","bucketId","bucket","get","worker","find","w","id","queue","push","values","sort","a","b","spawnShards","Promise","all","entries","map","tellWorkerToIdentify","shutdown","code","reason","forEach","shard","close","identify","requestIdentify","shardIsReady","shift","forwardToBot","payload","message","resolve","kill","delete","calculateShardId","guildId","Number","BigInt","joinVoiceChannel","channelId","editBotStatus","data","JSON","stringify","editShardStatus","leaveVoiceChannel"],"mappings":"AAAA,kEAAkE,GAElE,SAASA,UAAU,EAAEC,KAAK,EAAEC,MAAM,QAAQ,oBAAmB;AAC7D,OAAOC,WAAW,aAAY;AAG9B,OAAO,SAASC,qBAAqBC,OAAoC,EAAkB;IACzF,IAAI,CAACA,QAAQC,UAAU,EAAE;QACvBD,QAAQC,UAAU,GAAG;YACnBC,KAAK;YACLC,QAAQ;YACRC,mBAAmB;gBACjBC,gBAAgB;gBAChBC,WAAW;gBACXC,OAAO;gBACPC,YAAY,OAAO,KAAK,KAAK;YAC/B;QACF;IACF,CAAC;IAED,MAAMC,UAA0B;QAC9BC,QAAQV,QAAQU,MAAM;QACtBC,UAAUX,QAAQW,QAAQ,IAAI,KAAK;QACnCC,SAASZ,QAAQY,OAAO,IAAI;QAC5BC,YAAY;YACVC,IAAId,QAAQa,UAAU,EAAEC,MAAMC,QAAQC,QAAQ;YAC9CC,SAASjB,QAAQa,UAAU,EAAEI,WAAW;YACxCC,QAAQlB,QAAQa,UAAU,EAAEK,UAAU;QACxC;QACAC,OAAOnB,QAAQmB,KAAK;QACpBjB,KAAKF,QAAQE,GAAG,IAAIF,QAAQC,UAAU,CAACC,GAAG,IAAI;QAC9CkB,SAASpB,QAAQoB,OAAO,IAAI;QAC5BnB,YAAYD,QAAQC,UAAU;QAC9BoB,aAAarB,QAAQqB,WAAW,IAAIrB,QAAQC,UAAU,CAACE,MAAM,IAAI;QACjEmB,aAAatB,QAAQsB,WAAW,IAAI;QACpCC,cAAcvB,QAAQuB,YAAY,IAAI;QACtCC,cAAcxB,QAAQwB,YAAY,IAAI;QACtCC,iBAAiBzB,QAAQyB,eAAe,IAAI;QAC5CC,iBAAiB1B,QAAQ0B,eAAe,IAAI;QAC5CC,iBAAiB,KAAK;QACtBxB,QAAQ,IAAIyB;QACZC,SAAS,IAAID;QACbE,OAAO;YACLC,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;YACpD,CAAC;YAED1C,OAAOsC,KAAK,CAAC,CAAC,qCAAqC,EAAEgD,QAAQ,OAAO,EAAE5C,QAAQ,CAAC;YAC/E,MAAM+B,MAAMuB,iBAAiB,CAACV;QAChC;IACF;IAEA,OAAO1E;AACT,CAAC"}
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { ActivityTypes, Camelize, DiscordActivity, DiscordGatewayPayload, GatewayOpcodes, PresenceStatus } from '@discordeno/types'\nimport type Shard from './Shard.js'\n\nexport enum ShardState {\n /** Shard is fully connected to the gateway and receiving events from Discord. */\n Connected = 0,\n /** Shard started to connect to the gateway. This is only used if the shard is not currently trying to identify or resume. */\n Connecting = 1,\n /** Shard got disconnected and reconnection actions have been started. */\n Disconnected = 2,\n /** The shard is connected to the gateway but only heartbeating. At this state the shard has not been identified with discord. */\n Unidentified = 3,\n /** Shard is trying to identify with the gateway to create a new session. */\n Identifying = 4,\n /** Shard is trying to resume a session with the gateway. */\n Resuming = 5,\n /** Shard got shut down studied or due to a not (self) fixable error and may not attempt to reconnect on its own. */\n Offline = 6,\n}\n\nexport interface ShardGatewayConfig {\n /** Whether incoming payloads are compressed using zlib.\n *\n * @default false\n */\n compress: boolean\n /** The calculated intent value of the events which the shard should receive.\n *\n * @default 0\n */\n intents: number\n /** Identify properties to use */\n properties: {\n /** Operating system the shard runs on.\n *\n * @default \"darwin\" | \"linux\" | \"windows\"\n */\n os: string\n /** The \"browser\" where this shard is running on.\n *\n * @default \"Discordeno\"\n */\n browser: string\n /** The device on which the shard is running.\n *\n * @default \"Discordeno\"\n */\n device: string\n }\n /** Bot token which is used to connect to Discord */\n token: string\n /** The URL of the gateway which should be connected to.\n *\n * @default \"wss://gateway.discord.gg\"\n */\n url: string\n /** The gateway version which should be used.\n *\n * @default 10\n */\n version: number\n /**\n * The total number of shards to connect to across the entire bot.\n * @default 1\n */\n totalShards: number\n}\n\nexport interface ShardHeart {\n /** Whether or not the heartbeat was acknowledged by Discord in time. */\n acknowledged: boolean\n /** Interval between heartbeats requested by Discord. */\n interval: number\n /** Id of the interval, which is used for sending the heartbeats. */\n intervalId?: NodeJS.Timer\n /** Unix (in milliseconds) timestamp when the last heartbeat ACK was received from Discord. */\n lastAck?: number\n /** Unix timestamp (in milliseconds) when the last heartbeat was sent. */\n lastBeat?: number\n /** Round trip time (in milliseconds) from Shard to Discord and back.\n * Calculated using the heartbeat system.\n * Note: this value is undefined until the first heartbeat to Discord has happened.\n */\n rtt?: number\n /** Id of the timeout which is used for sending the first heartbeat to Discord since it's \"special\". */\n timeoutId?: NodeJS.Timeout\n}\n\nexport interface ShardEvents {\n /** A heartbeat has been send. */\n heartbeat?: (shard: Shard) => unknown\n /** A heartbeat ACK was received. */\n heartbeatAck?: (shard: Shard) => unknown\n /** Shard has received a Hello payload. */\n hello?: (shard: Shard) => unknown\n /** The Shards session has been invalidated. */\n invalidSession?: (shard: Shard, resumable: boolean) => unknown\n /** The shard has started a resume action. */\n resuming?: (shard: Shard) => unknown\n /** The shard has successfully resumed an old session. */\n resumed?: (shard: Shard) => unknown\n /** Discord has requested the Shard to reconnect. */\n requestedReconnect?: (shard: Shard) => unknown\n /** The shard started to connect to Discord's gateway. */\n connecting?: (shard: Shard) => unknown\n /** The shard is connected with Discord's gateway. */\n connected?: (shard: Shard) => unknown\n /** The shard has been disconnected from Discord's gateway. */\n disconnected?: (shard: Shard) => unknown\n /** The shard has started to identify itself to Discord. */\n identifying?: (shard: Shard) => unknown\n /** The shard has successfully been identified itself with Discord. */\n identified?: (shard: Shard) => unknown\n /** The shard has received a message from Discord. */\n message?: (shard: Shard, payload: Camelize<DiscordGatewayPayload>) => unknown\n}\n\nexport enum ShardSocketCloseCodes {\n /** A regular Shard shutdown. */\n Shutdown = 3000,\n /** A resume has been requested and therefore the old connection needs to be closed. */\n ResumeClosingOldConnection = 3024,\n /** Did not receive a heartbeat ACK in time.\n * Closing the shard and creating a new session.\n */\n ZombiedConnection = 3010,\n /** Discordeno's gateway tests hae been finished, therefore the Shard can be turned off. */\n TestingFinished = 3064,\n /** Special close code reserved for Discordeno's zero-downtime resharding system. */\n Resharded = 3065,\n /** Shard is re-identifying therefore the old connection needs to be closed. */\n ReIdentifying = 3066,\n}\n\nexport interface ShardSocketRequest {\n /** The OP-Code for the payload to send. */\n op: GatewayOpcodes\n /** Payload data. */\n d: unknown\n}\n\n/** https://discord.com/developers/docs/topics/gateway-events#update-presence */\nexport interface BotStatusUpdate {\n // /** Unix time (in milliseconds) of when the client went idle, or null if the client is not idle */\n since: number | null\n /** The user's activities */\n activities: BotActivity[]\n /** The user's new status */\n status: keyof typeof PresenceStatus\n}\n\n/** https://discord.com/developers/docs/topics/gateway-events#activity-object */\nexport interface BotActivity {\n name: string\n type: ActivityTypes\n url?: string\n}\n\n/** https://discord.com/developers/docs/topics/gateway#update-voice-state */\nexport interface UpdateVoiceState {\n /** id of the guild */\n guildId: string\n /** id of the voice channel client wants to join (null if disconnecting) */\n channelId: string | null\n /** Is the client muted */\n selfMute: boolean\n /** Is the client deafened */\n selfDeaf: boolean\n}\n\n/** https://discord.com/developers/docs/topics/gateway-events#update-presence */\nexport interface StatusUpdate {\n // /** Unix time (in milliseconds) of when the client went idle, or null if the client is not idle */\n // since: number | null;\n /** The user's activities */\n activities?: Camelize<Array<Omit<DiscordActivity, 'created_at'>>>\n /** The user's new status */\n status: keyof typeof PresenceStatus\n // /** Whether or not the client is afk */\n // afk: boolean;\n}\n"],"names":["ShardState","Connected","Connecting","Disconnected","Unidentified","Identifying","Resuming","Offline","ShardSocketCloseCodes","Shutdown","ResumeClosingOldConnection","ZombiedConnection","TestingFinished","Resharded","ReIdentifying"],"mappings":"AAAA,WAGO;UAAKA,UAAU;IAAVA,WAAAA,WACV,+EAA+E,GAC/EC,eAAY,KAAZA;IAFUD,WAAAA,WAGV,2HAA2H,GAC3HE,gBAAa,KAAbA;IAJUF,WAAAA,WAKV,uEAAuE,GACvEG,kBAAe,KAAfA;IANUH,WAAAA,WAOV,+HAA+H,GAC/HI,kBAAe,KAAfA;IARUJ,WAAAA,WASV,0EAA0E,GAC1EK,iBAAc,KAAdA;IAVUL,WAAAA,WAWV,0DAA0D,GAC1DM,cAAW,KAAXA;IAZUN,WAAAA,WAaV,kHAAkH,GAClHO,aAAU,KAAVA;GAdUP,eAAAA;WAkHL;UAAKQ,qBAAqB;IAArBA,sBAAAA,sBACV,8BAA8B,GAC9BC,cAAW,QAAXA;IAFUD,sBAAAA,sBAGV,qFAAqF,GACrFE,gCAA6B,QAA7BA;IAJUF,sBAAAA,sBAKV;;GAEC,GACDG,uBAAoB,QAApBA;IARUH,sBAAAA,sBASV,yFAAyF,GACzFI,qBAAkB,QAAlBA;IAVUJ,sBAAAA,sBAWV,kFAAkF,GAClFK,eAAY,QAAZA;IAZUL,sBAAAA,sBAaV,6EAA6E,GAC7EM,mBAAgB,QAAhBA;GAdUN,0BAAAA"}
1
+ {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { ActivityTypes, Camelize, DiscordActivity, DiscordGatewayPayload, GatewayOpcodes, PresenceStatus } from '@discordeno/types'\nimport type Shard from './Shard.js'\n\nexport enum ShardState {\n /** Shard is fully connected to the gateway and receiving events from Discord. */\n Connected = 0,\n /** Shard started to connect to the gateway. This is only used if the shard is not currently trying to identify or resume. */\n Connecting = 1,\n /** Shard got disconnected and reconnection actions have been started. */\n Disconnected = 2,\n /** The shard is connected to the gateway but only heartbeating. At this state the shard has not been identified with discord. */\n Unidentified = 3,\n /** Shard is trying to identify with the gateway to create a new session. */\n Identifying = 4,\n /** Shard is trying to resume a session with the gateway. */\n Resuming = 5,\n /** Shard got shut down studied or due to a not (self) fixable error and may not attempt to reconnect on its own. */\n Offline = 6,\n}\n\nexport interface ShardGatewayConfig {\n /** Whether incoming payloads are compressed using zlib.\n *\n * @default false\n */\n compress: boolean\n /** The calculated intent value of the events which the shard should receive.\n *\n * @default 0\n */\n intents: number\n /** Identify properties to use */\n properties: {\n /** Operating system the shard runs on.\n *\n * @default \"darwin\" | \"linux\" | \"windows\"\n */\n os: string\n /** The \"browser\" where this shard is running on.\n *\n * @default \"Discordeno\"\n */\n browser: string\n /** The device on which the shard is running.\n *\n * @default \"Discordeno\"\n */\n device: string\n }\n /** Bot token which is used to connect to Discord */\n token: string\n /** The URL of the gateway which should be connected to.\n *\n * @default \"wss://gateway.discord.gg\"\n */\n url: string\n /** The gateway version which should be used.\n *\n * @default 10\n */\n version: number\n /**\n * The total number of shards to connect to across the entire bot.\n * @default 1\n */\n totalShards: number\n}\n\nexport interface ShardHeart {\n /** Whether or not the heartbeat was acknowledged by Discord in time. */\n acknowledged: boolean\n /** Interval between heartbeats requested by Discord. */\n interval: number\n /** Id of the interval, which is used for sending the heartbeats. */\n intervalId?: NodeJS.Timer\n /** Unix (in milliseconds) timestamp when the last heartbeat ACK was received from Discord. */\n lastAck?: number\n /** Unix timestamp (in milliseconds) when the last heartbeat was sent. */\n lastBeat?: number\n /** Round trip time (in milliseconds) from Shard to Discord and back.\n * Calculated using the heartbeat system.\n * Note: this value is undefined until the first heartbeat to Discord has happened.\n */\n rtt?: number\n /** Id of the timeout which is used for sending the first heartbeat to Discord since it's \"special\". */\n timeoutId?: NodeJS.Timeout\n}\n\nexport interface ShardEvents {\n /** A heartbeat has been send. */\n heartbeat?: (shard: Shard) => unknown\n /** A heartbeat ACK was received. */\n heartbeatAck?: (shard: Shard) => unknown\n /** Shard has received a Hello payload. */\n hello?: (shard: Shard) => unknown\n /** The Shards session has been invalidated. */\n invalidSession?: (shard: Shard, resumable: boolean) => unknown\n /** The shard has started a resume action. */\n resuming?: (shard: Shard) => unknown\n /** The shard has successfully resumed an old session. */\n resumed?: (shard: Shard) => unknown\n /** Discord has requested the Shard to reconnect. */\n requestedReconnect?: (shard: Shard) => unknown\n /** The shard started to connect to Discord's gateway. */\n connecting?: (shard: Shard) => unknown\n /** The shard is connected with Discord's gateway. */\n connected?: (shard: Shard) => unknown\n /** The shard has been disconnected from Discord's gateway. */\n disconnected?: (shard: Shard) => unknown\n /** The shard has started to identify itself to Discord. */\n identifying?: (shard: Shard) => unknown\n /** The shard has successfully been identified itself with Discord. */\n identified?: (shard: Shard) => unknown\n /** The shard has received a message from Discord. */\n message?: (shard: Shard, payload: Camelize<DiscordGatewayPayload>) => unknown\n}\n\nexport enum ShardSocketCloseCodes {\n /** A regular Shard shutdown. */\n Shutdown = 3000,\n /** A resume has been requested and therefore the old connection needs to be closed. */\n ResumeClosingOldConnection = 3024,\n /** Did not receive a heartbeat ACK in time.\n * Closing the shard and creating a new session.\n */\n ZombiedConnection = 3010,\n /** Discordeno's gateway tests hae been finished, therefore the Shard can be turned off. */\n TestingFinished = 3064,\n /** Special close code reserved for Discordeno's zero-downtime resharding system. */\n Resharded = 3065,\n /** Shard is re-identifying therefore the old connection needs to be closed. */\n ReIdentifying = 3066,\n}\n\nexport interface ShardSocketRequest {\n /** The OP-Code for the payload to send. */\n op: GatewayOpcodes\n /** Payload data. */\n d: unknown\n}\n\n/** https://discord.com/developers/docs/topics/gateway-events#update-presence */\nexport interface BotStatusUpdate {\n // /** Unix time (in milliseconds) of when the client went idle, or null if the client is not idle */\n since: number | null\n /** The user's activities */\n activities: BotActivity[]\n /** The user's new status */\n status: keyof typeof PresenceStatus\n}\n\n/** https://discord.com/developers/docs/topics/gateway-events#activity-object */\nexport interface BotActivity {\n name: string\n type: ActivityTypes\n url?: string\n}\n\n/** https://discord.com/developers/docs/topics/gateway#update-voice-state */\nexport interface UpdateVoiceState {\n /** id of the guild */\n guildId: string\n /** id of the voice channel client wants to join (null if disconnecting) */\n channelId: string | null\n /** Is the client muted */\n selfMute: boolean\n /** Is the client deafened */\n selfDeaf: boolean\n}\n\n/** https://discord.com/developers/docs/topics/gateway-events#update-presence */\nexport interface StatusUpdate {\n // /** Unix time (in milliseconds) of when the client went idle, or null if the client is not idle */\n // since: number | null;\n /** The user's activities */\n activities?: Camelize<Array<Omit<DiscordActivity, 'created_at'>>>\n /** The user's new status */\n status: keyof typeof PresenceStatus\n // /** Whether or not the client is afk */\n // afk: boolean;\n}\n"],"names":["ShardState","Connected","Connecting","Disconnected","Unidentified","Identifying","Resuming","Offline","ShardSocketCloseCodes","Shutdown","ResumeClosingOldConnection","ZombiedConnection","TestingFinished","Resharded","ReIdentifying"],"mappings":"WAGO;UAAKA,UAAU;IAAVA,WAAAA,WACV,+EAA+E,GAC/EC,eAAY,KAAZA;IAFUD,WAAAA,WAGV,2HAA2H,GAC3HE,gBAAa,KAAbA;IAJUF,WAAAA,WAKV,uEAAuE,GACvEG,kBAAe,KAAfA;IANUH,WAAAA,WAOV,+HAA+H,GAC/HI,kBAAe,KAAfA;IARUJ,WAAAA,WASV,0EAA0E,GAC1EK,iBAAc,KAAdA;IAVUL,WAAAA,WAWV,0DAA0D,GAC1DM,cAAW,KAAXA;IAZUN,WAAAA,WAaV,kHAAkH,GAClHO,aAAU,KAAVA;GAdUP,eAAAA;WAkHL;UAAKQ,qBAAqB;IAArBA,sBAAAA,sBACV,8BAA8B,GAC9BC,cAAW,QAAXA;IAFUD,sBAAAA,sBAGV,qFAAqF,GACrFE,gCAA6B,QAA7BA;IAJUF,sBAAAA,sBAKV;;GAEC,GACDG,uBAAoB,QAApBA;IARUH,sBAAAA,sBASV,yFAAyF,GACzFI,qBAAkB,QAAlBA;IAVUJ,sBAAAA,sBAWV,kFAAkF,GAClFK,eAAY,QAAZA;IAZUL,sBAAAA,sBAaV,6EAA6E,GAC7EM,mBAAgB,QAAhBA;GAdUN,0BAAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@discordeno/gateway",
3
- "version": "19.0.0-next.fc13bdf",
3
+ "version": "19.0.0-next.fdf0d53",
4
4
  "main": "./dist/index.js",
5
5
  "types": "./dist/index.d.ts",
6
6
  "type": "module",
@@ -24,27 +24,27 @@
24
24
  "test:test-type": "tsc --project tsconfig.test.json"
25
25
  },
26
26
  "dependencies": {
27
- "@discordeno/types": "19.0.0-next.fc13bdf",
28
- "@discordeno/utils": "19.0.0-next.fc13bdf",
29
- "ws": "^8.11.0"
27
+ "@discordeno/types": "19.0.0-next.fdf0d53",
28
+ "@discordeno/utils": "19.0.0-next.fdf0d53",
29
+ "ws": "^8.13.0"
30
30
  },
31
31
  "devDependencies": {
32
- "@swc/cli": "^0.1.57",
33
- "@swc/core": "^1.3.21",
34
- "@types/chai": "^4",
35
- "@types/mocha": "^10",
36
- "@types/node": "^18.11.9",
32
+ "@swc/cli": "^0.1.62",
33
+ "@swc/core": "^1.3.40",
34
+ "@types/chai": "^4.3.4",
35
+ "@types/mocha": "^10.0.1",
36
+ "@types/node": "^18.15.3",
37
37
  "@types/sinon": "^10.0.13",
38
- "@types/ws": "^8.5.3",
39
- "c8": "^7.12.0",
38
+ "@types/ws": "^8.5.4",
39
+ "c8": "^7.13.0",
40
40
  "chai": "^4.3.7",
41
- "eslint": "^8.0.1",
41
+ "eslint": "^8.36.0",
42
42
  "eslint-config-discordeno": "*",
43
- "mocha": "^10.1.0",
44
- "sinon": "^15.0.0",
43
+ "mocha": "^10.2.0",
44
+ "sinon": "^15.0.2",
45
45
  "ts-node": "^10.9.1",
46
46
  "tsconfig": "*",
47
- "typescript": "^4.9.3",
48
- "uWebSockets.js": "uNetworking/uWebSockets.js#v20.19.0"
47
+ "typescript": "^4.9.5",
48
+ "uWebSockets.js": "https://github.com/uNetworking/uWebSockets.js.git#commit=42c9c0d5d31f46ca4115dc75672b0037ec970f28"
49
49
  }
50
50
  }