@bakit/gateway 3.0.1 → 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.d.cts CHANGED
@@ -1,201 +1,208 @@
1
- import EventEmitter from 'node:events';
2
- import { GatewayReadyDispatchData, GatewayReceivePayload, GatewayDispatchPayload, GatewaySendPayload } from 'discord-api-types/v10';
3
- import { ChildProcess } from 'node:child_process';
4
- import { Collection } from '@bakit/utils';
5
- import { REST, RESTProxy } from '@bakit/rest';
1
+ import EventEmitter from "node:events";
2
+ import { GatewayDispatchPayload, GatewayReadyDispatchData, GatewayReceivePayload, GatewaySendPayload } from "discord-api-types/v10";
3
+ import { ChildProcess } from "node:child_process";
4
+ import { Collection } from "@discordjs/collection";
5
+ import { RESTLike } from "@bakit/rest";
6
6
 
7
+ //#region src/lib/Shard.d.ts
7
8
  declare enum ShardState {
8
- Idle = 0,
9
- Connecting = 1,
10
- Ready = 2,
11
- Resuming = 3,
12
- Disconnecting = 4,
13
- Disconnected = 5
9
+ Idle = 0,
10
+ Connecting = 1,
11
+ Ready = 2,
12
+ Resuming = 3,
13
+ Disconnecting = 4,
14
+ Disconnected = 5
14
15
  }
15
16
  declare enum ShardStrategy {
16
- Resume = 0,
17
- Reconnect = 1,
18
- Shutdown = 2
17
+ Resume = 0,
18
+ Reconnect = 1,
19
+ Shutdown = 2
19
20
  }
20
21
  interface ShardOptions {
21
- total: number;
22
- token: string;
23
- intents: number | bigint;
24
- gateway: {
25
- baseURL: string;
26
- version: number;
27
- };
22
+ total: number;
23
+ token: string;
24
+ intents: number | bigint;
25
+ gateway: {
26
+ baseURL: string;
27
+ version: number;
28
+ };
28
29
  }
29
30
  interface ShardEvents {
30
- ready: [data: GatewayReadyDispatchData];
31
- disconnect: [code: number];
32
- resume: [];
33
- error: [error: Error];
34
- debug: [message: string];
35
- raw: [payload: GatewayReceivePayload];
36
- dispatch: [payload: GatewayDispatchPayload];
37
- needIdentify: [];
31
+ ready: [data: GatewayReadyDispatchData];
32
+ disconnect: [code: number];
33
+ resume: [];
34
+ error: [error: Error];
35
+ debug: [message: string];
36
+ raw: [payload: GatewayReceivePayload];
37
+ dispatch: [payload: GatewayDispatchPayload];
38
+ needIdentify: [];
38
39
  }
39
40
  declare class Shard extends EventEmitter<ShardEvents> {
40
- #private;
41
- readonly id: number;
42
- readonly options: ShardOptions;
43
- constructor(id: number, options: ShardOptions);
44
- get state(): ShardState;
45
- get latency(): number;
46
- get resumable(): boolean;
47
- connect(): Promise<void>;
48
- disconnect(code: number): Promise<void>;
49
- resume(): void;
50
- identify(): void;
51
- send(payload: GatewaySendPayload): void;
52
- sendHeartbeat(): void;
53
- }
54
-
41
+ #private;
42
+ readonly id: number;
43
+ readonly options: ShardOptions;
44
+ constructor(id: number, options: ShardOptions);
45
+ get state(): ShardState;
46
+ get latency(): number;
47
+ get resumable(): boolean;
48
+ connect(): Promise<void>;
49
+ disconnect(code: number): Promise<void>;
50
+ resume(): void;
51
+ identify(): void;
52
+ send(payload: GatewaySendPayload): void;
53
+ sendHeartbeat(): void;
54
+ }
55
+ //#endregion
56
+ //#region src/lib/cluster/Cluster.d.ts
55
57
  interface ClusterOptions {
56
- token: string;
57
- intents: bigint | number;
58
- shards: number[];
59
- total: number;
60
- gateway: {
61
- baseURL: string;
62
- version: number;
63
- };
58
+ token: string;
59
+ intents: bigint | number;
60
+ shards: number[];
61
+ total: number;
62
+ gateway: {
63
+ baseURL: string;
64
+ version: number;
65
+ };
64
66
  }
65
67
  interface ClusterEvents {
66
- shardAdd: [id: number];
67
- shardReady: [id: number];
68
- shardDisconnect: [id: number, code: number];
69
- shardResume: [id: number];
70
- shardError: [id: number, error: Error];
71
- needIdentify: [id: number];
72
- debug: [message: string];
73
- dispatch: [shardId: number, payload: GatewayDispatchPayload];
74
- raw: [shardId: number, payload: GatewayReceivePayload];
75
- ready: [];
76
- error: [error: Error];
68
+ shardAdd: [id: number];
69
+ shardReady: [id: number];
70
+ shardDisconnect: [id: number, code: number];
71
+ shardResume: [id: number];
72
+ shardError: [id: number, error: Error];
73
+ needIdentify: [id: number];
74
+ debug: [message: string];
75
+ dispatch: [shardId: number, payload: GatewayDispatchPayload];
76
+ raw: [shardId: number, payload: GatewayReceivePayload];
77
+ ready: [];
78
+ error: [error: Error];
77
79
  }
78
80
  declare class Cluster extends EventEmitter<ClusterEvents> {
79
- #private;
80
- readonly id: number;
81
- readonly options: ClusterOptions;
82
- readonly shards: Collection<number, Shard>;
83
- constructor(id: number, options: ClusterOptions);
84
- get size(): number;
85
- get ready(): boolean;
86
- spawn(): Promise<void>;
87
- shutdown(code?: number): Promise<void>;
88
- broadcast(fn: (shard: Shard) => void): void;
89
- send(payload: GatewaySendPayload): void;
90
- send(shardId: number, payload: GatewaySendPayload): void;
91
- }
92
-
81
+ #private;
82
+ readonly id: number;
83
+ readonly options: ClusterOptions;
84
+ readonly shards: Collection<number, Shard>;
85
+ constructor(id: number, options: ClusterOptions);
86
+ get size(): number;
87
+ get ready(): boolean;
88
+ spawn(): Promise<void>;
89
+ shutdown(code?: number): Promise<void>;
90
+ broadcast(fn: (shard: Shard) => void): void;
91
+ send(payload: GatewaySendPayload): void;
92
+ send(shardId: number, payload: GatewaySendPayload): void;
93
+ }
94
+ //#endregion
95
+ //#region src/lib/ShardingManager.d.ts
93
96
  interface ShardingManagerOptions {
94
- token: string;
95
- intents: bigint | number;
96
- totalShards?: number | "auto";
97
- shardsPerCluster?: number;
97
+ token: string;
98
+ intents: bigint | number;
99
+ totalShards?: number | "auto";
100
+ shardsPerCluster?: number;
98
101
  }
99
102
  interface ShardingManagerEvents {
100
- shardAdd: [cluster: ClusterProcess, shardId: number];
101
- shardReady: [cluster: ClusterProcess, shardId: number];
102
- shardDisconnect: [cluster: ClusterProcess, shardId: number, code: number];
103
- shardResume: [cluster: ClusterProcess, shardId: number];
104
- shardError: [cluster: ClusterProcess, shardId: number, error: Error];
105
- clusterCreate: [cluster: ClusterProcess];
106
- clusterReady: [cluster: ClusterProcess];
107
- clusterExit: [cluster: ClusterProcess, code: number | null];
108
- clusterError: [cluster: ClusterProcess, error: Error];
109
- dispatch: [cluster: ClusterProcess, shardId: number, payload: GatewayDispatchPayload];
110
- raw: [cluster: ClusterProcess, shardId: number, payload: GatewayReceivePayload];
111
- debug: [message: string];
112
- ready: [];
103
+ shardAdd: [cluster: ClusterProcess, shardId: number];
104
+ shardReady: [cluster: ClusterProcess, shardId: number];
105
+ shardDisconnect: [cluster: ClusterProcess, shardId: number, code: number];
106
+ shardResume: [cluster: ClusterProcess, shardId: number];
107
+ shardError: [cluster: ClusterProcess, shardId: number, error: Error];
108
+ clusterCreate: [cluster: ClusterProcess];
109
+ clusterReady: [cluster: ClusterProcess];
110
+ clusterExit: [cluster: ClusterProcess, code: number | null];
111
+ clusterError: [cluster: ClusterProcess, error: Error];
112
+ dispatch: [cluster: ClusterProcess, shardId: number, payload: GatewayDispatchPayload];
113
+ raw: [cluster: ClusterProcess, shardId: number, payload: GatewayReceivePayload];
114
+ debug: [message: string];
115
+ ready: [];
113
116
  }
114
117
  declare class ShardingManager extends EventEmitter<ShardingManagerEvents> {
115
- #private;
116
- readonly clusters: Collection<number, ClusterProcess>;
117
- readonly options: Required<ShardingManagerOptions>;
118
- readonly rest: REST | RESTProxy;
119
- constructor(options: ShardingManagerOptions, rest?: REST | RESTProxy);
120
- get totalClusters(): number;
121
- get totalShards(): number;
122
- get ready(): boolean;
123
- spawn(): Promise<void>;
124
- kill(signal?: NodeJS.Signals): Promise<void>;
125
- broadcast(payload: GatewaySendPayload): void;
126
- broadcastEval<T>(fn: (cluster: Cluster) => T | Promise<T>): Promise<EvalResult<T>[]>;
127
- protected requestIdentify(cluster: ClusterProcess, shardId: number): void;
128
- }
129
-
118
+ #private;
119
+ readonly clusters: Collection<number, ClusterProcess>;
120
+ readonly options: Required<ShardingManagerOptions>;
121
+ readonly rest: RESTLike;
122
+ constructor(options: ShardingManagerOptions, rest?: RESTLike);
123
+ get totalClusters(): number;
124
+ get totalShards(): number;
125
+ get ready(): boolean;
126
+ spawn(): Promise<void>;
127
+ kill(signal?: NodeJS.Signals): Promise<void>;
128
+ broadcast(payload: GatewaySendPayload): void;
129
+ broadcastEval<T>(fn: (cluster: Cluster) => T | Promise<T>): Promise<EvalResult<T>[]>;
130
+ send(shardId: number, payload: GatewaySendPayload): void;
131
+ protected requestIdentify(cluster: ClusterProcess, shardId: number): void;
132
+ }
133
+ //#endregion
134
+ //#region src/lib/cluster/ClusterProcess.d.ts
130
135
  type ClusterIPCDispatchPayload<E extends keyof ClusterEvents = keyof ClusterEvents> = {
131
- op: "dispatch";
132
- t: E;
133
- d: ClusterEvents[E];
136
+ op: "dispatch";
137
+ t: E;
138
+ d: ClusterEvents[E];
134
139
  };
135
140
  interface ClusterIPCIdentifyPayload {
136
- op: "identify";
137
- d: number;
141
+ op: "identify";
142
+ d: number;
138
143
  }
139
144
  interface ClusterIPCGatewaySendPayload {
140
- op: "send";
141
- d: {
142
- shardId?: number;
143
- data: GatewaySendPayload;
144
- };
145
+ op: "send";
146
+ d: {
147
+ shardId?: number;
148
+ data: GatewaySendPayload;
149
+ };
145
150
  }
146
151
  interface ClusterIPCEvalRequestPayload {
147
- op: "eval";
148
- d: {
149
- nonce: string;
150
- script: string;
151
- };
152
+ op: "eval";
153
+ d: {
154
+ nonce: string;
155
+ script: string;
156
+ };
152
157
  }
153
158
  interface ClusterIPCEvalResponsePayload {
154
- op: "evalResponse";
155
- d: {
156
- nonce: string;
157
- success: boolean;
158
- result: unknown;
159
- error?: string;
160
- };
159
+ op: "evalResponse";
160
+ d: {
161
+ nonce: string;
162
+ success: boolean;
163
+ result: unknown;
164
+ error?: string;
165
+ };
161
166
  }
162
167
  type ClusterIPCPayload = ClusterIPCDispatchPayload | ClusterIPCIdentifyPayload | ClusterIPCGatewaySendPayload | ClusterIPCEvalRequestPayload | ClusterIPCEvalResponsePayload;
163
168
  interface EvalResult<T> {
164
- /**
165
- * Whether the evaluation was successful
166
- */
167
- success: boolean;
168
- /**
169
- * The result of the evaluation if successful
170
- */
171
- data?: T;
172
- /**
173
- * The error if evaluation failed
174
- */
175
- error?: Error;
176
- /**
177
- * The cluster process that executed the evaluation
178
- */
179
- cluster: ClusterProcess;
169
+ /**
170
+ * Whether the evaluation was successful
171
+ */
172
+ success: boolean;
173
+ /**
174
+ * The result of the evaluation if successful
175
+ */
176
+ data?: T;
177
+ /**
178
+ * The error if evaluation failed
179
+ */
180
+ error?: Error;
181
+ /**
182
+ * The cluster process that executed the evaluation
183
+ */
184
+ cluster: ClusterProcess;
180
185
  }
181
186
  interface ClusterProcessOptions {
182
- env?: NodeJS.ProcessEnv;
183
- execArgv?: string[];
187
+ env?: NodeJS.ProcessEnv;
188
+ execArgv?: string[];
184
189
  }
185
190
  declare class ClusterProcess extends EventEmitter<ClusterEvents> {
186
- #private;
187
- readonly manager: ShardingManager;
188
- readonly id: number;
189
- readonly process: ChildProcess;
190
- constructor(manager: ShardingManager, id: number, options?: ClusterProcessOptions);
191
- get killed(): boolean;
192
- kill(signal?: NodeJS.Signals): void;
193
- eval<T, C = unknown>(fn: (cluster: Cluster, ctx: C) => T | Promise<T>, ctx?: C): Promise<EvalResult<T>>;
194
- send(payload: GatewaySendPayload): void;
195
- send(shardId: number, payload: GatewaySendPayload): void;
196
- sendIPC(message: ClusterIPCPayload): void;
197
- identifyShard(id: number): void;
198
- static bindProcess(cluster: Cluster): void;
199
- }
200
-
201
- export { Cluster, type ClusterEvents, type ClusterIPCDispatchPayload, type ClusterIPCEvalRequestPayload, type ClusterIPCEvalResponsePayload, type ClusterIPCGatewaySendPayload, type ClusterIPCIdentifyPayload, type ClusterIPCPayload, type ClusterOptions, ClusterProcess, type ClusterProcessOptions, type EvalResult, Shard, type ShardEvents, type ShardOptions, ShardState, ShardStrategy, ShardingManager, type ShardingManagerEvents, type ShardingManagerOptions };
191
+ #private;
192
+ readonly manager: ShardingManager;
193
+ readonly id: number;
194
+ readonly process: ChildProcess;
195
+ constructor(manager: ShardingManager, id: number, options?: ClusterProcessOptions);
196
+ get shards(): Set<number>;
197
+ get killed(): boolean;
198
+ kill(signal?: NodeJS.Signals): void;
199
+ eval<T, C = unknown>(fn: (cluster: Cluster, ctx: C) => T | Promise<T>, ctx?: C): Promise<EvalResult<T>>;
200
+ send(payload: GatewaySendPayload): void;
201
+ send(shardId: number, payload: GatewaySendPayload): void;
202
+ sendIPC(message: ClusterIPCPayload): void;
203
+ identifyShard(id: number): void;
204
+ static bindProcess(cluster: Cluster): void;
205
+ }
206
+ //#endregion
207
+ export { Cluster, ClusterEvents, ClusterIPCDispatchPayload, ClusterIPCEvalRequestPayload, ClusterIPCEvalResponsePayload, ClusterIPCGatewaySendPayload, ClusterIPCIdentifyPayload, ClusterIPCPayload, ClusterOptions, ClusterProcess, ClusterProcessOptions, EvalResult, Shard, ShardEvents, ShardOptions, ShardState, ShardStrategy, ShardingManager, ShardingManagerEvents, ShardingManagerOptions };
208
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../src/lib/Shard.ts","../src/lib/cluster/Cluster.ts","../src/lib/ShardingManager.ts","../src/lib/cluster/ClusterProcess.ts"],"mappings":";;;;;;;aAqBY,UAAA;EACX,IAAA;EACA,UAAA;EACA,KAAA;EACA,QAAA;EACA,aAAA;EACA,YAAA;AAAA;AAAA,aAGW,aAAA;EACX,MAAA;EACA,SAAA;EACA,QAAA;AAAA;AAAA,UAGgB,YAAA;EAChB,KAAA;EACA,KAAA;EACA,OAAA;EACA,OAAA;IACC,OAAA;IACA,OAAA;EAAA;AAAA;AAAA,UAIe,WAAA;EAChB,KAAA,GAAQ,IAAA,EAAM,wBAAA;EACd,UAAA,GAAa,IAAA;EACb,MAAA;EACA,KAAA,GAAQ,KAAA,EAAO,KAAA;EACf,KAAA,GAAQ,OAAA;EACR,GAAA,GAAM,OAAA,EAAS,qBAAA;EACf,QAAA,GAAW,OAAA,EAAS,sBAAA;EACpB,Y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AIV,MAAA,CAAA;EAIJ,IAAA,CAAK,MAAA,GAAQ,MAAA,CAAO,OAAA;EAad,IAAA,gBAAA,CAAqB,EAAA,GAAK,OAAA,EAAS,OAAA,EAAS,GAAA,EAAK,CAAA,KAAM,CAAA,GAAI,OAAA,CAAQ,CAAA,GAAI,GAAA,GAAM,CAAA,GAAI,OAAA,CAAQ,UAAA,CAAW,CAAA;EAkC1G,IAAA,CAAK,OAAA,EAAS,kBAAA;EACd,IAAA,CAAK,OAAA,UAAiB,OAAA,EAAS,kBAAA;EAY/B,OAAA,CAAQ,OAAA,EAAS,iBAAA;EAgBjB,aAAA,CAAc,EAAA;EAAA,OA4FP,WAAA,CAAY,OAAA,EAAS,OAAA;AAAA"}
@@ -0,0 +1,208 @@
1
+ import EventEmitter from "node:events";
2
+ import { GatewayDispatchPayload, GatewayReadyDispatchData, GatewayReceivePayload, GatewaySendPayload } from "discord-api-types/v10";
3
+ import { ChildProcess } from "node:child_process";
4
+ import { Collection } from "@discordjs/collection";
5
+ import { RESTLike } from "@bakit/rest";
6
+
7
+ //#region src/lib/Shard.d.ts
8
+ declare enum ShardState {
9
+ Idle = 0,
10
+ Connecting = 1,
11
+ Ready = 2,
12
+ Resuming = 3,
13
+ Disconnecting = 4,
14
+ Disconnected = 5
15
+ }
16
+ declare enum ShardStrategy {
17
+ Resume = 0,
18
+ Reconnect = 1,
19
+ Shutdown = 2
20
+ }
21
+ interface ShardOptions {
22
+ total: number;
23
+ token: string;
24
+ intents: number | bigint;
25
+ gateway: {
26
+ baseURL: string;
27
+ version: number;
28
+ };
29
+ }
30
+ interface ShardEvents {
31
+ ready: [data: GatewayReadyDispatchData];
32
+ disconnect: [code: number];
33
+ resume: [];
34
+ error: [error: Error];
35
+ debug: [message: string];
36
+ raw: [payload: GatewayReceivePayload];
37
+ dispatch: [payload: GatewayDispatchPayload];
38
+ needIdentify: [];
39
+ }
40
+ declare class Shard extends EventEmitter<ShardEvents> {
41
+ #private;
42
+ readonly id: number;
43
+ readonly options: ShardOptions;
44
+ constructor(id: number, options: ShardOptions);
45
+ get state(): ShardState;
46
+ get latency(): number;
47
+ get resumable(): boolean;
48
+ connect(): Promise<void>;
49
+ disconnect(code: number): Promise<void>;
50
+ resume(): void;
51
+ identify(): void;
52
+ send(payload: GatewaySendPayload): void;
53
+ sendHeartbeat(): void;
54
+ }
55
+ //#endregion
56
+ //#region src/lib/cluster/Cluster.d.ts
57
+ interface ClusterOptions {
58
+ token: string;
59
+ intents: bigint | number;
60
+ shards: number[];
61
+ total: number;
62
+ gateway: {
63
+ baseURL: string;
64
+ version: number;
65
+ };
66
+ }
67
+ interface ClusterEvents {
68
+ shardAdd: [id: number];
69
+ shardReady: [id: number];
70
+ shardDisconnect: [id: number, code: number];
71
+ shardResume: [id: number];
72
+ shardError: [id: number, error: Error];
73
+ needIdentify: [id: number];
74
+ debug: [message: string];
75
+ dispatch: [shardId: number, payload: GatewayDispatchPayload];
76
+ raw: [shardId: number, payload: GatewayReceivePayload];
77
+ ready: [];
78
+ error: [error: Error];
79
+ }
80
+ declare class Cluster extends EventEmitter<ClusterEvents> {
81
+ #private;
82
+ readonly id: number;
83
+ readonly options: ClusterOptions;
84
+ readonly shards: Collection<number, Shard>;
85
+ constructor(id: number, options: ClusterOptions);
86
+ get size(): number;
87
+ get ready(): boolean;
88
+ spawn(): Promise<void>;
89
+ shutdown(code?: number): Promise<void>;
90
+ broadcast(fn: (shard: Shard) => void): void;
91
+ send(payload: GatewaySendPayload): void;
92
+ send(shardId: number, payload: GatewaySendPayload): void;
93
+ }
94
+ //#endregion
95
+ //#region src/lib/ShardingManager.d.ts
96
+ interface ShardingManagerOptions {
97
+ token: string;
98
+ intents: bigint | number;
99
+ totalShards?: number | "auto";
100
+ shardsPerCluster?: number;
101
+ }
102
+ interface ShardingManagerEvents {
103
+ shardAdd: [cluster: ClusterProcess, shardId: number];
104
+ shardReady: [cluster: ClusterProcess, shardId: number];
105
+ shardDisconnect: [cluster: ClusterProcess, shardId: number, code: number];
106
+ shardResume: [cluster: ClusterProcess, shardId: number];
107
+ shardError: [cluster: ClusterProcess, shardId: number, error: Error];
108
+ clusterCreate: [cluster: ClusterProcess];
109
+ clusterReady: [cluster: ClusterProcess];
110
+ clusterExit: [cluster: ClusterProcess, code: number | null];
111
+ clusterError: [cluster: ClusterProcess, error: Error];
112
+ dispatch: [cluster: ClusterProcess, shardId: number, payload: GatewayDispatchPayload];
113
+ raw: [cluster: ClusterProcess, shardId: number, payload: GatewayReceivePayload];
114
+ debug: [message: string];
115
+ ready: [];
116
+ }
117
+ declare class ShardingManager extends EventEmitter<ShardingManagerEvents> {
118
+ #private;
119
+ readonly clusters: Collection<number, ClusterProcess>;
120
+ readonly options: Required<ShardingManagerOptions>;
121
+ readonly rest: RESTLike;
122
+ constructor(options: ShardingManagerOptions, rest?: RESTLike);
123
+ get totalClusters(): number;
124
+ get totalShards(): number;
125
+ get ready(): boolean;
126
+ spawn(): Promise<void>;
127
+ kill(signal?: NodeJS.Signals): Promise<void>;
128
+ broadcast(payload: GatewaySendPayload): void;
129
+ broadcastEval<T>(fn: (cluster: Cluster) => T | Promise<T>): Promise<EvalResult<T>[]>;
130
+ send(shardId: number, payload: GatewaySendPayload): void;
131
+ protected requestIdentify(cluster: ClusterProcess, shardId: number): void;
132
+ }
133
+ //#endregion
134
+ //#region src/lib/cluster/ClusterProcess.d.ts
135
+ type ClusterIPCDispatchPayload<E extends keyof ClusterEvents = keyof ClusterEvents> = {
136
+ op: "dispatch";
137
+ t: E;
138
+ d: ClusterEvents[E];
139
+ };
140
+ interface ClusterIPCIdentifyPayload {
141
+ op: "identify";
142
+ d: number;
143
+ }
144
+ interface ClusterIPCGatewaySendPayload {
145
+ op: "send";
146
+ d: {
147
+ shardId?: number;
148
+ data: GatewaySendPayload;
149
+ };
150
+ }
151
+ interface ClusterIPCEvalRequestPayload {
152
+ op: "eval";
153
+ d: {
154
+ nonce: string;
155
+ script: string;
156
+ };
157
+ }
158
+ interface ClusterIPCEvalResponsePayload {
159
+ op: "evalResponse";
160
+ d: {
161
+ nonce: string;
162
+ success: boolean;
163
+ result: unknown;
164
+ error?: string;
165
+ };
166
+ }
167
+ type ClusterIPCPayload = ClusterIPCDispatchPayload | ClusterIPCIdentifyPayload | ClusterIPCGatewaySendPayload | ClusterIPCEvalRequestPayload | ClusterIPCEvalResponsePayload;
168
+ interface EvalResult<T> {
169
+ /**
170
+ * Whether the evaluation was successful
171
+ */
172
+ success: boolean;
173
+ /**
174
+ * The result of the evaluation if successful
175
+ */
176
+ data?: T;
177
+ /**
178
+ * The error if evaluation failed
179
+ */
180
+ error?: Error;
181
+ /**
182
+ * The cluster process that executed the evaluation
183
+ */
184
+ cluster: ClusterProcess;
185
+ }
186
+ interface ClusterProcessOptions {
187
+ env?: NodeJS.ProcessEnv;
188
+ execArgv?: string[];
189
+ }
190
+ declare class ClusterProcess extends EventEmitter<ClusterEvents> {
191
+ #private;
192
+ readonly manager: ShardingManager;
193
+ readonly id: number;
194
+ readonly process: ChildProcess;
195
+ constructor(manager: ShardingManager, id: number, options?: ClusterProcessOptions);
196
+ get shards(): Set<number>;
197
+ get killed(): boolean;
198
+ kill(signal?: NodeJS.Signals): void;
199
+ eval<T, C = unknown>(fn: (cluster: Cluster, ctx: C) => T | Promise<T>, ctx?: C): Promise<EvalResult<T>>;
200
+ send(payload: GatewaySendPayload): void;
201
+ send(shardId: number, payload: GatewaySendPayload): void;
202
+ sendIPC(message: ClusterIPCPayload): void;
203
+ identifyShard(id: number): void;
204
+ static bindProcess(cluster: Cluster): void;
205
+ }
206
+ //#endregion
207
+ export { Cluster, ClusterEvents, ClusterIPCDispatchPayload, ClusterIPCEvalRequestPayload, ClusterIPCEvalResponsePayload, ClusterIPCGatewaySendPayload, ClusterIPCIdentifyPayload, ClusterIPCPayload, ClusterOptions, ClusterProcess, ClusterProcessOptions, EvalResult, Shard, ShardEvents, ShardOptions, ShardState, ShardStrategy, ShardingManager, ShardingManagerEvents, ShardingManagerOptions };
208
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/lib/Shard.ts","../src/lib/cluster/Cluster.ts","../src/lib/ShardingManager.ts","../src/lib/cluster/ClusterProcess.ts"],"mappings":";;;;;;;aAqBY,UAAA;EACX,IAAA;EACA,UAAA;EACA,KAAA;EACA,QAAA;EACA,aAAA;EACA,YAAA;AAAA;AAAA,aAGW,aAAA;EACX,MAAA;EACA,SAAA;EACA,QAAA;AAAA;AAAA,UAGgB,YAAA;EAChB,KAAA;EACA,KAAA;EACA,OAAA;EACA,OAAA;IACC,OAAA;IACA,OAAA;EAAA;AAAA;AAAA,UAIe,WAAA;EAChB,KAAA,GAAQ,IAAA,EAAM,wBAAA;EACd,UAAA,GAAa,IAAA;EACb,MAAA;EACA,KAAA,GAAQ,KAAA,EAAO,KAAA;EACf,KAAA,GAAQ,OAAA;EACR,GAAA,GAAM,OAAA,EAAS,qBAAA;EACf,QAAA,GAAW,OAAA,EAAS,sBAAA;EACpB,YAAA;AAAA;AAAA,cAGY,KAAA,SAAc,YAAA,CAAa,WAAA;EAAA;WAqBtB,EAAA;EAAA,SACA,OAAA,EAAS,YAAA;cADT,EAAA,UACA,OAAA,EAAS,YAAA;EAAA,IAKf,KAAA,CAAA,GAAK,UAAA;EAAA,IAIL,OAAA,CAAA;EAAA,IAQA,SAAA,CAAA;EAQE,OAAA,CAAA,GAAW,OAAA;EA2BjB,UAAA,CAAW,IAAA,WAAY,OAAA;EAkBvB,MAAA,CAAA;EAiBA,QAAA,CAAA;EAgBA,IAAA,CAAK,OAAA,EAAS,kBAAA;EAMd,aAAA,CAAA;AAAA;;;UCrLS,cAAA;EAChB,KAAA;EACA,OAAA;EACA,MAAA;EACA,KAAA;EACA,OAAA;IACC,OAAA;IACA,OAAA;EAAA;AAAA;AAAA,UAIe,aAAA;EAChB,QAAA,GAAW,EAAA;EACX,UAAA,GAAa,EAAA;EACb,eAAA,GAAkB,EAAA,UAAY,IAAA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AAAA,UAIe,6BAAA;EAChB,EAAA;EACA,CAAA;IACC,KAAA;IACA,OAAA;IACA,MAAA;IACA,KAAA;EAAA;AAAA;AAAA,KAIU,iBAAA,GACT,yBAAA,GACA,yBAAA,GACA,4BAAA,GACA,4BAAA,GACA,6BAAA;AAAA,UAsBc,UAAA;EHtCR;AAIT;;EGsCC,OAAA;EHrCc;;;EGyCd,IAAA,GAAO,CAAA;EHnCmC;;;EGuC1C,KAAA,GAAQ,KAAA;EH7CM;;;EGiDd,OAAA,EAAS,cAAA;AAAA;AAAA,UAGO,qBAAA;EAChB,GAAA,GAAM,MAAA,CAAO,UAAA;EACb,QAAA;AAAA;AAAA,cAGY,cAAA,SAAuB,YAAA,CAAa,aAAA;EAAA;WAc/B,OAAA,EAAS,eAAA;EAAA,SACT,EAAA;EAAA,SAdD,OAAA,EAAS,YAAA;cAaR,OAAA,EAAS,eAAA,EACT,EAAA,UAChB,OAAA,GAAS,qBAAA;EAAA,IAgBC,MAAA,CAAA,GAAU,GAAA;EAAA,IAIV,MAAA,CAAA;EAIJ,IAAA,CAAK,MAAA,GAAQ,MAAA,CAAO,OAAA;EAad,IAAA,gBAAA,CAAqB,EAAA,GAAK,OAAA,EAAS,OAAA,EAAS,GAAA,EAAK,CAAA,KAAM,CAAA,GAAI,OAAA,CAAQ,CAAA,GAAI,GAAA,GAAM,CAAA,GAAI,OAAA,CAAQ,UAAA,CAAW,CAAA;EAkC1G,IAAA,CAAK,OAAA,EAAS,kBAAA;EACd,IAAA,CAAK,OAAA,UAAiB,OAAA,EAAS,kBAAA;EAY/B,OAAA,CAAQ,OAAA,EAAS,iBAAA;EAgBjB,aAAA,CAAc,EAAA;EAAA,OA4FP,WAAA,CAAY,OAAA,EAAS,OAAA;AAAA"}
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ import e from"node:events";import{constants as t,createInflate as n}from"node:zlib";import{TextDecoder as r}from"node:util";import{randomInt as i,randomUUID as a}from"node:crypto";import o from"ws";import{GatewayCloseCodes as s,GatewayDispatchEvents as c,GatewayOpcodes as l}from"discord-api-types/v10";import{fork as u}from"node:child_process";import{dirname as d,resolve as f}from"node:path";import{fileURLToPath as p}from"node:url";import{isCommonJS as m}from"@bakit/utils";import{Collection as h}from"@discordjs/collection";import g from"p-queue";import{REST as _}from"@bakit/rest";let v=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}({}),y=function(e){return e[e.Resume=0]=`Resume`,e[e.Reconnect=1]=`Reconnect`,e[e.Shutdown=2]=`Shutdown`,e}({});var b=class extends e{#e=v.Idle;#t;#n;#r=new r;#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===y.Resume&&t&&e}async connect(){if(this.#e!==v.Idle&&this.#e!==v.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=v.Disconnecting,this.#m=y.Shutdown,!this.#t){t();return}this.#t.once(`close`,()=>{t()}),this.#t.close(e)})}resume(){this.resumable&&(this.#e=v.Resuming,this.send({op:l.Resume,d:{token:this.options.token,session_id:this.#a,seq:this.#o}}))}identify(){this.send({op:l.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===o.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:l.Heartbeat,d:this.#o??null}),this.#c=Date.now()}#h(){this.#e=v.Connecting,this.#m??=y.Reconnect;let e=new URL(this.#m===y.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 o(e,{perMessageDeflate:!1}),this.#n=n({flush:t.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 n;n=Buffer.isBuffer(e)?e:Array.isArray(e)?Buffer.concat(e):e instanceof ArrayBuffer?Buffer.from(e):Buffer.from(String(e));let r=n.length>=4&&n[n.length-4]===0&&n[n.length-3]===0&&n[n.length-2]===255&&n[n.length-1]===255;this.#n.write(n,e=>{if(e){this.emit(`error`,e);return}r&&this.#n?.flush(t.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(`{`)&&!x(n))return;this.emit(`error`,e),this.#i=[]}}}#v(e){switch(this.emit(`raw`,e),e.op){case l.Dispatch:this.#y(e);break;case l.Hello:this.#C(e.d.heartbeat_interval),this.resumable?this.resume():this.emit(`needIdentify`);break;case l.Heartbeat:this.sendHeartbeat();break;case l.HeartbeatAck:this.#l=Date.now();break;case l.InvalidSession:e.d?this.#m=y.Resume:(this.#m=y.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 l.Reconnect:this.#m=y.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 c.Ready:{let{d:t}=e;this.#e=v.Ready,this.#a=t.session_id,this.#s=t.resume_gateway_url,this.emit(`ready`,t);break}case c.Resumed:this.#e=v.Ready,this.#m=void 0,this.emit(`resume`);break}}#b(e){if(this.#w(),this.#e=v.Disconnected,this.emit(`disconnect`,e),this.#m===y.Shutdown){switch(e){case s.AuthenticationFailed:this.emit(`error`,Error(`Invalid token provided`));break;case s.InvalidIntents:this.emit(`error`,Error(`Invalid intents provided`));break;case s.DisallowedIntents:this.emit(`error`,Error(`Disallowed intents provided`));break}return}else this.#m||=this.#x(e);(this.#m===y.Reconnect||this.#m===y.Resume)&&this.#S()}#x(e){switch(e){case s.AuthenticationFailed:case s.InvalidIntents:case s.DisallowedIntents:return y.Shutdown;case s.InvalidSeq:case s.SessionTimedOut:return y.Reconnect;default:return y.Resume}}#S(e=1e3){this.#p||=setTimeout(()=>{this.#p=void 0,this.#e=v.Idle,this.#h()},e)}#C(e){this.#d&&=(clearInterval(this.#d),void 0),(e<1e3||e>6e4)&&(e=45e3);let t=i(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 x(e){try{return JSON.parse(e),!0}catch{return!1}}const S=3e4,C=d(p(import.meta.url));function w(e){return e.op===`dispatch`}function T(e){return e.op===`identify`}function E(e){return e.op===`send`}function D(e){return e.op===`eval`}function O(e){return e.op===`evalResponse`}var k=class t extends e{process;#e=new Map;#t=new Set;constructor(e,t,n={}){super(),this.manager=e,this.id=t,this.setMaxListeners(0),this.process=u(f(C,m()?`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=a();return new Promise((r,i)=>{let a=setTimeout(()=>{this.#e.delete(n),i(Error(`Eval timed out after ${S}ms`))},S);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(w(e)){this.#i(e);return}if(O(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(e){let n=e.emit.bind(e),r=t=>{process.connected&&process.send?.(t,void 0,void 0,t=>{t&&e.emit(`error`,t)})};e.emit=function(e,...t){let i=n(e,...t);return r({op:`dispatch`,t:e,d:t}),i},process.on(`message`,async n=>{if(T(n)){e.shards.get(n.d)?.identify();return}if(E(n)){n.d.shardId===void 0?e.send(n.d.data):e.send(n.d.shardId,n.d.data);return}if(D(n)){await t.#s(e,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 ${S}ms`))},S)}),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)}})}}},A=class extends e{shards=new h;#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 b(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}`)})}},j=class extends e{clusters=new h;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 _({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 g({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 k(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)})}};export{A as Cluster,k as ClusterProcess,b as Shard,v as ShardState,y as ShardStrategy,j as ShardingManager};
2
+ //# sourceMappingURL=index.mjs.map