Skip to content

Commit

Permalink
chore: lint files
Browse files Browse the repository at this point in the history
  • Loading branch information
0t4u committed Aug 10, 2024
1 parent 0f13f27 commit 1a68248
Show file tree
Hide file tree
Showing 13 changed files with 190 additions and 173 deletions.
18 changes: 9 additions & 9 deletions src/Constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,27 @@ export enum State {
CONNECTED,
RECONNECTING,
DISCONNECTING,
DISCONNECTED
DISCONNECTED,
}

export enum VoiceState {
SESSION_READY,
SESSION_ID_MISSING,
SESSION_ENDPOINT_MISSING,
SESSION_FAILED_UPDATE
SESSION_FAILED_UPDATE,
}

export enum OpCodes {
PLAYER_UPDATE = 'playerUpdate',
STATS = 'stats',
EVENT = 'event',
READY = 'ready'
READY = 'ready',
}

export enum Versions {
REST_VERSION = 4,
WEBSOCKET_VERSION = 4
}
export const Versions = {
REST_VERSION: 4,
WEBSOCKET_VERSION: 4,
};

export const ShoukakuDefaults: Required<ShoukakuOptions> = {
resume: false,
Expand All @@ -43,7 +43,7 @@ export const ShoukakuDefaults: Required<ShoukakuOptions> = {
nodeResolver: (nodes) => [ ...nodes.values() ]
.filter(node => node.state === State.CONNECTED)
.sort((a, b) => a.penalties - b.penalties)
.shift()
.shift(),
};

export const ShoukakuClientInfo = `${Info.name}/${Info.version} (${Info.repository.url})`;
Expand All @@ -53,5 +53,5 @@ export const NodeDefaults: NodeOption = {
url: '',
auth: '',
secure: false,
group: undefined
group: undefined,
};
34 changes: 17 additions & 17 deletions src/Shoukaku.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import { Connector } from './connectors/Connector';
import { Constructor, mergeDefault } from './Utils';
import { Player } from './guild/Player';
import { Rest } from './node/Rest';
import { Connection } from './guild/Connection.js';
import { Connection } from './guild/Connection';

export interface Structures {
/**
* A custom structure that extends the Rest class
*/
rest?: Constructor<Rest>;
rest?: Constructor<Rest>;
/**
* A custom structure that extends the Player class
*/
Expand Down Expand Up @@ -85,7 +85,7 @@ export interface ShoukakuOptions {
/**
* Node Resolver to use if you want to customize it
*/
nodeResolver?: (nodes: Map<string, Node>, connection?: Connection) => Node|undefined;
nodeResolver?: (nodes: Map<string, Node>, connection?: Connection) => Node | undefined;
}

export interface VoiceChannelOptions {
Expand Down Expand Up @@ -134,17 +134,17 @@ export interface ShoukakuEvents {
'raw': [name: string, json: unknown];
}

export declare interface Shoukaku {
export declare interface IShoukaku {
on<K extends keyof ShoukakuEvents>(event: K, listener: (...args: ShoukakuEvents[K]) => void): this;
once<K extends keyof ShoukakuEvents>(event: K, listener: (...args: ShoukakuEvents[K]) => void): this;
off<K extends keyof ShoukakuEvents>(event: K, listener: (...args: ShoukakuEvents[K]) => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: string | symbol, ...args: unknown[]): boolean;
}

/**
* Main Shoukaku class
*/
export class Shoukaku extends EventEmitter {
export class Shoukaku extends EventEmitter implements IShoukaku {
/**
* Discord library connector
*/
Expand All @@ -168,7 +168,7 @@ export class Shoukaku extends EventEmitter {
/**
* Shoukaku instance identifier
*/
public id: string|null;
public id: string | null;
/**
* @param connector A Discord library connector
* @param nodes An array that conforms to the NodeOption type that specifies nodes to connect to
Expand All @@ -187,7 +187,7 @@ export class Shoukaku extends EventEmitter {
constructor(connector: Connector, nodes: NodeOption[], options: ShoukakuOptions = {}) {
super();
this.connector = connector.set(this);
this.options = mergeDefault(ShoukakuDefaults, options);
this.options = mergeDefault<ShoukakuOptions>(ShoukakuDefaults, options);
this.nodes = new Map();
this.connections = new Map();
this.players = new Map();
Expand All @@ -214,13 +214,13 @@ export class Shoukaku extends EventEmitter {
*/
public addNode(options: NodeOption): void {
const node = new Node(this, options);
node.on('debug', (...args) => this.emit('debug', node.name, ...args));
node.on('reconnecting', (...args) => this.emit('reconnecting', node.name, ...args));
node.on('error', (...args) => this.emit('error', node.name, ...args));
node.on('close', (...args) => this.emit('close', node.name, ...args));
node.on('ready', (...args) => this.emit('ready', node.name, ...args));
node.on('raw', (...args) => this.emit('raw', node.name, ...args));
node.once('disconnect', (...args) => this.clean(node, ...args));
node.on('debug', (...args: unknown[]) => this.emit('debug', node.name, ...args));
node.on('reconnecting', (...args: unknown[]) => this.emit('reconnecting', node.name, ...args));
node.on('error', (...args: unknown[]) => this.emit('error', node.name, ...args));
node.on('close', (...args: unknown[]) => this.emit('close', node.name, ...args));
node.on('ready', (...args: unknown[]) => this.emit('ready', node.name, ...args));
node.on('raw', (...args: unknown[]) => this.emit('raw', node.name, ...args));
node.once('disconnect', (...args: unknown[]) => this.clean(node, ...args));
node.connect();
this.nodes.set(node.name, node);
}
Expand Down Expand Up @@ -263,7 +263,7 @@ export class Shoukaku extends EventEmitter {
const player = this.options.structures.player ? new this.options.structures.player(connection.guildId, node) : new Player(connection.guildId, node);
const onUpdate = (state: VoiceState) => {
if (state !== VoiceState.SESSION_READY) return;
player.sendServerUpdate(connection);
void player.sendServerUpdate(connection);
};
await player.sendServerUpdate(connection);
connection.on('connectionUpdate', onUpdate);
Expand Down Expand Up @@ -291,7 +291,7 @@ export class Shoukaku extends EventEmitter {
if (player) {
try {
await player.destroy();
} catch (_) { /* empty */ }
} catch { /* empty */ }
player.clean();
this.players.delete(guildId);
}
Expand Down
5 changes: 3 additions & 2 deletions src/Utils.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
export type Constructor<T> = new (...args: any[]) => T;
export type Constructor<T> = new (...args: unknown[]) => T;

/**
* Merge the default options to user input
* @param def Default options
* @param given User input
* @returns Merged options
*/
export function mergeDefault<T extends { [key: string]: any }>(def: T, given: T): Required<T> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function mergeDefault<T extends Record<string, any>>(def: T, given: T): Required<T> {
if (!given) return def as Required<T>;
const defaultKeys: (keyof T)[] = Object.keys(def);
for (const key in given) {
Expand Down
17 changes: 10 additions & 7 deletions src/connectors/Connector.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */
import { NodeOption, Shoukaku } from '../Shoukaku';
import { NodeDefaults } from '../Constants';
import { mergeDefault } from '../Utils';
import { ServerUpdate, StateUpdatePartial } from '../guild/Connection';

export interface ConnectorMethods {
sendPacket: any;
Expand All @@ -11,8 +13,9 @@ export const AllowedPackets = [ 'VOICE_STATE_UPDATE', 'VOICE_SERVER_UPDATE' ];

export abstract class Connector {
protected readonly client: any;
protected manager: Shoukaku|null;
protected manager: Shoukaku | null;
constructor(client: any) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this.client = client;
this.manager = null;
}
Expand All @@ -28,19 +31,19 @@ export abstract class Connector {
}

protected raw(packet: any): void {
if (!AllowedPackets.includes(packet.t)) return;
const guildId = packet.d.guild_id;
if (!AllowedPackets.includes(packet.t as string)) return;
const guildId = packet.d.guild_id as string;
const connection = this.manager!.connections.get(guildId);
if (!connection) return;
if (packet.t === 'VOICE_SERVER_UPDATE') return connection.setServerUpdate(packet.d);
const userId = packet.d.user_id;
if (packet.t === 'VOICE_SERVER_UPDATE') return connection.setServerUpdate(packet.d as ServerUpdate);
const userId = packet.d.user_id as string;
if (userId !== this.manager!.id) return;
connection.setStateUpdate(packet.d);
connection.setStateUpdate(packet.d as StateUpdatePartial);
}

abstract getId(): string;

abstract sendPacket(shardId: number, payload: any, important: boolean): void;
abstract sendPacket(shardId: number, payload: unknown, important: boolean): void;

abstract listen(nodes: NodeOption[]): void;
}
1 change: 1 addition & 0 deletions src/connectors/libs/DiscordJS.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-explicit-any */
import { Connector } from '../Connector';
import { NodeOption } from '../../Shoukaku';

Expand Down
1 change: 1 addition & 0 deletions src/connectors/libs/Eris.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-explicit-any */
import { Connector } from '../Connector';
import { NodeOption } from '../../Shoukaku';

Expand Down
1 change: 1 addition & 0 deletions src/connectors/libs/OceanicJS.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-explicit-any */
import { Connector } from '../Connector';
import { NodeOption } from '../../Shoukaku';

Expand Down
11 changes: 6 additions & 5 deletions src/connectors/libs/Seyfert.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-explicit-any */
import { Connector } from '../Connector';
import { NodeOption } from '../../Shoukaku';

export class Seyfert extends Connector {
// sendPacket is where your library send packets to Discord Gateway
public sendPacket(shardId: number, payload: any, important: boolean): void {
public sendPacket(shardId: number, payload: unknown, important: boolean): void {
return this.client.gateway.send(shardId, payload);
}
// getId is a getter where the lib stores the client user (the one logged in as a bot) id
Expand All @@ -13,13 +14,13 @@ export class Seyfert extends Connector {
// Listen attaches the event listener to the library you are using
public listen(nodes: NodeOption[]): void {
this.client.events.values.RAW = {
data: { name: "raw" },
data: { name: 'raw' },
run: (packet: any) => {
// Only attach to ready event once, refer to your library for its ready event
if (packet.t === "READY") return this.ready(nodes);
if (packet.t === 'READY') return this.ready(nodes);
// Attach to the raw websocket event, this event must be 1:1 on spec with dapi (most libs implement this)
return this.raw(packet);
}
}
},
};
}
}
2 changes: 1 addition & 1 deletion src/connectors/libs/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export * from './DiscordJS';
export * from './Eris';
export * from './OceanicJS';
export * from "./Seyfert"
export * from './Seyfert';
34 changes: 17 additions & 17 deletions src/guild/Connection.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { EventEmitter, once } from 'events';
import { State, VoiceState } from '../Constants';
import { Shoukaku, VoiceChannelOptions } from '../Shoukaku.js';
import { Shoukaku, VoiceChannelOptions } from '../Shoukaku';

/**
* Represents the partial payload from a stateUpdate event
Expand Down Expand Up @@ -36,8 +36,7 @@ export class Connection extends EventEmitter {
/**
* VoiceChannelId of the connection that is being managed by this instance
*/
public channelId: string|null;

public channelId: string | null;
/**
* ShardId where this connection sends data on
*/
Expand All @@ -53,23 +52,23 @@ export class Connection extends EventEmitter {
/**
* Id of the voice channel where this instance was connected before the current channelId
*/
public lastChannelId: string|null;
public lastChannelId: string | null;
/**
* Id of the currently active voice channel connection
*/
public sessionId: string|null;
public sessionId: string | null;
/**
* Region of connected voice channel
*/
public region: string|null;
public region: string | null;
/**
* Last region of the connected voice channel
*/
public lastRegion: string|null;
public lastRegion: string | null;
/**
* Cached serverUpdate event from Lavalink
*/
public serverUpdate: ServerUpdate|null;
public serverUpdate: ServerUpdate | null;
/**
* Connection state
*/
Expand Down Expand Up @@ -149,15 +148,16 @@ export class Connection extends EventEmitter {
const timeout = setTimeout(() => controller.abort(), this.manager.options.voiceConnectionTimeout * 1000);

try {
const [ status ] = await once(this, 'connectionUpdate', { signal: controller.signal });
const [ status ] = await once(this, 'connectionUpdate', { signal: controller.signal }) as [ VoiceState ];
if (status !== VoiceState.SESSION_READY) {
switch(status) {
switch (status) {
case VoiceState.SESSION_ID_MISSING: throw new Error('The voice connection is not established due to missing session id');
case VoiceState.SESSION_ENDPOINT_MISSING: throw new Error('The voice connection is not established due to missing connection endpoint');
}
}
this.state = State.CONNECTED;
} catch (error: any) {
} catch (e: unknown) {
const error = e as Error;
this.debug(`[Voice] </- [Discord] : Request Connection Failed | Guild: ${this.guildId}`);
if (error.name === 'AbortError')
throw new Error(`The voice connection is not established in ${this.manager.options.voiceConnectionTimeout} seconds`);
Expand All @@ -177,8 +177,8 @@ export class Connection extends EventEmitter {
* @internal
*/
public setStateUpdate({ session_id, channel_id, self_deaf, self_mute }: StateUpdatePartial): void {
this.lastChannelId = this.channelId?.repeat(1) || null;
this.channelId = channel_id || null;
this.lastChannelId = this.channelId?.repeat(1) ?? null;
this.channelId = channel_id ?? null;

if (this.channelId && this.lastChannelId !== this.channelId) {
this.debug(`[Voice] <- [Discord] : Channel Moved | Old Channel: ${this.channelId} Guild: ${this.guildId}`);
Expand All @@ -191,7 +191,7 @@ export class Connection extends EventEmitter {

this.deafened = self_deaf;
this.muted = self_mute;
this.sessionId = session_id || null;
this.sessionId = session_id ?? null;
this.debug(`[Voice] <- [Discord] : State Update Received | Channel: ${this.channelId} Session ID: ${session_id} Guild: ${this.guildId}`);
}

Expand All @@ -209,8 +209,8 @@ export class Connection extends EventEmitter {
return;
}

this.lastRegion = this.region?.repeat(1) || null;
this.region = data.endpoint.split('.').shift()?.replace(/[0-9]/g, '') || null;
this.lastRegion = this.region?.repeat(1) ?? null;
this.region = data.endpoint.split('.').shift()?.replace(/[0-9]/g, '') ?? null;

if (this.region && this.lastRegion !== this.region) {
this.debug(`[Voice] <- [Discord] : Voice Region Moved | Old Region: ${this.lastRegion} New Region: ${this.region} Guild: ${this.guildId}`);
Expand All @@ -234,7 +234,7 @@ export class Connection extends EventEmitter {
* @param data The data to send
* @internal
*/
private send(data: any): void {
private send(data: unknown): void {
this.manager.connector.sendPacket(this.shardId, { op: 4, d: data }, false);
}

Expand Down
Loading

0 comments on commit 1a68248

Please sign in to comment.