@bakit/gateway 2.1.9 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,25 @@
1
+ 'use strict';
2
+
3
+ var gateway = require('@bakit/gateway');
4
+
5
+ // src/lib/internal/cluster.ts
6
+ var {
7
+ BAKIT_CLUSTER_ID,
8
+ BAKIT_DISCORD_TOKEN,
9
+ BAKIT_DISCORD_INTENTS,
10
+ BAKIT_DISCORD_GATEWAY_URL,
11
+ BAKIT_DISCORD_GATEWAY_VERSION,
12
+ BAKIT_CLUSTER_SHARD_TOTAL,
13
+ BAKIT_CLUSTER_SHARD_LIST
14
+ } = process.env, cluster = new gateway.Cluster(Number(BAKIT_CLUSTER_ID), {
15
+ token: BAKIT_DISCORD_TOKEN,
16
+ intents: Number(BAKIT_DISCORD_INTENTS),
17
+ total: Number(BAKIT_CLUSTER_SHARD_TOTAL),
18
+ shards: JSON.parse(BAKIT_CLUSTER_SHARD_LIST),
19
+ gateway: {
20
+ baseURL: BAKIT_DISCORD_GATEWAY_URL,
21
+ version: Number(BAKIT_DISCORD_GATEWAY_VERSION)
22
+ }
23
+ });
24
+ gateway.ClusterProcess.bindProcess(cluster);
25
+ cluster.spawn();
@@ -0,0 +1,23 @@
1
+ import { Cluster, ClusterProcess } from '@bakit/gateway';
2
+
3
+ // src/lib/internal/cluster.ts
4
+ var {
5
+ BAKIT_CLUSTER_ID,
6
+ BAKIT_DISCORD_TOKEN,
7
+ BAKIT_DISCORD_INTENTS,
8
+ BAKIT_DISCORD_GATEWAY_URL,
9
+ BAKIT_DISCORD_GATEWAY_VERSION,
10
+ BAKIT_CLUSTER_SHARD_TOTAL,
11
+ BAKIT_CLUSTER_SHARD_LIST
12
+ } = process.env, cluster = new Cluster(Number(BAKIT_CLUSTER_ID), {
13
+ token: BAKIT_DISCORD_TOKEN,
14
+ intents: Number(BAKIT_DISCORD_INTENTS),
15
+ total: Number(BAKIT_CLUSTER_SHARD_TOTAL),
16
+ shards: JSON.parse(BAKIT_CLUSTER_SHARD_LIST),
17
+ gateway: {
18
+ baseURL: BAKIT_DISCORD_GATEWAY_URL,
19
+ version: Number(BAKIT_DISCORD_GATEWAY_VERSION)
20
+ }
21
+ });
22
+ ClusterProcess.bindProcess(cluster);
23
+ cluster.spawn();
package/dist/index.cjs ADDED
@@ -0,0 +1,632 @@
1
+ 'use strict';
2
+
3
+ var EventEmitter = require('events');
4
+ var zlib = require('zlib');
5
+ var util = require('util');
6
+ var crypto = require('crypto');
7
+ var WebSocket = require('ws');
8
+ var v10 = require('discord-api-types/v10');
9
+ var child_process = require('child_process');
10
+ var path = require('path');
11
+ var url = require('url');
12
+ var utils = require('@bakit/utils');
13
+ var rest = require('@bakit/rest');
14
+
15
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
16
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
17
+
18
+ var EventEmitter__default = /*#__PURE__*/_interopDefault(EventEmitter);
19
+ var WebSocket__default = /*#__PURE__*/_interopDefault(WebSocket);
20
+
21
+ // src/lib/Shard.ts
22
+ var MIN_HEARTBEAT_INTERVAL = 1e3, MAX_HEARTBEAT_INTERVAL = 6e4, SAFE_HEARTBEAT_INTERVAL = 45e3, ShardState = /* @__PURE__ */ ((ShardState2) => (ShardState2[ShardState2.Idle = 0] = "Idle", ShardState2[ShardState2.Connecting = 1] = "Connecting", ShardState2[ShardState2.Ready = 2] = "Ready", ShardState2[ShardState2.Resuming = 3] = "Resuming", ShardState2[ShardState2.Disconnecting = 4] = "Disconnecting", ShardState2[ShardState2.Disconnected = 5] = "Disconnected", ShardState2))(ShardState || {}), ShardStrategy = /* @__PURE__ */ ((ShardStrategy2) => (ShardStrategy2[ShardStrategy2.Resume = 0] = "Resume", ShardStrategy2[ShardStrategy2.Reconnect = 1] = "Reconnect", ShardStrategy2[ShardStrategy2.Shutdown = 2] = "Shutdown", ShardStrategy2))(ShardStrategy || {}), Shard = class extends EventEmitter__default.default {
23
+ constructor(id, options) {
24
+ super();
25
+ this.id = id;
26
+ this.options = options;
27
+ }
28
+ #state = 0 /* Idle */;
29
+ #ws;
30
+ #inflater;
31
+ #textDecoder = new util.TextDecoder();
32
+ #decompressBuffer = [];
33
+ #sessionId;
34
+ #lastSequence;
35
+ #resumeGatewayURL;
36
+ #lastHeartbeatSent = -1;
37
+ #lastHeartbeatAck = -1;
38
+ #missedHeartbeats = 0;
39
+ #heartbeatInterval;
40
+ #heartbeatTimeout;
41
+ #reconnectTimeout;
42
+ #strategy;
43
+ get state() {
44
+ return this.#state;
45
+ }
46
+ get latency() {
47
+ return this.#lastHeartbeatSent === -1 || this.#lastHeartbeatAck === -1 ? -1 : this.#lastHeartbeatAck - this.#lastHeartbeatSent;
48
+ }
49
+ get resumable() {
50
+ let hasSessionId = this.#sessionId !== void 0, hasSequence = this.#lastSequence !== void 0;
51
+ return this.#strategy === 0 /* Resume */ && hasSequence && hasSessionId;
52
+ }
53
+ async connect() {
54
+ if (this.#state !== 0 /* Idle */ && this.#state !== 5 /* Disconnected */)
55
+ throw new Error("Shard already connecting or connected");
56
+ return new Promise((resolve2, reject) => {
57
+ let cleanup = () => {
58
+ this.off("error", onError), this.off("ready", onReady);
59
+ }, onReady = () => {
60
+ cleanup(), resolve2();
61
+ }, onError = (err) => {
62
+ cleanup(), reject(err);
63
+ };
64
+ this.once("ready", onReady), this.once("error", onError), this.#init();
65
+ });
66
+ }
67
+ disconnect(code) {
68
+ return new Promise((resolve2) => {
69
+ if (this.#state = 4 /* Disconnecting */, this.#strategy = 2 /* Shutdown */, !this.#ws) {
70
+ resolve2();
71
+ return;
72
+ }
73
+ this.#ws.once("close", () => {
74
+ resolve2();
75
+ }), this.#ws.close(code);
76
+ });
77
+ }
78
+ resume() {
79
+ this.resumable && (this.#state = 3 /* Resuming */, this.send({
80
+ op: v10.GatewayOpcodes.Resume,
81
+ d: {
82
+ token: this.options.token,
83
+ session_id: this.#sessionId,
84
+ seq: this.#lastSequence
85
+ }
86
+ }));
87
+ }
88
+ identify() {
89
+ this.send({
90
+ op: v10.GatewayOpcodes.Identify,
91
+ d: {
92
+ token: this.options.token,
93
+ intents: Number(this.options.intents),
94
+ properties: {
95
+ os: process.platform,
96
+ browser: "bakit",
97
+ device: "bakit"
98
+ },
99
+ shard: [this.id, this.options.total]
100
+ }
101
+ });
102
+ }
103
+ send(payload) {
104
+ this.#ws?.readyState === WebSocket__default.default.OPEN && this.#ws.send(JSON.stringify(payload));
105
+ }
106
+ sendHeartbeat() {
107
+ if (this.#lastHeartbeatSent !== -1 && this.#lastHeartbeatAck < this.#lastHeartbeatSent ? this.#missedHeartbeats++ : this.#missedHeartbeats = 0, this.#missedHeartbeats >= 2) {
108
+ this.emit("debug", "Missed 2 heartbeats, reconnecting"), this.#ws?.terminate();
109
+ return;
110
+ }
111
+ this.send({
112
+ op: v10.GatewayOpcodes.Heartbeat,
113
+ d: this.#lastSequence ?? null
114
+ }), this.#lastHeartbeatSent = Date.now();
115
+ }
116
+ #init() {
117
+ this.#state = 1 /* Connecting */, this.#strategy ??= 1 /* Reconnect */;
118
+ let url = new URL(
119
+ this.#strategy === 0 /* Resume */ && this.#resumeGatewayURL ? this.#resumeGatewayURL : this.options.gateway.baseURL
120
+ );
121
+ url.searchParams.set("v", String(this.options.gateway.version)), url.searchParams.set("encoding", "json"), url.searchParams.set("compress", "zlib-stream"), this.#ws = new WebSocket__default.default(url, { perMessageDeflate: false }), this.#inflater = zlib.createInflate({ flush: zlib.constants.Z_SYNC_FLUSH }), this.#inflater.on("data", (chunk) => this.#onInflate(chunk)), this.#inflater.on("error", (err) => {
122
+ this.emit("error", err), this.#ws?.terminate();
123
+ }), this.#ws.on("message", (data) => this.#onMessage(data)), this.#ws.on("close", (code) => this.#onClose(code)), this.#ws.on("error", (err) => this.emit("error", err));
124
+ }
125
+ #onMessage(data) {
126
+ if (!this.#inflater) {
127
+ try {
128
+ let text = data.toString(), payload = JSON.parse(text);
129
+ this.#handlePayload(payload);
130
+ } catch (error) {
131
+ this.emit("error", error);
132
+ }
133
+ return;
134
+ }
135
+ let buffer;
136
+ Buffer.isBuffer(data) ? buffer = data : Array.isArray(data) ? buffer = Buffer.concat(data) : data instanceof ArrayBuffer ? buffer = Buffer.from(data) : buffer = Buffer.from(String(data));
137
+ let hasSyncFlush = buffer.length >= 4 && buffer[buffer.length - 4] === 0 && buffer[buffer.length - 3] === 0 && buffer[buffer.length - 2] === 255 && buffer[buffer.length - 1] === 255;
138
+ this.#inflater.write(buffer, (writeError) => {
139
+ if (writeError) {
140
+ this.emit("error", writeError);
141
+ return;
142
+ }
143
+ hasSyncFlush && this.#inflater?.flush(zlib.constants.Z_SYNC_FLUSH);
144
+ });
145
+ }
146
+ #onInflate(chunk) {
147
+ this.#decompressBuffer.push(chunk);
148
+ let fullBuffer = Buffer.concat(this.#decompressBuffer);
149
+ try {
150
+ let text = this.#textDecoder.decode(fullBuffer), payload = JSON.parse(text);
151
+ this.#handlePayload(payload), this.#decompressBuffer = [];
152
+ } catch (error) {
153
+ if (error instanceof SyntaxError) {
154
+ let text = this.#textDecoder.decode(fullBuffer);
155
+ if (text.includes("{") && !isValidJSON(text))
156
+ return;
157
+ this.emit("error", error), this.#decompressBuffer = [];
158
+ }
159
+ }
160
+ }
161
+ #handlePayload(payload) {
162
+ switch (this.emit("raw", payload), payload.op) {
163
+ case v10.GatewayOpcodes.Dispatch: {
164
+ this.#handleDispatch(payload);
165
+ break;
166
+ }
167
+ case v10.GatewayOpcodes.Hello: {
168
+ this.#startHeartbeat(payload.d.heartbeat_interval), this.resumable ? this.resume() : this.emit("needIdentify");
169
+ break;
170
+ }
171
+ case v10.GatewayOpcodes.Heartbeat: {
172
+ this.sendHeartbeat();
173
+ break;
174
+ }
175
+ case v10.GatewayOpcodes.HeartbeatAck: {
176
+ this.#lastHeartbeatAck = Date.now();
177
+ break;
178
+ }
179
+ case v10.GatewayOpcodes.InvalidSession: {
180
+ payload.d ? this.#strategy = 0 /* Resume */ : (this.#strategy = 1 /* Reconnect */, this.#sessionId = void 0, this.#lastSequence = void 0, this.#resumeGatewayURL = void 0), this.emit("debug", `Invalid session (resumable=${this.resumable})`), this.#ws?.terminate();
181
+ break;
182
+ }
183
+ case v10.GatewayOpcodes.Reconnect: {
184
+ this.#strategy = 0 /* Resume */, this.emit("debug", "Reconnecting to gateway"), this.#ws?.terminate();
185
+ break;
186
+ }
187
+ }
188
+ }
189
+ #handleDispatch(payload) {
190
+ switch (this.#lastSequence = payload.s, this.emit("dispatch", payload), payload.t) {
191
+ case v10.GatewayDispatchEvents.Ready: {
192
+ let { d: data } = payload;
193
+ this.#state = 2 /* Ready */, this.#sessionId = data.session_id, this.#resumeGatewayURL = data.resume_gateway_url, this.emit("ready", data);
194
+ break;
195
+ }
196
+ case v10.GatewayDispatchEvents.Resumed: {
197
+ this.#state = 2 /* Ready */, this.#strategy = void 0, this.emit("resume");
198
+ break;
199
+ }
200
+ }
201
+ }
202
+ #onClose(code) {
203
+ if (this.#cleanup(), this.#state = 5 /* Disconnected */, this.emit("disconnect", code), this.#strategy === 2 /* Shutdown */) {
204
+ switch (code) {
205
+ case v10.GatewayCloseCodes.AuthenticationFailed:
206
+ this.emit("error", new Error("Invalid token provided"));
207
+ break;
208
+ case v10.GatewayCloseCodes.InvalidIntents:
209
+ this.emit("error", new Error("Invalid intents provided"));
210
+ break;
211
+ case v10.GatewayCloseCodes.DisallowedIntents:
212
+ this.emit("error", new Error("Disallowed intents provided"));
213
+ break;
214
+ }
215
+ return;
216
+ } else this.#strategy || (this.#strategy = this.#getStrategy(code));
217
+ (this.#strategy === 1 /* Reconnect */ || this.#strategy === 0 /* Resume */) && this.#scheduleReconnect();
218
+ }
219
+ #getStrategy(code) {
220
+ switch (code) {
221
+ case v10.GatewayCloseCodes.AuthenticationFailed:
222
+ case v10.GatewayCloseCodes.InvalidIntents:
223
+ case v10.GatewayCloseCodes.DisallowedIntents:
224
+ return 2 /* Shutdown */;
225
+ case v10.GatewayCloseCodes.InvalidSeq:
226
+ case v10.GatewayCloseCodes.SessionTimedOut:
227
+ return 1 /* Reconnect */;
228
+ default:
229
+ return 0 /* Resume */;
230
+ }
231
+ }
232
+ #scheduleReconnect(delay = 1e3) {
233
+ this.#reconnectTimeout || (this.#reconnectTimeout = setTimeout(() => {
234
+ this.#reconnectTimeout = void 0, this.#state = 0 /* Idle */, this.#init();
235
+ }, delay));
236
+ }
237
+ #startHeartbeat(interval) {
238
+ this.#heartbeatInterval && (clearInterval(this.#heartbeatInterval), this.#heartbeatInterval = void 0), (interval < MIN_HEARTBEAT_INTERVAL || interval > MAX_HEARTBEAT_INTERVAL) && (interval = SAFE_HEARTBEAT_INTERVAL);
239
+ let jitter = crypto.randomInt(0, 10) / 100, firstDelay = Math.floor(interval * jitter);
240
+ this.emit("debug", `Starting heartbeat (interval=${interval}ms, jitter=${firstDelay}ms)`), this.#heartbeatTimeout = setTimeout(() => {
241
+ this.sendHeartbeat(), this.#heartbeatInterval = setInterval(() => this.sendHeartbeat(), interval);
242
+ }, firstDelay);
243
+ }
244
+ #cleanup() {
245
+ clearTimeout(this.#reconnectTimeout), clearInterval(this.#heartbeatInterval), clearTimeout(this.#heartbeatTimeout), this.#inflater?.destroy(), this.#inflater = void 0, this.#ws?.removeAllListeners(), this.#ws = void 0, this.#decompressBuffer = [], this.#missedHeartbeats = 0;
246
+ }
247
+ };
248
+ function isValidJSON(str) {
249
+ try {
250
+ return JSON.parse(str), !0;
251
+ } catch {
252
+ return false;
253
+ }
254
+ }
255
+ var EVAL_TIMEOUT = 3e4, __filename$1 = url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))), __dirname$1 = path.dirname(__filename$1);
256
+ function isDispatchPayload(payload) {
257
+ return payload.op === "dispatch";
258
+ }
259
+ function isIdentifyPayload(payload) {
260
+ return payload.op === "identify";
261
+ }
262
+ function isSendPayload(payload) {
263
+ return payload.op === "send";
264
+ }
265
+ function isEvalRequestPayload(payload) {
266
+ return payload.op === "eval";
267
+ }
268
+ function isEvalResponsePayload(payload) {
269
+ return payload.op === "evalResponse";
270
+ }
271
+ var ClusterProcess = class _ClusterProcess extends EventEmitter__default.default {
272
+ constructor(manager, id, options = {}) {
273
+ super();
274
+ this.manager = manager;
275
+ this.id = id;
276
+ this.setMaxListeners(0);
277
+ let entry = path.resolve(__dirname$1, utils.isCommonJS() ? "cluster.cjs" : "cluster.js");
278
+ this.process = child_process.fork(entry, {
279
+ env: options.env,
280
+ execArgv: options.execArgv,
281
+ stdio: ["inherit", "inherit", "inherit", "ipc"]
282
+ }), this.#bindProcessEvents();
283
+ }
284
+ process;
285
+ #pendingEvals = /* @__PURE__ */ new Map();
286
+ get killed() {
287
+ return this.process.killed || !this.process.connected;
288
+ }
289
+ kill(signal = "SIGTERM") {
290
+ if (!this.killed) {
291
+ for (let [nonce, pending] of this.#pendingEvals)
292
+ clearTimeout(pending.timeout), pending.reject(new Error(`Process killed before eval completed (nonce: ${nonce})`));
293
+ this.#pendingEvals.clear(), this.process.kill(signal);
294
+ }
295
+ }
296
+ async eval(fn, ctx) {
297
+ let nonce = crypto.randomUUID();
298
+ return new Promise((resolve2, reject) => {
299
+ let timeoutId = setTimeout(() => {
300
+ this.#pendingEvals.delete(nonce), reject(new Error(`Eval timed out after ${EVAL_TIMEOUT}ms`));
301
+ }, EVAL_TIMEOUT);
302
+ this.#pendingEvals.set(nonce, {
303
+ resolve: resolve2,
304
+ reject,
305
+ timeout: timeoutId
306
+ });
307
+ let context;
308
+ try {
309
+ context = JSON.stringify(ctx ?? null);
310
+ } catch {
311
+ reject(new Error("Eval context is not serializable"));
312
+ return;
313
+ }
314
+ let script = `(${fn.toString()})(cluster, ${context})`;
315
+ this.sendIPC({
316
+ op: "eval",
317
+ d: { nonce, script }
318
+ });
319
+ });
320
+ }
321
+ send(idOrPayload, payload) {
322
+ let hasShardId = typeof idOrPayload == "number" && payload !== void 0, shardId = hasShardId ? idOrPayload : void 0, data = hasShardId ? payload : idOrPayload;
323
+ this.sendIPC({
324
+ op: "send",
325
+ d: { shardId, data }
326
+ });
327
+ }
328
+ sendIPC(message) {
329
+ if (!(!this.process.connected || this.process.killed))
330
+ try {
331
+ this.process.send(message, void 0, void 0, (err) => {
332
+ err && this.emit("error", err);
333
+ });
334
+ } catch (err) {
335
+ this.emit("error", err);
336
+ }
337
+ }
338
+ identifyShard(id) {
339
+ this.sendIPC({
340
+ op: "identify",
341
+ d: id
342
+ });
343
+ }
344
+ #bindProcessEvents() {
345
+ this.process.on("message", (message) => this.#handleIPC(message)), this.process.on("error", (err) => this.emit("error", err)), this.process.on("disconnect", () => this.emit("debug", "Process disconnected")), this.process.on("exit", (code) => {
346
+ for (let [nonce, pending] of this.#pendingEvals)
347
+ clearTimeout(pending.timeout), pending.reject(new Error(`Process exited (code: ${code}) before eval completed (nonce: ${nonce})`));
348
+ this.#pendingEvals.clear();
349
+ });
350
+ }
351
+ #handleIPC(message) {
352
+ if (this.#isValidPayload(message)) {
353
+ if (isDispatchPayload(message)) {
354
+ this.emit(message.t, ...message.d);
355
+ return;
356
+ }
357
+ if (isEvalResponsePayload(message)) {
358
+ this.#handleEvalResponse(message);
359
+ return;
360
+ }
361
+ }
362
+ }
363
+ #handleEvalResponse(payload) {
364
+ let pending = this.#pendingEvals.get(payload.d.nonce);
365
+ if (!pending) {
366
+ this.emit("debug", `Received eval response for unknown nonce: ${payload.d.nonce}`);
367
+ return;
368
+ }
369
+ if (pending.timeout && clearTimeout(pending.timeout), this.#pendingEvals.delete(payload.d.nonce), payload.d.success)
370
+ pending.resolve({
371
+ success: true,
372
+ data: payload.d.result,
373
+ cluster: this
374
+ });
375
+ else {
376
+ let error = new Error(payload.d.error ?? "Unknown eval error");
377
+ pending.resolve({
378
+ success: false,
379
+ error,
380
+ cluster: this
381
+ });
382
+ }
383
+ }
384
+ #isValidPayload(message) {
385
+ if (typeof message != "object" || message === null)
386
+ return false;
387
+ let payload = message;
388
+ return payload.op === "dispatch" || payload.op === "identify" || payload.op === "send" || payload.op === "eval" || payload.op === "evalResponse";
389
+ }
390
+ static bindProcess(cluster) {
391
+ let superEmit = cluster.emit.bind(cluster), safeSend = (message) => {
392
+ process.connected && process.send?.(message, void 0, void 0, (err) => {
393
+ err && cluster.emit("error", err);
394
+ });
395
+ };
396
+ cluster.emit = function(eventName, ...args) {
397
+ let result = superEmit(eventName, ...args);
398
+ return safeSend({
399
+ op: "dispatch",
400
+ t: eventName,
401
+ d: args
402
+ }), result;
403
+ };
404
+ let messageHandler = async (message) => {
405
+ if (isIdentifyPayload(message)) {
406
+ cluster.shards.get(message.d)?.identify();
407
+ return;
408
+ }
409
+ if (isSendPayload(message)) {
410
+ message.d.shardId !== void 0 ? cluster.send(message.d.shardId, message.d.data) : cluster.send(message.d.data);
411
+ return;
412
+ }
413
+ if (isEvalRequestPayload(message)) {
414
+ await _ClusterProcess.#handleEvalRequest(cluster, message, safeSend);
415
+ return;
416
+ }
417
+ };
418
+ process.on("message", messageHandler);
419
+ }
420
+ static async #handleEvalRequest(cluster, payload, safeSend) {
421
+ let { nonce, script } = payload.d, executeEval = async () => await new Function("cluster", `return ${script}`)(cluster), timeoutId;
422
+ try {
423
+ let evalPromise = executeEval(), timeoutPromise = new Promise((_, reject) => {
424
+ timeoutId = setTimeout(() => {
425
+ reject(new Error(`Eval execution timed out after ${EVAL_TIMEOUT}ms`));
426
+ }, EVAL_TIMEOUT);
427
+ }), result = await Promise.race([evalPromise, timeoutPromise]);
428
+ timeoutId && clearTimeout(timeoutId), safeSend({
429
+ op: "evalResponse",
430
+ d: {
431
+ nonce,
432
+ success: !0,
433
+ result
434
+ }
435
+ });
436
+ } catch (err) {
437
+ timeoutId && clearTimeout(timeoutId), safeSend({
438
+ op: "evalResponse",
439
+ d: {
440
+ nonce,
441
+ success: false,
442
+ result: void 0,
443
+ error: err instanceof Error ? err.message : String(err)
444
+ }
445
+ });
446
+ }
447
+ }
448
+ };
449
+ var Cluster = class extends EventEmitter__default.default {
450
+ constructor(id, options) {
451
+ super();
452
+ this.id = id;
453
+ this.options = options;
454
+ }
455
+ shards = new utils.Collection();
456
+ #readyCount = 0;
457
+ #starting = false;
458
+ get size() {
459
+ return this.shards.size;
460
+ }
461
+ get ready() {
462
+ return this.#readyCount === this.options.shards.length;
463
+ }
464
+ async spawn() {
465
+ if (!this.#starting) {
466
+ this.#starting = true, this.emit("debug", `Spawning ${this.options.shards.length} shards...`);
467
+ for (let i of this.options.shards)
468
+ await this.#spawnShard(i);
469
+ this.emit("debug", "All shards spawned");
470
+ }
471
+ }
472
+ async shutdown(code = 1e3) {
473
+ this.emit("debug", "Shutting down cluster...");
474
+ let tasks = [];
475
+ for (let shard of this.shards.values())
476
+ tasks.push(shard.disconnect(code));
477
+ await Promise.allSettled(tasks), this.emit("debug", "Cluster shutdown complete");
478
+ }
479
+ broadcast(fn) {
480
+ for (let shard of this.shards.values())
481
+ fn(shard);
482
+ }
483
+ send(idOrPayload, payload) {
484
+ let hasId = typeof idOrPayload == "number" && payload !== void 0, shardId = hasId ? idOrPayload : void 0, data = hasId ? payload : idOrPayload;
485
+ shardId !== void 0 ? this.shards.get(shardId)?.send(data) : this.broadcast((shard) => shard.send(data));
486
+ }
487
+ async #spawnShard(id) {
488
+ let shard = new Shard(id, {
489
+ token: this.options.token,
490
+ intents: this.options.intents,
491
+ total: this.options.total,
492
+ gateway: this.options.gateway
493
+ });
494
+ this.#bindShardEvents(shard), this.shards.set(id, shard), this.emit("shardAdd", id), await shard.connect();
495
+ }
496
+ #bindShardEvents(shard) {
497
+ let id = shard.id;
498
+ shard.on("ready", () => {
499
+ this.#readyCount++, this.emit("debug", `Shard ${id} ready`), this.emit("shardReady", id), this.ready && this.emit("ready");
500
+ }), shard.on("resume", () => {
501
+ this.emit("debug", `Shard ${id} resumed`), this.emit("shardResume", id);
502
+ }), shard.on("disconnect", (code) => {
503
+ this.emit("debug", `Shard ${id} disconnected (${code})`), this.emit("shardDisconnect", id, code);
504
+ }), shard.on("error", (err) => {
505
+ this.emit("debug", `Shard ${id} error: ${err.message}`), this.emit("shardError", id, err);
506
+ }), shard.on("raw", (payload) => {
507
+ this.emit("raw", id, payload);
508
+ }), shard.on("dispatch", (payload) => {
509
+ this.emit("dispatch", id, payload);
510
+ }), shard.on("needIdentify", () => {
511
+ this.emit("needIdentify", id);
512
+ }), shard.on("debug", (msg) => {
513
+ this.emit("debug", `[Shard ${id}] ${msg}`);
514
+ });
515
+ }
516
+ };
517
+ var ShardingManager = class extends EventEmitter__default.default {
518
+ clusters = new utils.Collection();
519
+ options;
520
+ rest;
521
+ #gatewayInfo;
522
+ #totalShards = 0;
523
+ #readyCount = 0;
524
+ #identifyQueue;
525
+ constructor(options, rest$1) {
526
+ super(), this.setMaxListeners(0), this.options = {
527
+ shardsPerCluster: 5,
528
+ totalShards: options.totalShards ?? "auto",
529
+ ...options
530
+ }, rest$1 || (rest$1 = new rest.REST({ token: this.options.token })), this.rest = rest$1;
531
+ }
532
+ get totalClusters() {
533
+ let { shardsPerCluster } = this.options;
534
+ return shardsPerCluster <= 0 ? 0 : Math.ceil(this.totalShards / shardsPerCluster);
535
+ }
536
+ get totalShards() {
537
+ return this.#totalShards;
538
+ }
539
+ get ready() {
540
+ return this.#readyCount === this.totalClusters;
541
+ }
542
+ async spawn() {
543
+ this.#gatewayInfo = await this.rest.get("/gateway/bot");
544
+ let { session_start_limit: limit } = this.#gatewayInfo;
545
+ this.#totalShards = typeof this.options.totalShards == "number" ? this.options.totalShards : this.#gatewayInfo.shards, this.#identifyQueue = new utils.Queue({
546
+ concurrency: limit.max_concurrency,
547
+ intervalCap: limit.max_concurrency,
548
+ interval: 5e3
549
+ });
550
+ let { totalShards, totalClusters } = this;
551
+ this.emit("debug", `Spawning ${totalClusters} clusters (${totalShards} total shards)...`);
552
+ let promises = [];
553
+ for (let i = 0; i < totalClusters; i++)
554
+ promises.push(this.#spawnCluster(i));
555
+ await Promise.all(promises), this.emit("debug", "All clusters spawned");
556
+ }
557
+ async kill(signal = "SIGTERM") {
558
+ this.emit("debug", "Shutting down all clusters...");
559
+ let tasks = [];
560
+ for (let cluster of this.clusters.values())
561
+ tasks.push(
562
+ new Promise((resolve2) => {
563
+ cluster.process.once("exit", () => resolve2()), cluster.kill(signal);
564
+ })
565
+ );
566
+ await Promise.all(tasks), this.emit("debug", "All clusters shut down");
567
+ }
568
+ broadcast(payload) {
569
+ for (let cluster of this.clusters.values())
570
+ cluster.send(payload);
571
+ }
572
+ async broadcastEval(fn) {
573
+ let promises = this.clusters.map((cluster) => cluster.eval(fn));
574
+ return Promise.all(promises);
575
+ }
576
+ requestIdentify(cluster, shardId) {
577
+ this.#identifyQueue?.add(() => cluster.identifyShard(shardId));
578
+ }
579
+ #getShardIdsForCluster(clusterId) {
580
+ let start = clusterId * this.options.shardsPerCluster, end = Math.min(start + this.options.shardsPerCluster, this.totalShards);
581
+ return Array.from({ length: end - start }, (_, i) => start + i);
582
+ }
583
+ async #spawnCluster(id) {
584
+ let shardIds = this.#getShardIdsForCluster(id), firstShardId = shardIds[0], lastShardId = shardIds[shardIds.length - 1];
585
+ this.emit("debug", `Spawning cluster ${id} (shards ${firstShardId}-${lastShardId})`);
586
+ let env = {
587
+ ...process.env,
588
+ BAKIT_CLUSTER_ID: String(id),
589
+ BAKIT_CLUSTER_SHARD_TOTAL: String(this.totalShards),
590
+ BAKIT_CLUSTER_SHARD_LIST: JSON.stringify(shardIds),
591
+ BAKIT_DISCORD_TOKEN: this.options.token,
592
+ BAKIT_DISCORD_INTENTS: String(this.options.intents),
593
+ BAKIT_DISCORD_GATEWAY_URL: this.#gatewayInfo?.url,
594
+ BAKIT_DISCORD_GATEWAY_VERSION: "10"
595
+ }, cluster = new ClusterProcess(this, id, { env });
596
+ this.#bindClusterEvents(cluster, id), this.clusters.set(id, cluster), this.emit("clusterCreate", cluster);
597
+ }
598
+ #bindClusterEvents(cluster, id) {
599
+ cluster.on("ready", () => {
600
+ this.#readyCount++, this.emit("clusterReady", cluster), this.ready && this.emit("ready");
601
+ }), cluster.process.on("exit", (code) => {
602
+ this.emit("clusterExit", cluster, code), this.clusters.delete(id), this.#readyCount = Math.max(0, this.#readyCount - 1);
603
+ }), cluster.on("error", (err) => {
604
+ this.emit("clusterError", cluster, err);
605
+ }), cluster.on("debug", (msg) => {
606
+ this.emit("debug", `[Cluster ${id}] ${msg}`);
607
+ }), cluster.on("dispatch", (shardId, payload) => {
608
+ this.emit("dispatch", cluster, shardId, payload);
609
+ }), cluster.on("raw", (shardId, payload) => {
610
+ this.emit("raw", cluster, shardId, payload);
611
+ }), cluster.on("shardAdd", (shardId) => {
612
+ this.emit("shardAdd", cluster, shardId);
613
+ }), cluster.on("shardReady", (shardId) => {
614
+ this.emit("shardReady", cluster, shardId);
615
+ }), cluster.on("shardDisconnect", (shardId, code) => {
616
+ this.emit("shardDisconnect", cluster, shardId, code);
617
+ }), cluster.on("shardResume", (shardId) => {
618
+ this.emit("shardResume", cluster, shardId);
619
+ }), cluster.on("shardError", (shardId, error) => {
620
+ this.emit("shardError", cluster, shardId, error);
621
+ }), cluster.on("needIdentify", (shardId) => {
622
+ this.requestIdentify(cluster, shardId);
623
+ });
624
+ }
625
+ };
626
+
627
+ exports.Cluster = Cluster;
628
+ exports.ClusterProcess = ClusterProcess;
629
+ exports.Shard = Shard;
630
+ exports.ShardState = ShardState;
631
+ exports.ShardStrategy = ShardStrategy;
632
+ exports.ShardingManager = ShardingManager;