@bakit/gateway 3.0.2 → 3.0.3

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